diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..5d00b1c14cfd97622ec4ef2a152d296de71bf284 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.md @@ -0,0 +1,24 @@ +# Patch-overlapping Python context before the fix + +## `mlflow/utils/file_utils.py` — `function:make_tarfile` (lines 284-301) + +```python +def make_tarfile(output_filename, source_dir, archive_name, custom_filter=None): + # Helper for filtering out modification timestamps + def _filter_timestamps(tar_info): + tar_info.mtime = 0 + return tar_info if custom_filter is None else custom_filter(tar_info) + + unzipped_filename = tempfile.mktemp() + try: + with tarfile.open(unzipped_filename, "w") as tar: + tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps) + # When gzipping the tar, don't include the tar's filename or modification time in the + # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile) + with gzip.GzipFile( + filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0 + ) as gzipped_tar, open(unzipped_filename, "rb") as tar: + gzipped_tar.write(tar.read()) + finally: + os.remove(unzipped_filename) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f84f01ffa4132072ea7e8d67513a5bacea8c57aa --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.json @@ -0,0 +1,44 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-1a630dd8f83b2e29740d", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-1a630dd8f83b2e29740d", + "project_id": "pyvul__mlflow__mlflow", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "mlflow/utils/file_utils.py" + ], + "patch_units": { + "before": [ + "function:make_tarfile" + ], + "after": [ + "function:make_tarfile" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/19fa596228b1fb4b86e469be665edd7d7dbeb9b0b3686da07895004356b280c4/database", + "cache_key": "19fa596228b1fb4b86e469be665edd7d7dbeb9b0b3686da07895004356b280c4", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/6542ed4eb6001d9e9ca948df5dfeebb2e57bc60e826ac0604d9041b761dd7fcf/database", + "cache_key": "6542ed4eb6001d9e9ca948df5dfeebb2e57bc60e826ac0604d9041b761dd7fcf", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/f5ac0d40fec4af9c5fe47b810e939639e7cc56bf5fc589efd3262e3aab0aae88/database", + "cache_key": "f5ac0d40fec4af9c5fe47b810e939639e7cc56bf5fc589efd3262e3aab0aae88", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-1a630dd8f83b2e29740d/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-1a630dd8f83b2e29740d/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fc600f4cd6d613f1786fa448503a5027f034f45e --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diff @@ -0,0 +1,168 @@ +diff --git a/DESCRIPTION.md b/DESCRIPTION.md +index 5e6684a2..0f626e3a 100644 +--- a/DESCRIPTION.md ++++ b/DESCRIPTION.md +@@ -11,6 +11,7 @@ Source code is also available at: https://github.com/snowflakedb/snowflake-conne + - v2.8.2(November 18,2022) + + - Improved performance of OCSP response caching ++ - Improved performance of regexes used for PUT/GET SQL statement detection + + - v2.8.1(October 30,2022) + +diff --git a/src/snowflake/connector/_sql_util.py b/src/snowflake/connector/_sql_util.py +new file mode 100644 +index 00000000..51a9d090 +--- /dev/null ++++ b/src/snowflake/connector/_sql_util.py +@@ -0,0 +1,52 @@ ++# ++# Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved. ++# ++ ++from __future__ import annotations ++ ++import re ++ ++from .constants import FileTransferType ++ ++COMMENT_START_SQL_RE = re.compile( ++ r""" ++ ^\s*(?: ++ /\*[\w\W]*?\*/ ++ )""", ++ re.VERBOSE, ++) ++ ++PUT_SQL_RE = re.compile(r"^\s*put", flags=re.IGNORECASE) ++GET_SQL_RE = re.compile(r"^\s*get", flags=re.IGNORECASE) ++ ++ ++def remove_starting_comments(sql: str) -> str: ++ """Remove all comments from the start of a SQL statement.""" ++ commentless_sql = sql ++ while True: ++ start_comment = COMMENT_START_SQL_RE.match(commentless_sql) ++ if start_comment is None: ++ break ++ commentless_sql = commentless_sql[start_comment.end() :] ++ return commentless_sql ++ ++ ++def get_file_transfer_type(sql: str) -> FileTransferType | None: ++ """Decide whether a SQL is a file transfer and return its type. ++ ++ None is returned if the SQL isn't a file transfer so that this function can be ++ used in an if-statement. ++ """ ++ commentless_sql = remove_starting_comments(sql) ++ if PUT_SQL_RE.match(commentless_sql): ++ return FileTransferType.PUT ++ elif GET_SQL_RE.match(commentless_sql): ++ return FileTransferType.GET ++ ++ ++def is_put_statement(sql: str) -> bool: ++ return get_file_transfer_type(sql) == FileTransferType.PUT ++ ++ ++def is_get_statement(sql: str) -> bool: ++ return get_file_transfer_type(sql) == FileTransferType.GET +diff --git a/src/snowflake/connector/cursor.py b/src/snowflake/connector/cursor.py +index 2a8089b0..a367a987 100644 +--- a/src/snowflake/connector/cursor.py ++++ b/src/snowflake/connector/cursor.py +@@ -32,6 +32,7 @@ from snowflake.connector.result_batch import create_batches_from_response + from snowflake.connector.result_set import ResultSet + + from . import compat ++from ._sql_util import get_file_transfer_type + from .bind_upload_agent import BindUploadAgent, BindUploadError + from .constants import ( + FIELD_NAME_TO_ID, +@@ -183,8 +184,6 @@ class SnowflakeCursor: + Calling a function is expensive in Python and most of these getters are unnecessary. + """ + +- PUT_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*put\s+", flags=re.IGNORECASE) +- GET_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*get\s+", flags=re.IGNORECASE) + INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE) + COMMENT_SQL_RE = re.compile(r"/\*.*\*/") + INSERT_SQL_VALUES_RE = re.compile( +@@ -202,11 +201,7 @@ class SnowflakeCursor: + None is returned if the SQL isn't a file transfer so that this function can be + used in an if-statement. + """ +- if SnowflakeCursor.PUT_SQL_RE.match(sql): +- return FileTransferType.PUT +- elif SnowflakeCursor.GET_SQL_RE.match(sql): +- return FileTransferType.GET +- return None ++ return get_file_transfer_type(sql) + + def __init__( + self, +@@ -464,9 +459,7 @@ class SnowflakeCursor: + self._is_file_transfer = _is_put_get + else: + # or detect it. +- self._is_file_transfer = self.PUT_SQL_RE.match( +- query +- ) or self.GET_SQL_RE.match(query) ++ self._is_file_transfer = get_file_transfer_type(query) is not None + logger.debug("is_file_transfer: %s", self._is_file_transfer is not None) + + real_timeout = ( +diff --git a/src/snowflake/connector/gcs_storage_client.py b/src/snowflake/connector/gcs_storage_client.py +index b3709be3..e113e459 100644 +--- a/src/snowflake/connector/gcs_storage_client.py ++++ b/src/snowflake/connector/gcs_storage_client.py +@@ -10,6 +10,7 @@ import os + from logging import getLogger + from typing import TYPE_CHECKING, Any, NamedTuple + ++from ._sql_util import is_put_statement + from .compat import quote + from .constants import ( + FILE_PROTOCOL, +@@ -269,9 +270,7 @@ class SnowflakeGCSRestClient(SnowflakeStorageClient): + The local file path. + """ + command = self._command +- if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match( +- command +- ): ++ if FILE_PROTOCOL not in self._command or not is_put_statement(command): + return None + + file_path_begin_index = command.find(FILE_PROTOCOL) +diff --git a/test/unit/test_cursor.py b/test/unit/test_cursor.py +index 37c118c1..bc43a559 100644 +--- a/test/unit/test_cursor.py ++++ b/test/unit/test_cursor.py +@@ -27,9 +27,24 @@ class FakeConnection(SnowflakeConnection): + @pytest.mark.parametrize( + "sql,_type", + ( ++ ("", None), ++ ("select 1;", None), + ("PUT file:///tmp/data/mydata.csv @my_int_stage;", FileTransferType.PUT), + ("GET @%mytable file:///tmp/data/;", FileTransferType.GET), +- ("select 1;", None), ++ ("/**/PUT file:///tmp/data/mydata.csv @my_int_stage;", FileTransferType.PUT), ++ ("/**/ GET @%mytable file:///tmp/data/;", FileTransferType.GET), ++ pytest.param( ++ "/**/\n" ++ + "\t/*/get\t*/\t/**/\n" * 10000 ++ + "\t*/get @~/test.csv file:///tmp\n", ++ None, ++ id="long_incorrect", ++ ), ++ pytest.param( ++ "/**/\n" + "\t/*/put\t*/\t/**/\n" * 10000 + "put file:///tmp/data.csv @~", ++ FileTransferType.PUT, ++ id="long_correct", ++ ), + ), + ) + def test_get_filetransfer_type(sql, _type): diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..ffc908c466193bebd7310d54de1d0c89d8b60bf9 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.md @@ -0,0 +1,1823 @@ +# Patch-overlapping Python context after the fix + +## `src/snowflake/connector/_sql_util.py` — `function:remove_starting_comments` (lines 23-31) + +```python +def remove_starting_comments(sql: str) -> str: + """Remove all comments from the start of a SQL statement.""" + commentless_sql = sql + while True: + start_comment = COMMENT_START_SQL_RE.match(commentless_sql) + if start_comment is None: + break + commentless_sql = commentless_sql[start_comment.end() :] + return commentless_sql +``` + +## `src/snowflake/connector/_sql_util.py` — `function:get_file_transfer_type` (lines 34-44) + +```python +def get_file_transfer_type(sql: str) -> FileTransferType | None: + """Decide whether a SQL is a file transfer and return its type. + + None is returned if the SQL isn't a file transfer so that this function can be + used in an if-statement. + """ + commentless_sql = remove_starting_comments(sql) + if PUT_SQL_RE.match(commentless_sql): + return FileTransferType.PUT + elif GET_SQL_RE.match(commentless_sql): + return FileTransferType.GET +``` + +## `src/snowflake/connector/_sql_util.py` — `function:is_put_statement` (lines 47-48) + +```python +def is_put_statement(sql: str) -> bool: + return get_file_transfer_type(sql) == FileTransferType.PUT +``` + +## `src/snowflake/connector/_sql_util.py` — `function:is_get_statement` (lines 51-52) + +```python +def is_get_statement(sql: str) -> bool: + return get_file_transfer_type(sql) == FileTransferType.GET +``` + +## `src/snowflake/connector/_sql_util.py` — `module:@5` (lines 5-5) + +```python +from __future__ import annotations +``` + +## `src/snowflake/connector/_sql_util.py` — `module:@7` (lines 7-7) + +```python +import re +``` + +## `src/snowflake/connector/_sql_util.py` — `module:@9` (lines 9-9) + +```python +from .constants import FileTransferType +``` + +## `src/snowflake/connector/_sql_util.py` — `module:@11` (lines 11-17) + +```python +COMMENT_START_SQL_RE = re.compile( + r""" + ^\s*(?: + /\*[\w\W]*?\*/ + )""", + re.VERBOSE, +) +``` + +## `src/snowflake/connector/_sql_util.py` — `module:@19` (lines 19-19) + +```python +PUT_SQL_RE = re.compile(r"^\s*put", flags=re.IGNORECASE) +``` + +## `src/snowflake/connector/_sql_util.py` — `module:@20` (lines 20-20) + +```python +GET_SQL_RE = re.compile(r"^\s*get", flags=re.IGNORECASE) +``` + +## `src/snowflake/connector/cursor.py` — `class:SnowflakeCursor` (lines 159-1301) + +```python +class SnowflakeCursor: + """Implementation of Cursor object that is returned from Connection.cursor() method. + + Attributes: + description: A list of namedtuples about metadata for all columns. + rowcount: The number of records updated or selected. If not clear, -1 is returned. + rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be + determined. + sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support. + sqlstate: Snowflake SQL State code. + timestamp_output_format: Snowflake timestamp_output_format for timestamps. + timestamp_ltz_output_format: Snowflake output format for LTZ timestamps. + timestamp_tz_output_format: Snowflake output format for TZ timestamps. + timestamp_ntz_output_format: Snowflake output format for NTZ timestamps. + date_output_format: Snowflake output format for dates. + time_output_format: Snowflake output format for times. + timezone: Snowflake timezone. + binary_output_format: Snowflake output format for binary fields. + arraysize: The default number of rows fetched by fetchmany. + connection: The connection object by which the cursor was created. + errorhandle: The class that handles error handling. + is_file_transfer: Whether, or not the current command is a put, or get. + + TODO: + Most of these attributes have no reason to be properties, we could just store them in public variables. + Calling a function is expensive in Python and most of these getters are unnecessary. + """ + + INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE) + COMMENT_SQL_RE = re.compile(r"/\*.*\*/") + INSERT_SQL_VALUES_RE = re.compile( + r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL + ) + ALTER_SESSION_RE = re.compile( + r"alter\s+session\s+set\s+(.*)=\'?([^\']+)\'?\s*;", + flags=re.IGNORECASE | re.MULTILINE | re.DOTALL, + ) + + @staticmethod + def get_file_transfer_type(sql: str) -> FileTransferType | None: + """Decide whether a SQL is a file transfer and return its type. + + None is returned if the SQL isn't a file transfer so that this function can be + used in an if-statement. + """ + return get_file_transfer_type(sql) + + def __init__( + self, + connection: SnowflakeConnection, + use_dict_result: bool = False, + ) -> None: + """Inits a SnowflakeCursor with a connection. + + Args: + connection: The connection that created this cursor. + use_dict_result: Decides whether to use dict result or not. + """ + self._connection: SnowflakeConnection = connection + + self._errorhandler: Callable[ + [SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]], + None, + ] = Error.default_errorhandler + self.messages: list[ + tuple[type[Error] | type[Exception], dict[str, str | bool]] + ] = [] + self._timebomb: Timer | None = None # must be here for abort_exit method + self._description: list[ResultMetadata] | None = None + self._column_idx_to_name = None + self._sfqid = None + self._sqlstate = None + self._total_rowcount = -1 + self._sequence_counter = -1 + self._request_id = None + self._is_file_transfer = False + + self._timestamp_output_format = None + self._timestamp_ltz_output_format = None + self._timestamp_ntz_output_format = None + self._timestamp_tz_output_format = None + self._date_output_format = None + self._time_output_format = None + self._timezone = None + self._binary_output_format = None + self._result: Iterator[tuple] | Iterator[dict] | None = None + self._result_set: ResultSet | None = None + self._result_state: ResultState = ResultState.DEFAULT + self._use_dict_result = use_dict_result + self.query: str | None = None + # TODO: self._query_result_format could be defined as an enum + self._query_result_format: str | None = None + + self._arraysize = 1 # PEP-0249: defaults to 1 + + self._lock_canceling = Lock() + + self._first_chunk_time = None + + self._log_max_query_length = connection.log_max_query_length + self._inner_cursor: SnowflakeCursor | None = None + self._prefetch_hook = None + self._rownumber: int | None = None + + self.reset() + + def __del__(self) -> None: # pragma: no cover + try: + self.close() + except compat.BASE_EXCEPTION_CLASS as e: + if logger.getEffectiveLevel() <= logging.INFO: + logger.info(e) + + @property + def description(self) -> list[ResultMetadata]: + return self._description + + @property + def rowcount(self): + return self._total_rowcount if self._total_rowcount >= 0 else None + + @property + def rownumber(self): + return self._rownumber if self._rownumber >= 0 else None + + @property + def sfqid(self): + return self._sfqid + + @property + def sqlstate(self): + return self._sqlstate + + @property + def timestamp_output_format(self): + return self._timestamp_output_format + + @property + def timestamp_ltz_output_format(self): + return ( + self._timestamp_ltz_output_format + if self._timestamp_ltz_output_format + else self._timestamp_output_format + ) + + @property + def timestamp_tz_output_format(self): + return ( + self._timestamp_tz_output_format + if self._timestamp_tz_output_format + else self._timestamp_output_format + ) + + @property + def timestamp_ntz_output_format(self): + return ( + self._timestamp_ntz_output_format + if self._timestamp_ntz_output_format + else self._timestamp_output_format + ) + + @property + def date_output_format(self): + return self._date_output_format + + @property + def time_output_format(self): + return self._time_output_format + + @property + def timezone(self): + return self._timezone + + @property + def binary_output_format(self): + return self._binary_output_format + + @property + def arraysize(self): + return self._arraysize + + @arraysize.setter + def arraysize(self, value): + self._arraysize = int(value) + + @property + def connection(self): + return self._connection + + @property + def errorhandler(self): + return self._errorhandler + + @errorhandler.setter + def errorhandler(self, value): + logger.debug("setting errorhandler: %s", value) + if value is None: + raise ProgrammingError("Invalid errorhandler is specified") + self._errorhandler = value + + @property + def is_file_transfer(self): + """Whether the command is PUT or GET.""" + return hasattr(self, "_is_file_transfer") and self._is_file_transfer + + @property + def lastrowid(self) -> None: + """Snowflake does not support lastrowid in which case None should be returned as per PEP249.""" + return None + + def callproc(self, procname: str, args: T = ()) -> T: + """Call a stored procedure. + + Args: + procname: The stored procedure to be called. + args: Parameters to be passed into the stored procedure. + + Returns: + The input parameters. + """ + marker_format = "%s" if self._connection.is_pyformat else "?" + command = ( + f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})" + ) + self.execute(command, args) + return args + + def close(self) -> bool | None: + """Closes the cursor object. + + Returns whether the cursor was closed during this call. + """ + try: + if self.is_closed(): + return False + + with self._lock_canceling: + self.reset(closing=True) + self._connection = None + del self.messages[:] + return True + except Exception: + pass + + def is_closed(self): + return self._connection is None or self._connection.is_closed() + + def _execute_helper( + self, + query: str, + timeout: int = 0, + statement_params: dict[str, str] | None = None, + binding_params: tuple | dict[str, dict[str, str]] = None, + binding_stage: str | None = None, + is_internal: bool = False, + describe_only: bool = False, + _no_results: bool = False, + _is_put_get=None, + _no_retry: bool = False, + ): + del self.messages[:] + + if statement_params is not None and not isinstance(statement_params, dict): + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": "The data type of statement params is invalid. It must be dict.", + "errno": ER_INVALID_VALUE, + }, + ) + + # check if current installation include arrow extension or not, + # if not, we set statement level query result format to be JSON + if not CAN_USE_ARROW_RESULT_FORMAT: + logger.debug("Cannot use arrow result format, fallback to json format") + if statement_params is None: + statement_params = { + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" + } + else: + result_format_val = statement_params.get( + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ) + if str(result_format_val).upper() == "ARROW": + self.check_can_use_arrow_resultset() + elif result_format_val is None: + statement_params[ + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ] = "JSON" + + self._sequence_counter = self._connection._next_sequence_counter() + self._request_id = uuid.uuid4() + + logger.debug(f"Request id: {self._request_id}") + + logger.debug("running query [%s]", self._format_query_for_log(query)) + if _is_put_get is not None: + # if told the query is PUT or GET, use the information + self._is_file_transfer = _is_put_get + else: + # or detect it. + self._is_file_transfer = get_file_transfer_type(query) is not None + logger.debug("is_file_transfer: %s", self._is_file_transfer is not None) + + real_timeout = ( + timeout if timeout and timeout > 0 else self._connection.network_timeout + ) + + if real_timeout is not None: + self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) + self._timebomb.start() + logger.debug("started timebomb in %ss", real_timeout) + else: + self._timebomb = None + + original_sigint = signal.getsignal(signal.SIGINT) + + def interrupt_handler(*_): # pragma: no cover + try: + signal.signal(signal.SIGINT, exit_handler) + except (ValueError, TypeError): + # ignore failures + pass + try: + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + self._timebomb = None + self.__cancel_query(query) + finally: + if original_sigint: + try: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): + # ignore failures + pass + raise KeyboardInterrupt + + try: + if not original_sigint == exit_handler: + signal.signal(signal.SIGINT, interrupt_handler) + except ValueError: # pragma: no cover + logger.debug( + "Failed to set SIGINT handler. " "Not in main thread. Ignored..." + ) + ret = {"data": {}} + try: + ret = self._connection.cmd_query( + query, + self._sequence_counter, + self._request_id, + binding_params=binding_params, + binding_stage=binding_stage, + is_file_transfer=bool(self._is_file_transfer), + statement_params=statement_params, + is_internal=is_internal, + describe_only=describe_only, + _no_results=_no_results, + _no_retry=_no_retry, + ) + finally: + try: + if original_sigint: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): # pragma: no cover + logger.debug( + "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." + ) + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + + if "data" in ret and "parameters" in ret["data"]: + parameters = ret["data"]["parameters"] + # Set session parameters for cursor object + for kv in parameters: + if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_output_format = kv["value"] + if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ntz_output_format = kv["value"] + if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ltz_output_format = kv["value"] + if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_tz_output_format = kv["value"] + if "DATE_OUTPUT_FORMAT" in kv["name"]: + self._date_output_format = kv["value"] + if "TIME_OUTPUT_FORMAT" in kv["name"]: + self._time_output_format = kv["value"] + if "TIMEZONE" in kv["name"]: + self._timezone = kv["value"] + if "BINARY_OUTPUT_FORMAT" in kv["name"]: + self._binary_output_format = kv["value"] + # Set session parameters for connection object + self._connection._update_parameters( + {p["name"]: p["value"] for p in parameters} + ) + + self.query = query + self._sequence_counter = -1 + return ret + + def execute( + self, + command: str, + params: Sequence[Any] | dict[Any, Any] | None = None, + _bind_stage: str | None = None, + timeout: int | None = None, + _exec_async: bool = False, + _no_retry: bool = False, + _do_reset: bool = True, + _put_callback: SnowflakeProgressPercentage = None, + _put_azure_callback: SnowflakeProgressPercentage = None, + _put_callback_output_stream: IO[str] = sys.stdout, + _get_callback: SnowflakeProgressPercentage = None, + _get_azure_callback: SnowflakeProgressPercentage = None, + _get_callback_output_stream: IO[str] = sys.stdout, + _show_progress_bar: bool = True, + _statement_params: dict[str, str] | None = None, + _is_internal: bool = False, + _describe_only: bool = False, + _no_results: bool = False, + _is_put_get: bool | None = None, + _raise_put_get_error: bool = True, + _force_put_overwrite: bool = False, + file_stream: IO[bytes] | None = None, + ) -> SnowflakeCursor | None: + """Executes a command/query. + + Args: + command: The SQL command to be executed. + params: Parameters to be bound into the SQL statement. + _bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files. + timeout: Number of seconds after which to abort the query. + _exec_async: Whether to execute this query asynchronously. + _no_retry: Whether or not to retry on known errors. + _do_reset: Whether or not the result set needs to be reset before executing query. + _put_callback: Function to which GET command should call back to. + _put_azure_callback: Function to which an Azure GET command should call back to. + _put_callback_output_stream: The output stream a PUT command's callback should report on. + _get_callback: Function to which GET command should call back to. + _get_azure_callback: Function to which an Azure GET command should call back to. + _get_callback_output_stream: The output stream a GET command's callback should report on. + _show_progress_bar: Whether or not to show progress bar. + _statement_params: Extra information that should be sent to Snowflake with query. + _is_internal: This flag indicates whether the query is issued internally by the connector. + _describe_only: If true, the query will not be executed but return the schema/description of this query. + _no_results: This flag tells the back-end to not return the result, just fire the query and return the + response returned by Snowflake's server. + _use_ijson: This flag doesn't do anything as ijson support has ended. + _is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise. + _raise_put_get_error: Whether to raise PUT and GET errors. + _force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already + existing file on stage. + file_stream: File-like object to be uploaded with PUT + + Returns: + The cursor itself, or None if some error happened, or the response returned + by Snowflake if the _no_results flag is on. + """ + if _exec_async: + _no_results = True + logger.debug("executing SQL/command") + if self.is_closed(): + Error.errorhandler_wrapper( + self.connection, + self, + InterfaceError, + {"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED}, + ) + + if _do_reset: + self.reset() + command = command.strip(" \t\n\r") if command else None + if not command: + logger.warning("execute: no query is given to execute") + return + + kwargs = { + "timeout": timeout, + "statement_params": _statement_params, + "is_internal": _is_internal, + "describe_only": _describe_only, + "_no_results": _no_results, + "_is_put_get": _is_put_get, + "_no_retry": _no_retry, + } + + if self._connection.is_pyformat: + # pyformat/format paramstyle + # client side binding + processed_params = self._connection._process_params_pyformat(params, self) + # SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement + if params is not None and len(params) == 0: + self._log_telemetry_job_data( + TelemetryField.EMPTY_SEQ_INTERPOLATION, + TelemetryData.TRUE + if self.connection._interpolate_empty_sequences + else TelemetryData.FALSE, + ) + if logger.getEffectiveLevel() <= logging.DEBUG: + logger.debug( + f"binding: [{self._format_query_for_log(command)}] " + f"with input=[{params}], " + f"processed=[{processed_params}]", + ) + if ( + self.connection._interpolate_empty_sequences + and processed_params is not None + ) or ( + not self.connection._interpolate_empty_sequences + and len(processed_params) > 0 + ): + query = command % processed_params + else: + query = command + else: + # qmark and numeric paramstyle + query = command + if _bind_stage: + kwargs["binding_stage"] = _bind_stage + else: + if params is not None and not isinstance(params, (list, tuple)): + errorvalue = { + "msg": f"Binding parameters must be a list: {params}", + "errno": ER_FAILED_PROCESSING_PYFORMAT, + } + Error.errorhandler_wrapper( + self.connection, self, ProgrammingError, errorvalue + ) + + kwargs["binding_params"] = self._connection._process_params_qmarks( + params, self + ) + + m = DESC_TABLE_RE.match(query) + if m: + query1 = f"describe table {m.group(1)}" + if logger.getEffectiveLevel() <= logging.WARNING: + logger.info( + "query was rewritten: org=%s, new=%s", + " ".join(line.strip() for line in query.split("\n")), + query1, + ) + query = query1 + + if logger.getEffectiveLevel() <= logging.INFO: + logger.info("query: [%s]", self._format_query_for_log(query)) + ret = self._execute_helper(query, **kwargs) + self._sfqid = ( + ret["data"]["queryId"] + if "data" in ret and "queryId" in ret["data"] + else None + ) + self._sqlstate = ( + ret["data"]["sqlState"] + if "data" in ret and "sqlState" in ret["data"] + else None + ) + self._first_chunk_time = get_time_millis() + + # if server gives a send time, log the time it took to arrive + if "data" in ret and "sendResultTime" in ret["data"]: + time_consume_first_result = ( + self._first_chunk_time - ret["data"]["sendResultTime"] + ) + self._log_telemetry_job_data( + TelemetryField.TIME_CONSUME_FIRST_RESULT, time_consume_first_result + ) + logger.debug("sfqid: %s", self.sfqid) + + logger.info("query execution done") + if ret["success"]: + logger.debug("SUCCESS") + data = ret["data"] + + logger.debug("PUT OR GET: %s", self.is_file_transfer) + if self.is_file_transfer: + # Decide whether to use the old, or new code path + sf_file_transfer_agent = SnowflakeFileTransferAgent( + self, + query, + ret, + put_callback=_put_callback, + put_azure_callback=_put_azure_callback, + put_callback_output_stream=_put_callback_output_stream, + get_callback=_get_callback, + get_azure_callback=_get_azure_callback, + get_callback_output_stream=_get_callback_output_stream, + show_progress_bar=_show_progress_bar, + raise_put_get_error=_raise_put_get_error, + force_put_overwrite=_force_put_overwrite + or data.get("overwrite", False), + source_from_stream=file_stream, + multipart_threshold=data.get("threshold"), + use_s3_regional_url=self._connection.enable_stage_s3_privatelink_for_us_east_1, + ) + sf_file_transfer_agent.execute() + data = sf_file_transfer_agent.result() + self._total_rowcount = len(data["rowset"]) if "rowset" in data else -1 + m = self.ALTER_SESSION_RE.match(query) + if m: + # session parameters + param = m.group(1).upper() + value = m.group(2) + self._connection.converter.set_parameter(param, value) + + if _exec_async: + self.connection._async_sfqids[self._sfqid] = None + if _no_results: + self._total_rowcount = ( + ret["data"]["total"] + if "data" in ret and "total" in ret["data"] + else -1 + ) + return data + self._init_result_and_meta(data) + else: + self._total_rowcount = ( + ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1 + ) + logger.debug(ret) + err = ret["message"] + code = ret.get("code", -1) + if "data" in ret: + err += ret["data"].get("errorMessage", "") + errvalue = { + "msg": err, + "errno": int(code), + "sqlstate": self._sqlstate, + "sfqid": self._sfqid, + } + is_integrity_error = ( + code == "100072" + ) # NULL result in a non-nullable column + error_class = IntegrityError if is_integrity_error else ProgrammingError + Error.errorhandler_wrapper(self.connection, self, error_class, errvalue) + return self + + def execute_async(self, *args, **kwargs): + """Convenience function to execute a query without waiting for results (asynchronously). + + This function takes the same arguments as execute, please refer to that function + for documentation. + """ + kwargs["_exec_async"] = True + return self.execute(*args, **kwargs) + + def describe(self, *args, **kwargs) -> list[ResultMetadata]: + """Obtain the schema of the result without executing the query. + + This function takes the same arguments as execute, please refer to that function + for documentation. + + Returns: + The schema of the result. + """ + kwargs["_describe_only"] = kwargs["_is_internal"] = True + self.execute(*args, **kwargs) + return self._description + + def _format_query_for_log(self, query): + return self._connection._format_query_for_log(query) + + def _is_dml(self, data): + return ( + "statementTypeId" in data + and int(data["statementTypeId"]) in STATEMENT_TYPE_ID_DML_SET + ) + + def _init_result_and_meta(self, data): + is_dml = self._is_dml(data) + self._query_result_format = data.get("queryResultFormat", "json") + logger.debug("Query result format: %s", self._query_result_format) + + if self._total_rowcount == -1 and not is_dml and data.get("total") is not None: + self._total_rowcount = data["total"] + + self._description: list[ResultMetadata] = [ + ResultMetadata.from_column(col) for col in data["rowtype"] + ] + + result_chunks = create_batches_from_response( + self, self._query_result_format, data, self._description + ) + + if not (is_dml or self.is_file_transfer): + logger.info( + "Number of results in first chunk: %s", result_chunks[0].rowcount + ) + + self._result_set = ResultSet( + self, + result_chunks, + self._connection.client_prefetch_threads, + ) + self._rownumber = -1 + self._result_state = ResultState.VALID + + # don't update the row count when the result is returned from `describe` method + if is_dml and "rowset" in data and len(data["rowset"]) > 0: + updated_rows = 0 + for idx, desc in enumerate(self._description): + if desc[0] in ( + "number of rows updated", + "number of multi-joined rows updated", + "number of rows deleted", + ) or desc[0].startswith("number of rows inserted"): + updated_rows += int(data["rowset"][0][idx]) + if self._total_rowcount == -1: + self._total_rowcount = updated_rows + else: + self._total_rowcount += updated_rows + + def check_can_use_arrow_resultset(self): + global CAN_USE_ARROW_RESULT_FORMAT + + if not CAN_USE_ARROW_RESULT_FORMAT: + if self._connection.application == "SnowSQL": + msg = "Currently SnowSQL doesn't support the result set in Apache Arrow format." + errno = ER_NO_PYARROW_SNOWSQL + else: + msg = "The result set in Apache Arrow format is not supported for the platform." + errno = ER_NO_ARROW_RESULT + + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": msg, + "errno": errno, + }, + ) + + def check_can_use_pandas(self): + if not installed_pandas: + msg = ( + "Optional dependency: 'pandas' is not installed, please see the following link for install " + "instructions: https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#installation" + ) + errno = ER_NO_PYARROW + + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": msg, + "errno": errno, + }, + ) + + def query_result(self, qid): + url = f"/queries/{qid}/result" + ret = self._connection.rest.request(url=url, method="get") + self._sfqid = ( + ret["data"]["queryId"] + if "data" in ret and "queryId" in ret["data"] + else None + ) + self._sqlstate = ( + ret["data"]["sqlState"] + if "data" in ret and "sqlState" in ret["data"] + else None + ) + logger.debug("sfqid=%s", self._sfqid) + + if ret.get("success"): + data = ret.get("data") + self._init_result_and_meta(data) + else: + logger.info("failed") + logger.debug(ret) + err = ret["message"] + code = ret.get("code", -1) + if "data" in ret: + err += ret["data"].get("errorMessage", "") + errvalue = { + "msg": err, + "errno": int(code), + "sqlstate": self._sqlstate, + "sfqid": self._sfqid, + } + Error.errorhandler_wrapper( + self.connection, self, ProgrammingError, errvalue + ) + return self + + def fetch_arrow_batches(self) -> Iterator[Table]: + self.check_can_use_arrow_resultset() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data( + TelemetryField.ARROW_FETCH_BATCHES, TelemetryData.TRUE + ) + return self._result_set._fetch_arrow_batches() + + def fetch_arrow_all(self) -> Table | None: + self.check_can_use_arrow_resultset() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data(TelemetryField.ARROW_FETCH_ALL, TelemetryData.TRUE) + return self._result_set._fetch_arrow_all() + + def fetch_pandas_batches(self, **kwargs) -> Iterator[pandas.DataFrame]: + """Fetches a single Arrow Table.""" + self.check_can_use_pandas() + if self._prefetch_hook is not None: + self._prefetch_hook() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data( + TelemetryField.PANDAS_FETCH_BATCHES, TelemetryData.TRUE + ) + return self._result_set._fetch_pandas_batches(**kwargs) + + def fetch_pandas_all(self, **kwargs) -> pandas.DataFrame: + """Fetch Pandas dataframes in batches, where 'batch' refers to Snowflake Chunk.""" + self.check_can_use_pandas() + if self._prefetch_hook is not None: + self._prefetch_hook() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data( + TelemetryField.PANDAS_FETCH_ALL, TelemetryData.TRUE + ) + return self._result_set._fetch_pandas_all(**kwargs) + + def abort_query(self, qid): + url = f"/queries/{qid}/abort-request" + ret = self._connection.rest.request(url=url, method="post") + return ret.get("success") + + def executemany( + self, + command: str, + seqparams: Sequence[Any] | dict[str, Any], + **kwargs: dict[str, Any], + ) -> SnowflakeCursor: + """Executes a command/query with the given set of parameters sequentially.""" + logger.debug("executing many SQLs/commands") + command = command.strip(" \t\n\r") if command else None + + if not seqparams: + return self + + if self.INSERT_SQL_RE.match(command): + if self._connection.is_pyformat: + logger.debug("rewriting INSERT query") + command_wo_comments = re.sub(self.COMMENT_SQL_RE, "", command) + m = self.INSERT_SQL_VALUES_RE.match(command_wo_comments) + if not m: + Error.errorhandler_wrapper( + self.connection, + self, + InterfaceError, + { + "msg": "Failed to rewrite multi-row insert", + "errno": ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT, + }, + ) + + fmt = m.group(1) + values = [] + for param in seqparams: + logger.debug(f"parameter: {param}") + values.append( + fmt % self._connection._process_params_pyformat(param, self) + ) + command = command.replace(fmt, ",".join(values), 1) + self.execute(command, **kwargs) + return self + else: + logger.debug("bulk insert") + # sanity check + row_size = len(seqparams[0]) + for row in seqparams: + if len(row) != row_size: + error_value = { + "msg": f"Bulk data size don't match. expected: {row_size}, " + f"got: {len(row)}, command: {command}", + "errno": ER_INVALID_VALUE, + } + Error.errorhandler_wrapper( + self.connection, self, InterfaceError, error_value + ) + return self + bind_size = len(seqparams) * row_size + bind_stage = None + if ( + bind_size + > self.connection._session_parameters[ + "CLIENT_STAGE_ARRAY_BINDING_THRESHOLD" + ] + > 0 + ): + # bind stage optimization + try: + rows = self.connection._write_params_to_byte_rows(seqparams) + bind_uploader = BindUploadAgent(self, rows) + bind_uploader.upload() + bind_stage = bind_uploader.stage_path + except BindUploadError: + logger.debug( + "Failed to upload binds to stage, sending binds to " + "Snowflake instead." + ) + binding_param = ( + None if bind_stage else list(map(list, zip(*seqparams))) + ) # transpose + self.execute( + command, params=binding_param, _bind_stage=bind_stage, **kwargs + ) + return self + + self.reset() + for param in seqparams: + self.execute(command, params=param, _do_reset=False, **kwargs) + return self + + def _result_iterator( + self, + ) -> Generator[dict, None, None] | Generator[tuple, None, None]: + """Yields the elements from _result and raises an exception when appropriate.""" + try: + for _next in self._result: + if isinstance(_next, Exception): + Error.errorhandler_wrapper_from_ready_exception( + self._connection, + self, + _next, + ) + self._rownumber += 1 + yield _next + except TypeError as err: + if self._result_state == ResultState.DEFAULT: + raise err + else: + yield None + + def fetchone(self) -> dict | tuple | None: + """Fetches one row.""" + if self._prefetch_hook is not None: + self._prefetch_hook() + if self._result is None and self._result_set is not None: + self._result = iter(self._result_set) + self._result_state = ResultState.VALID + try: + return next(self._result_iterator()) + except StopIteration: + return None + + def fetchmany(self, size=None): + """Fetches the number of specified rows.""" + if size is None: + size = self.arraysize + + if size < 0: + errorvalue = { + "msg": ( + "The number of rows is not zero or " "positive number: {}" + ).format(size), + "errno": ER_NOT_POSITIVE_SIZE, + } + Error.errorhandler_wrapper( + self.connection, self, ProgrammingError, errorvalue + ) + ret = [] + while size > 0: + row = self.fetchone() + if row is None: + break + ret.append(row) + if size is not None: + size -= 1 + + return ret + + def fetchall(self) -> list[tuple] | list[dict]: + """Fetches all of the results.""" + ret = [] + while True: + row = self.fetchone() + if row is None: + break + ret.append(row) + return ret + + def nextset(self): + """Not supported.""" + logger.debug("nop") + return None + + def setinputsizes(self, _): + """Not supported.""" + logger.debug("nop") + + def setoutputsize(self, _, column=None): + """Not supported.""" + del column + logger.debug("nop") + + def scroll(self, value, mode="relative"): + Error.errorhandler_wrapper( + self.connection, + self, + NotSupportedError, + { + "msg": "scroll is not supported.", + "errno": ER_UNSUPPORTED_METHOD, + "sqlstate": SQLSTATE_FEATURE_NOT_SUPPORTED, + }, + ) + + def reset(self, closing=False): + """Resets the result set.""" + # SNOW-647539: Do not erase the rowcount + # information when closing the cursor + if not closing: + self._total_rowcount = -1 + if self._result_state != ResultState.DEFAULT: + self._result_state = ResultState.RESET + if self._result is not None: + self._result = None + if self._inner_cursor is not None: + self._inner_cursor.reset(closing=closing) + self._result = None + self._inner_cursor = None + self._prefetch_hook = None + if not self.connection._reuse_results: + self._result_set = None + + def __iter__(self) -> Iterator[dict] | Iterator[tuple]: + """Iteration over the result set.""" + # set _result if _result_set is not None + if self._result is None and self._result_set is not None: + self._result = iter(self._result_set) + self._result_state = ResultState.VALID + return self._result_iterator() + + def __cancel_query(self, query): + if self._sequence_counter >= 0 and not self.is_closed(): + logger.debug("canceled. %s, request_id: %s", query, self._request_id) + with self._lock_canceling: + self._connection._cancel_query(query, self._request_id) + + def _log_telemetry_job_data( + self, telemetry_field: TelemetryField, value: Any + ) -> None: + """Builds an instance of TelemetryData with the given field and logs it.""" + ts = get_time_millis() + try: + self._connection._log_telemetry( + TelemetryData.from_telemetry_data_dict( + from_dict={ + TelemetryField.KEY_TYPE.value: telemetry_field.value, + TelemetryField.KEY_SFQID.value: self._sfqid, + TelemetryField.KEY_VALUE.value: value, + }, + timestamp=ts, + connection=self._connection, + ) + ) + except AttributeError: + logger.warning( + "Cursor failed to log to telemetry. Connection object may be None.", + exc_info=True, + ) + + def __enter__(self): + """Context manager.""" + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Context manager with commit or rollback.""" + self.close() + + def get_results_from_sfqid(self, sfqid: str): + """Gets the results from previously ran query.""" + + def wait_until_ready(): + """Makes sure query has finished executing and once it has retrieves results.""" + no_data_counter = 0 + retry_pattern_pos = 0 + while True: + status = self.connection.get_query_status(sfqid) + if not self.connection.is_still_running(status): + break + if status == QueryStatus.NO_DATA: # pragma: no cover + no_data_counter += 1 + if no_data_counter > ASYNC_NO_DATA_MAX_RETRY: + raise DatabaseError( + "Cannot retrieve data on the status of this query. No information returned " + "from server for query '{}'" + ) + time.sleep( + 0.5 * ASYNC_RETRY_PATTERN[retry_pattern_pos] + ) # Same wait as JDBC + # If we can advance in ASYNC_RETRY_PATTERN then do so + if retry_pattern_pos < (len(ASYNC_RETRY_PATTERN) - 1): + retry_pattern_pos += 1 + if status != QueryStatus.SUCCESS: + raise DatabaseError( + "Status of query '{}' is {}, results are unavailable".format( + sfqid, status.name + ) + ) + self._inner_cursor.execute(f"select * from table(result_scan('{sfqid}'))") + self._result = self._inner_cursor._result + self._query_result_format = self._inner_cursor._query_result_format + self._total_rowcount = self._inner_cursor._total_rowcount + self._description = self._inner_cursor._description + self._result_set = self._inner_cursor._result_set + self._result_state = ResultState.VALID + self._rownumber = 0 + # Unset this function, so that we don't block anymore + self._prefetch_hook = None + + self.connection.get_query_status_throw_if_error( + sfqid + ) # Trigger an exception if query failed + klass = self.__class__ + self._inner_cursor = klass(self.connection) + self._sfqid = sfqid + self._prefetch_hook = wait_until_ready + + def get_result_batches(self) -> list[ResultBatch] | None: + """Get the previously executed query's ``ResultBatch`` s if available. + + If they are unavailable, in case nothing has been executed yet None will + be returned. + + For a detailed description of ``ResultBatch`` s please see the docstring of: + ``snowflake.connector.result_batches.ResultBatch`` + """ + if self._result_set is None: + return None + self._log_telemetry_job_data( + TelemetryField.GET_PARTITIONS_USED, TelemetryData.TRUE + ) + return self._result_set.batches +``` + +## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor.get_file_transfer_type` (lines 197-204) + +```python + def get_file_transfer_type(sql: str) -> FileTransferType | None: + """Decide whether a SQL is a file transfer and return its type. + + None is returned if the SQL isn't a file transfer so that this function can be + used in an if-statement. + """ + return get_file_transfer_type(sql) +``` + +## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor._execute_helper` (lines 406-560) + +```python + def _execute_helper( + self, + query: str, + timeout: int = 0, + statement_params: dict[str, str] | None = None, + binding_params: tuple | dict[str, dict[str, str]] = None, + binding_stage: str | None = None, + is_internal: bool = False, + describe_only: bool = False, + _no_results: bool = False, + _is_put_get=None, + _no_retry: bool = False, + ): + del self.messages[:] + + if statement_params is not None and not isinstance(statement_params, dict): + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": "The data type of statement params is invalid. It must be dict.", + "errno": ER_INVALID_VALUE, + }, + ) + + # check if current installation include arrow extension or not, + # if not, we set statement level query result format to be JSON + if not CAN_USE_ARROW_RESULT_FORMAT: + logger.debug("Cannot use arrow result format, fallback to json format") + if statement_params is None: + statement_params = { + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" + } + else: + result_format_val = statement_params.get( + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ) + if str(result_format_val).upper() == "ARROW": + self.check_can_use_arrow_resultset() + elif result_format_val is None: + statement_params[ + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ] = "JSON" + + self._sequence_counter = self._connection._next_sequence_counter() + self._request_id = uuid.uuid4() + + logger.debug(f"Request id: {self._request_id}") + + logger.debug("running query [%s]", self._format_query_for_log(query)) + if _is_put_get is not None: + # if told the query is PUT or GET, use the information + self._is_file_transfer = _is_put_get + else: + # or detect it. + self._is_file_transfer = get_file_transfer_type(query) is not None + logger.debug("is_file_transfer: %s", self._is_file_transfer is not None) + + real_timeout = ( + timeout if timeout and timeout > 0 else self._connection.network_timeout + ) + + if real_timeout is not None: + self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) + self._timebomb.start() + logger.debug("started timebomb in %ss", real_timeout) + else: + self._timebomb = None + + original_sigint = signal.getsignal(signal.SIGINT) + + def interrupt_handler(*_): # pragma: no cover + try: + signal.signal(signal.SIGINT, exit_handler) + except (ValueError, TypeError): + # ignore failures + pass + try: + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + self._timebomb = None + self.__cancel_query(query) + finally: + if original_sigint: + try: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): + # ignore failures + pass + raise KeyboardInterrupt + + try: + if not original_sigint == exit_handler: + signal.signal(signal.SIGINT, interrupt_handler) + except ValueError: # pragma: no cover + logger.debug( + "Failed to set SIGINT handler. " "Not in main thread. Ignored..." + ) + ret = {"data": {}} + try: + ret = self._connection.cmd_query( + query, + self._sequence_counter, + self._request_id, + binding_params=binding_params, + binding_stage=binding_stage, + is_file_transfer=bool(self._is_file_transfer), + statement_params=statement_params, + is_internal=is_internal, + describe_only=describe_only, + _no_results=_no_results, + _no_retry=_no_retry, + ) + finally: + try: + if original_sigint: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): # pragma: no cover + logger.debug( + "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." + ) + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + + if "data" in ret and "parameters" in ret["data"]: + parameters = ret["data"]["parameters"] + # Set session parameters for cursor object + for kv in parameters: + if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_output_format = kv["value"] + if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ntz_output_format = kv["value"] + if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ltz_output_format = kv["value"] + if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_tz_output_format = kv["value"] + if "DATE_OUTPUT_FORMAT" in kv["name"]: + self._date_output_format = kv["value"] + if "TIME_OUTPUT_FORMAT" in kv["name"]: + self._time_output_format = kv["value"] + if "TIMEZONE" in kv["name"]: + self._timezone = kv["value"] + if "BINARY_OUTPUT_FORMAT" in kv["name"]: + self._binary_output_format = kv["value"] + # Set session parameters for connection object + self._connection._update_parameters( + {p["name"]: p["value"] for p in parameters} + ) + + self.query = query + self._sequence_counter = -1 + return ret +``` + +## `src/snowflake/connector/cursor.py` — `module:@35` (lines 35-35) + +```python +from ._sql_util import get_file_transfer_type +``` + +## `src/snowflake/connector/gcs_storage_client.py` — `class:SnowflakeGCSRestClient` (lines 48-395) + +```python +class SnowflakeGCSRestClient(SnowflakeStorageClient): + def __init__( + self, + meta: SnowflakeFileMeta, + credentials: StorageCredential, + stage_info: dict[str, Any], + cnx: SnowflakeConnection, + command: str, + use_s3_regional_url=False, + ) -> None: + """Creates a client object with given stage credentials. + + Args: + stage_info: Access credentials and info of a stage. + + Returns: + The client to communicate with GCS. + """ + super().__init__( + meta, stage_info, -1, credentials=credentials, chunked_transfer=False + ) + self.stage_info = stage_info + self._command = command + self.meta = meta + self._cursor = cnx.cursor() + # presigned_url in meta is for downloading + self.presigned_url: str = meta.presigned_url or stage_info.get("presignedUrl") + self.security_token = credentials.creds.get("GCS_ACCESS_TOKEN") + + if self.security_token: + logger.debug(f"len(GCS_ACCESS_TOKEN): {len(self.security_token)}") + else: + logger.debug("No access token received from GS, requesting presigned url") + self._update_presigned_url() + + def _has_expired_token(self, response: requests.Response) -> bool: + return self.security_token and response.status_code == 401 + + def _has_expired_presigned_url(self, response: requests.Response) -> bool: + # Presigned urls can be generated for any xml-api operation + # offered by GCS. Hence the error codes expected are similar + # to xml api. + # https://cloud.google.com/storage/docs/xml-api/reference-status + + presigned_url_expired = ( + not self.security_token + ) and response.status_code == 400 + if presigned_url_expired and self.last_err_is_presigned_url: + logger.debug("Presigned url expiration error two times in a row.") + response.raise_for_status() + self.last_err_is_presigned_url = presigned_url_expired + return presigned_url_expired + + def _upload_chunk(self, chunk_id: int, chunk: bytes) -> None: + meta = self.meta + + content_encoding = "" + if meta.dst_compression_type is not None: + content_encoding = meta.dst_compression_type.name.lower() + + # We set the contentEncoding to blank for GZIP files. We don't + # want GCS to think our gzip files are gzips because it makes + # them download uncompressed, and none of the other providers do + # that. There's essentially no way for us to prevent that + # behavior. Bad Google. + if content_encoding and content_encoding == "gzip": + content_encoding = "" + + gcs_headers = { + HTTP_HEADER_CONTENT_ENCODING: content_encoding, + GCS_METADATA_SFC_DIGEST: meta.sha256_digest, + } + + if self.encryption_metadata: + gcs_headers.update( + { + GCS_METADATA_ENCRYPTIONDATAPROP: json.dumps( + { + "EncryptionMode": "FullBlob", + "WrappedContentKey": { + "KeyId": "symmKey1", + "EncryptedKey": self.encryption_metadata.key, + "Algorithm": "AES_CBC_256", + }, + "EncryptionAgent": { + "Protocol": "1.0", + "EncryptionAlgorithm": "AES_CBC_256", + }, + "ContentEncryptionIV": self.encryption_metadata.iv, + "KeyWrappingMetadata": {"EncryptionLibrary": "Java 5.3.0"}, + } + ), + GCS_METADATA_MATDESC_KEY: self.encryption_metadata.matdesc, + } + ) + + def generate_url_and_rest_args() -> tuple[ + str, dict[str, dict[str | Any, str | None] | bytes] + ]: + if not self.presigned_url: + upload_url = self.generate_file_url( + self.stage_info["location"], meta.dst_file_name.lstrip("/") + ) + access_token = self.security_token + else: + upload_url = self.presigned_url + access_token: str | None = None + if access_token: + gcs_headers.update({"Authorization": f"Bearer {access_token}"}) + rest_args = {"headers": gcs_headers, "data": chunk} + return upload_url, rest_args + + response = self._send_request_with_retry( + "PUT", generate_url_and_rest_args, chunk_id + ) + response.raise_for_status() + meta.gcs_file_header_digest = gcs_headers[GCS_METADATA_SFC_DIGEST] + meta.gcs_file_header_content_length = meta.upload_size + meta.gcs_file_header_encryption_metadata = json.loads( + gcs_headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, "null") + ) + + def download_chunk(self, chunk_id: int) -> None: + meta = self.meta + + def generate_url_and_rest_args() -> tuple[ + str, dict[str, dict[str, str] | bool] + ]: + gcs_headers = {} + if not self.presigned_url: + download_url = self.generate_file_url( + self.stage_info["location"], meta.src_file_name.lstrip("/") + ) + access_token = self.security_token + gcs_headers["Authorization"] = f"Bearer {access_token}" + else: + download_url = self.presigned_url + rest_args = {"headers": gcs_headers, "stream": True} + return download_url, rest_args + + response = self._send_request_with_retry( + "GET", generate_url_and_rest_args, chunk_id + ) + response.raise_for_status() + + self.write_downloaded_chunk(chunk_id, response.content) + + encryption_metadata = None + + if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): + encryptiondata = json.loads( + response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] + ) + + if encryptiondata: + encryption_metadata = EncryptionMetadata( + key=encryptiondata["WrappedContentKey"]["EncryptedKey"], + iv=encryptiondata["ContentEncryptionIV"], + matdesc=response.headers[GCS_METADATA_MATDESC_KEY] + if GCS_METADATA_MATDESC_KEY in response.headers + else None, + ) + + meta.gcs_file_header_digest = response.headers.get(GCS_METADATA_SFC_DIGEST) + meta.gcs_file_header_content_length = len(response.content) + meta.gcs_file_header_encryption_metadata = encryption_metadata + + def finish_download(self) -> None: + super().finish_download() + # Sadly, we can only determine the src file size after we've + # downloaded it, unlike the other cloud providers where the + # metadata can be read beforehand. + self.meta.src_file_size = os.path.getsize(self.intermediate_dst_path) + + def _update_presigned_url(self) -> None: + """Updates the file metas with presigned urls if any. + + Currently only the file metas generated for PUT/GET on a GCP account need the presigned urls. + """ + logger.debug("Updating presigned url") + + # Rewrite the command such that a new PUT call is made for each file + # represented by the regex (if present) separately. This is the only + # way to get the presigned url for that file. + file_path_to_be_replaced = self._get_local_file_path_from_put_command() + + if not file_path_to_be_replaced: + # This prevents GET statements to proceed + return + + # At this point the connector has already figured out and + # validated that the local file exists and has also decided + # upon the destination file name and the compression type. + # The only thing that's left to do is to get the presigned + # url for the destination file. If the command originally + # referred to a single file, then the presigned url got in + # that case is simply ignore, since the file name is not what + # we want. + + # GS only looks at the file name at the end of local file + # path to figure out the remote object name. Hence the prefix + # for local path is not necessary in the reconstructed command. + file_path_to_replace_with = self.meta.dst_file_name + command_with_single_file = self._command + command_with_single_file = command_with_single_file.replace( + file_path_to_be_replaced, file_path_to_replace_with + ) + + logger.debug("getting presigned url for %s", file_path_to_replace_with) + ret = self._cursor._execute_helper(command_with_single_file) + + stage_info = ret.get("data", dict()).get("stageInfo", dict()) + self.meta.presigned_url = stage_info.get("presignedUrl") + self.presigned_url = stage_info.get("presignedUrl") + + def _get_local_file_path_from_put_command(self) -> str | None: + """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita). + + Args: + command: Command to be parsed and get the local file path out of. + + Returns: + The local file path. + """ + command = self._command + if FILE_PROTOCOL not in self._command or not is_put_statement(command): + return None + + file_path_begin_index = command.find(FILE_PROTOCOL) + is_file_path_quoted = command[file_path_begin_index - 1] == "'" + file_path_begin_index += len(FILE_PROTOCOL) + + file_path = "" + + if is_file_path_quoted: + file_path_end_index = command.find("'", file_path_begin_index) + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + else: + index_list = [] + for delimiter in [" ", "\n", ";"]: + index = command.find(delimiter, file_path_begin_index) + if index != -1: + index_list += [index] + + file_path_end_index = min(index_list) if index_list else -1 + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + elif file_path_end_index == -1: + file_path = command[file_path_begin_index:] + + return file_path + + def get_file_header(self, filename: str) -> FileHeader | None: + """Gets the remote file's metadata. + + Args: + filename: Not applicable to GCS. + + Returns: + The file header, with expected properties populated or None, based on how the request goes with the + storage provider. + + Notes: + Sometimes this method is called to verify that the file has indeed been uploaded. In cases of presigned + url, we have no way of verifying that, except with the http status code of 200 which we have already + confirmed and set the meta.result_status = UPLOADED/DOWNLOADED. + """ + meta = self.meta + if ( + meta.result_status == ResultStatus.UPLOADED + or meta.result_status == ResultStatus.DOWNLOADED + ): + return FileHeader( + digest=meta.gcs_file_header_digest, + content_length=meta.gcs_file_header_content_length, + encryption_metadata=meta.gcs_file_header_encryption_metadata, + ) + elif self.presigned_url: + meta.result_status = ResultStatus.NOT_FOUND_FILE + else: + + def generate_url_and_authenticated_headers(): + url = self.generate_file_url( + self.stage_info["location"], filename.lstrip("/") + ) + gcs_headers = {"Authorization": f"Bearer {self.security_token}"} + rest_args = {"headers": gcs_headers} + return url, rest_args + + retry_id = "HEAD" + self.retry_count[retry_id] = 0 + response = self._send_request_with_retry( + "HEAD", generate_url_and_authenticated_headers, retry_id + ) + if response.status_code == 404: + meta.result_status = ResultStatus.NOT_FOUND_FILE + return None + elif response.status_code == 200: + digest = response.headers.get(GCS_METADATA_SFC_DIGEST, None) + content_length = int(response.headers.get("content-length", "0")) + + encryption_metadata = EncryptionMetadata("", "", "") + if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): + encryption_data = json.loads( + response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] + ) + + if encryption_data: + encryption_metadata = EncryptionMetadata( + key=encryption_data["WrappedContentKey"]["EncryptedKey"], + iv=encryption_data["ContentEncryptionIV"], + matdesc=response.headers[GCS_METADATA_MATDESC_KEY] + if GCS_METADATA_MATDESC_KEY in response.headers + else None, + ) + meta.result_status = ResultStatus.UPLOADED + return FileHeader( + digest=digest, + content_length=content_length, + encryption_metadata=encryption_metadata, + ) + response.raise_for_status() + return None + + @staticmethod + def extract_bucket_name_and_path(stage_location: str) -> GcsLocation: + container_name = stage_location + path = "" + + # split stage location as bucket name and path + if "/" in stage_location: + container_name = stage_location[0 : stage_location.index("/")] + path = stage_location[stage_location.index("/") + 1 :] + if path and not path.endswith("/"): + path += "/" + + return GcsLocation(bucket_name=container_name, path=path) + + @staticmethod + def generate_file_url(stage_location: str, filename: str) -> str: + gcs_location = SnowflakeGCSRestClient.extract_bucket_name_and_path( + stage_location + ) + full_file_path = f"{gcs_location.path}{filename}" + return f"https://storage.googleapis.com/{gcs_location.bucket_name}/{quote(full_file_path)}" +``` + +## `src/snowflake/connector/gcs_storage_client.py` — `function:SnowflakeGCSRestClient._get_local_file_path_from_put_command` (lines 263-301) + +```python + def _get_local_file_path_from_put_command(self) -> str | None: + """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita). + + Args: + command: Command to be parsed and get the local file path out of. + + Returns: + The local file path. + """ + command = self._command + if FILE_PROTOCOL not in self._command or not is_put_statement(command): + return None + + file_path_begin_index = command.find(FILE_PROTOCOL) + is_file_path_quoted = command[file_path_begin_index - 1] == "'" + file_path_begin_index += len(FILE_PROTOCOL) + + file_path = "" + + if is_file_path_quoted: + file_path_end_index = command.find("'", file_path_begin_index) + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + else: + index_list = [] + for delimiter in [" ", "\n", ";"]: + index = command.find(delimiter, file_path_begin_index) + if index != -1: + index_list += [index] + + file_path_end_index = min(index_list) if index_list else -1 + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + elif file_path_end_index == -1: + file_path = command[file_path_begin_index:] + + return file_path +``` + +## `src/snowflake/connector/gcs_storage_client.py` — `module:@13` (lines 13-13) + +```python +from ._sql_util import is_put_statement +``` + +## `test/unit/test_cursor.py` — `function:test_get_filetransfer_type` (lines 27-51) + +```python +def test_get_filetransfer_type(sql, _type): + assert SnowflakeCursor.get_file_transfer_type(sql) == _type +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..dccf4278a77a04699c1ea378f097659a0849dbee --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.md @@ -0,0 +1,1755 @@ +# Patch-overlapping Python context before the fix + +## `src/snowflake/connector/cursor.py` — `class:SnowflakeCursor` (lines 158-1308) + +```python +class SnowflakeCursor: + """Implementation of Cursor object that is returned from Connection.cursor() method. + + Attributes: + description: A list of namedtuples about metadata for all columns. + rowcount: The number of records updated or selected. If not clear, -1 is returned. + rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be + determined. + sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support. + sqlstate: Snowflake SQL State code. + timestamp_output_format: Snowflake timestamp_output_format for timestamps. + timestamp_ltz_output_format: Snowflake output format for LTZ timestamps. + timestamp_tz_output_format: Snowflake output format for TZ timestamps. + timestamp_ntz_output_format: Snowflake output format for NTZ timestamps. + date_output_format: Snowflake output format for dates. + time_output_format: Snowflake output format for times. + timezone: Snowflake timezone. + binary_output_format: Snowflake output format for binary fields. + arraysize: The default number of rows fetched by fetchmany. + connection: The connection object by which the cursor was created. + errorhandle: The class that handles error handling. + is_file_transfer: Whether, or not the current command is a put, or get. + + TODO: + Most of these attributes have no reason to be properties, we could just store them in public variables. + Calling a function is expensive in Python and most of these getters are unnecessary. + """ + + PUT_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*put\s+", flags=re.IGNORECASE) + GET_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*get\s+", flags=re.IGNORECASE) + INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE) + COMMENT_SQL_RE = re.compile(r"/\*.*\*/") + INSERT_SQL_VALUES_RE = re.compile( + r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL + ) + ALTER_SESSION_RE = re.compile( + r"alter\s+session\s+set\s+(.*)=\'?([^\']+)\'?\s*;", + flags=re.IGNORECASE | re.MULTILINE | re.DOTALL, + ) + + @staticmethod + def get_file_transfer_type(sql: str) -> FileTransferType | None: + """Decide whether a SQL is a file transfer and return its type. + + None is returned if the SQL isn't a file transfer so that this function can be + used in an if-statement. + """ + if SnowflakeCursor.PUT_SQL_RE.match(sql): + return FileTransferType.PUT + elif SnowflakeCursor.GET_SQL_RE.match(sql): + return FileTransferType.GET + return None + + def __init__( + self, + connection: SnowflakeConnection, + use_dict_result: bool = False, + ) -> None: + """Inits a SnowflakeCursor with a connection. + + Args: + connection: The connection that created this cursor. + use_dict_result: Decides whether to use dict result or not. + """ + self._connection: SnowflakeConnection = connection + + self._errorhandler: Callable[ + [SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]], + None, + ] = Error.default_errorhandler + self.messages: list[ + tuple[type[Error] | type[Exception], dict[str, str | bool]] + ] = [] + self._timebomb: Timer | None = None # must be here for abort_exit method + self._description: list[ResultMetadata] | None = None + self._column_idx_to_name = None + self._sfqid = None + self._sqlstate = None + self._total_rowcount = -1 + self._sequence_counter = -1 + self._request_id = None + self._is_file_transfer = False + + self._timestamp_output_format = None + self._timestamp_ltz_output_format = None + self._timestamp_ntz_output_format = None + self._timestamp_tz_output_format = None + self._date_output_format = None + self._time_output_format = None + self._timezone = None + self._binary_output_format = None + self._result: Iterator[tuple] | Iterator[dict] | None = None + self._result_set: ResultSet | None = None + self._result_state: ResultState = ResultState.DEFAULT + self._use_dict_result = use_dict_result + self.query: str | None = None + # TODO: self._query_result_format could be defined as an enum + self._query_result_format: str | None = None + + self._arraysize = 1 # PEP-0249: defaults to 1 + + self._lock_canceling = Lock() + + self._first_chunk_time = None + + self._log_max_query_length = connection.log_max_query_length + self._inner_cursor: SnowflakeCursor | None = None + self._prefetch_hook = None + self._rownumber: int | None = None + + self.reset() + + def __del__(self) -> None: # pragma: no cover + try: + self.close() + except compat.BASE_EXCEPTION_CLASS as e: + if logger.getEffectiveLevel() <= logging.INFO: + logger.info(e) + + @property + def description(self) -> list[ResultMetadata]: + return self._description + + @property + def rowcount(self): + return self._total_rowcount if self._total_rowcount >= 0 else None + + @property + def rownumber(self): + return self._rownumber if self._rownumber >= 0 else None + + @property + def sfqid(self): + return self._sfqid + + @property + def sqlstate(self): + return self._sqlstate + + @property + def timestamp_output_format(self): + return self._timestamp_output_format + + @property + def timestamp_ltz_output_format(self): + return ( + self._timestamp_ltz_output_format + if self._timestamp_ltz_output_format + else self._timestamp_output_format + ) + + @property + def timestamp_tz_output_format(self): + return ( + self._timestamp_tz_output_format + if self._timestamp_tz_output_format + else self._timestamp_output_format + ) + + @property + def timestamp_ntz_output_format(self): + return ( + self._timestamp_ntz_output_format + if self._timestamp_ntz_output_format + else self._timestamp_output_format + ) + + @property + def date_output_format(self): + return self._date_output_format + + @property + def time_output_format(self): + return self._time_output_format + + @property + def timezone(self): + return self._timezone + + @property + def binary_output_format(self): + return self._binary_output_format + + @property + def arraysize(self): + return self._arraysize + + @arraysize.setter + def arraysize(self, value): + self._arraysize = int(value) + + @property + def connection(self): + return self._connection + + @property + def errorhandler(self): + return self._errorhandler + + @errorhandler.setter + def errorhandler(self, value): + logger.debug("setting errorhandler: %s", value) + if value is None: + raise ProgrammingError("Invalid errorhandler is specified") + self._errorhandler = value + + @property + def is_file_transfer(self): + """Whether the command is PUT or GET.""" + return hasattr(self, "_is_file_transfer") and self._is_file_transfer + + @property + def lastrowid(self) -> None: + """Snowflake does not support lastrowid in which case None should be returned as per PEP249.""" + return None + + def callproc(self, procname: str, args: T = ()) -> T: + """Call a stored procedure. + + Args: + procname: The stored procedure to be called. + args: Parameters to be passed into the stored procedure. + + Returns: + The input parameters. + """ + marker_format = "%s" if self._connection.is_pyformat else "?" + command = ( + f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})" + ) + self.execute(command, args) + return args + + def close(self) -> bool | None: + """Closes the cursor object. + + Returns whether the cursor was closed during this call. + """ + try: + if self.is_closed(): + return False + + with self._lock_canceling: + self.reset(closing=True) + self._connection = None + del self.messages[:] + return True + except Exception: + pass + + def is_closed(self): + return self._connection is None or self._connection.is_closed() + + def _execute_helper( + self, + query: str, + timeout: int = 0, + statement_params: dict[str, str] | None = None, + binding_params: tuple | dict[str, dict[str, str]] = None, + binding_stage: str | None = None, + is_internal: bool = False, + describe_only: bool = False, + _no_results: bool = False, + _is_put_get=None, + _no_retry: bool = False, + ): + del self.messages[:] + + if statement_params is not None and not isinstance(statement_params, dict): + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": "The data type of statement params is invalid. It must be dict.", + "errno": ER_INVALID_VALUE, + }, + ) + + # check if current installation include arrow extension or not, + # if not, we set statement level query result format to be JSON + if not CAN_USE_ARROW_RESULT_FORMAT: + logger.debug("Cannot use arrow result format, fallback to json format") + if statement_params is None: + statement_params = { + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" + } + else: + result_format_val = statement_params.get( + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ) + if str(result_format_val).upper() == "ARROW": + self.check_can_use_arrow_resultset() + elif result_format_val is None: + statement_params[ + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ] = "JSON" + + self._sequence_counter = self._connection._next_sequence_counter() + self._request_id = uuid.uuid4() + + logger.debug(f"Request id: {self._request_id}") + + logger.debug("running query [%s]", self._format_query_for_log(query)) + if _is_put_get is not None: + # if told the query is PUT or GET, use the information + self._is_file_transfer = _is_put_get + else: + # or detect it. + self._is_file_transfer = self.PUT_SQL_RE.match( + query + ) or self.GET_SQL_RE.match(query) + logger.debug("is_file_transfer: %s", self._is_file_transfer is not None) + + real_timeout = ( + timeout if timeout and timeout > 0 else self._connection.network_timeout + ) + + if real_timeout is not None: + self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) + self._timebomb.start() + logger.debug("started timebomb in %ss", real_timeout) + else: + self._timebomb = None + + original_sigint = signal.getsignal(signal.SIGINT) + + def interrupt_handler(*_): # pragma: no cover + try: + signal.signal(signal.SIGINT, exit_handler) + except (ValueError, TypeError): + # ignore failures + pass + try: + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + self._timebomb = None + self.__cancel_query(query) + finally: + if original_sigint: + try: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): + # ignore failures + pass + raise KeyboardInterrupt + + try: + if not original_sigint == exit_handler: + signal.signal(signal.SIGINT, interrupt_handler) + except ValueError: # pragma: no cover + logger.debug( + "Failed to set SIGINT handler. " "Not in main thread. Ignored..." + ) + ret = {"data": {}} + try: + ret = self._connection.cmd_query( + query, + self._sequence_counter, + self._request_id, + binding_params=binding_params, + binding_stage=binding_stage, + is_file_transfer=bool(self._is_file_transfer), + statement_params=statement_params, + is_internal=is_internal, + describe_only=describe_only, + _no_results=_no_results, + _no_retry=_no_retry, + ) + finally: + try: + if original_sigint: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): # pragma: no cover + logger.debug( + "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." + ) + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + + if "data" in ret and "parameters" in ret["data"]: + parameters = ret["data"]["parameters"] + # Set session parameters for cursor object + for kv in parameters: + if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_output_format = kv["value"] + if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ntz_output_format = kv["value"] + if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ltz_output_format = kv["value"] + if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_tz_output_format = kv["value"] + if "DATE_OUTPUT_FORMAT" in kv["name"]: + self._date_output_format = kv["value"] + if "TIME_OUTPUT_FORMAT" in kv["name"]: + self._time_output_format = kv["value"] + if "TIMEZONE" in kv["name"]: + self._timezone = kv["value"] + if "BINARY_OUTPUT_FORMAT" in kv["name"]: + self._binary_output_format = kv["value"] + # Set session parameters for connection object + self._connection._update_parameters( + {p["name"]: p["value"] for p in parameters} + ) + + self.query = query + self._sequence_counter = -1 + return ret + + def execute( + self, + command: str, + params: Sequence[Any] | dict[Any, Any] | None = None, + _bind_stage: str | None = None, + timeout: int | None = None, + _exec_async: bool = False, + _no_retry: bool = False, + _do_reset: bool = True, + _put_callback: SnowflakeProgressPercentage = None, + _put_azure_callback: SnowflakeProgressPercentage = None, + _put_callback_output_stream: IO[str] = sys.stdout, + _get_callback: SnowflakeProgressPercentage = None, + _get_azure_callback: SnowflakeProgressPercentage = None, + _get_callback_output_stream: IO[str] = sys.stdout, + _show_progress_bar: bool = True, + _statement_params: dict[str, str] | None = None, + _is_internal: bool = False, + _describe_only: bool = False, + _no_results: bool = False, + _is_put_get: bool | None = None, + _raise_put_get_error: bool = True, + _force_put_overwrite: bool = False, + file_stream: IO[bytes] | None = None, + ) -> SnowflakeCursor | None: + """Executes a command/query. + + Args: + command: The SQL command to be executed. + params: Parameters to be bound into the SQL statement. + _bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files. + timeout: Number of seconds after which to abort the query. + _exec_async: Whether to execute this query asynchronously. + _no_retry: Whether or not to retry on known errors. + _do_reset: Whether or not the result set needs to be reset before executing query. + _put_callback: Function to which GET command should call back to. + _put_azure_callback: Function to which an Azure GET command should call back to. + _put_callback_output_stream: The output stream a PUT command's callback should report on. + _get_callback: Function to which GET command should call back to. + _get_azure_callback: Function to which an Azure GET command should call back to. + _get_callback_output_stream: The output stream a GET command's callback should report on. + _show_progress_bar: Whether or not to show progress bar. + _statement_params: Extra information that should be sent to Snowflake with query. + _is_internal: This flag indicates whether the query is issued internally by the connector. + _describe_only: If true, the query will not be executed but return the schema/description of this query. + _no_results: This flag tells the back-end to not return the result, just fire the query and return the + response returned by Snowflake's server. + _use_ijson: This flag doesn't do anything as ijson support has ended. + _is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise. + _raise_put_get_error: Whether to raise PUT and GET errors. + _force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already + existing file on stage. + file_stream: File-like object to be uploaded with PUT + + Returns: + The cursor itself, or None if some error happened, or the response returned + by Snowflake if the _no_results flag is on. + """ + if _exec_async: + _no_results = True + logger.debug("executing SQL/command") + if self.is_closed(): + Error.errorhandler_wrapper( + self.connection, + self, + InterfaceError, + {"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED}, + ) + + if _do_reset: + self.reset() + command = command.strip(" \t\n\r") if command else None + if not command: + logger.warning("execute: no query is given to execute") + return + + kwargs = { + "timeout": timeout, + "statement_params": _statement_params, + "is_internal": _is_internal, + "describe_only": _describe_only, + "_no_results": _no_results, + "_is_put_get": _is_put_get, + "_no_retry": _no_retry, + } + + if self._connection.is_pyformat: + # pyformat/format paramstyle + # client side binding + processed_params = self._connection._process_params_pyformat(params, self) + # SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement + if params is not None and len(params) == 0: + self._log_telemetry_job_data( + TelemetryField.EMPTY_SEQ_INTERPOLATION, + TelemetryData.TRUE + if self.connection._interpolate_empty_sequences + else TelemetryData.FALSE, + ) + if logger.getEffectiveLevel() <= logging.DEBUG: + logger.debug( + f"binding: [{self._format_query_for_log(command)}] " + f"with input=[{params}], " + f"processed=[{processed_params}]", + ) + if ( + self.connection._interpolate_empty_sequences + and processed_params is not None + ) or ( + not self.connection._interpolate_empty_sequences + and len(processed_params) > 0 + ): + query = command % processed_params + else: + query = command + else: + # qmark and numeric paramstyle + query = command + if _bind_stage: + kwargs["binding_stage"] = _bind_stage + else: + if params is not None and not isinstance(params, (list, tuple)): + errorvalue = { + "msg": f"Binding parameters must be a list: {params}", + "errno": ER_FAILED_PROCESSING_PYFORMAT, + } + Error.errorhandler_wrapper( + self.connection, self, ProgrammingError, errorvalue + ) + + kwargs["binding_params"] = self._connection._process_params_qmarks( + params, self + ) + + m = DESC_TABLE_RE.match(query) + if m: + query1 = f"describe table {m.group(1)}" + if logger.getEffectiveLevel() <= logging.WARNING: + logger.info( + "query was rewritten: org=%s, new=%s", + " ".join(line.strip() for line in query.split("\n")), + query1, + ) + query = query1 + + if logger.getEffectiveLevel() <= logging.INFO: + logger.info("query: [%s]", self._format_query_for_log(query)) + ret = self._execute_helper(query, **kwargs) + self._sfqid = ( + ret["data"]["queryId"] + if "data" in ret and "queryId" in ret["data"] + else None + ) + self._sqlstate = ( + ret["data"]["sqlState"] + if "data" in ret and "sqlState" in ret["data"] + else None + ) + self._first_chunk_time = get_time_millis() + + # if server gives a send time, log the time it took to arrive + if "data" in ret and "sendResultTime" in ret["data"]: + time_consume_first_result = ( + self._first_chunk_time - ret["data"]["sendResultTime"] + ) + self._log_telemetry_job_data( + TelemetryField.TIME_CONSUME_FIRST_RESULT, time_consume_first_result + ) + logger.debug("sfqid: %s", self.sfqid) + + logger.info("query execution done") + if ret["success"]: + logger.debug("SUCCESS") + data = ret["data"] + + logger.debug("PUT OR GET: %s", self.is_file_transfer) + if self.is_file_transfer: + # Decide whether to use the old, or new code path + sf_file_transfer_agent = SnowflakeFileTransferAgent( + self, + query, + ret, + put_callback=_put_callback, + put_azure_callback=_put_azure_callback, + put_callback_output_stream=_put_callback_output_stream, + get_callback=_get_callback, + get_azure_callback=_get_azure_callback, + get_callback_output_stream=_get_callback_output_stream, + show_progress_bar=_show_progress_bar, + raise_put_get_error=_raise_put_get_error, + force_put_overwrite=_force_put_overwrite + or data.get("overwrite", False), + source_from_stream=file_stream, + multipart_threshold=data.get("threshold"), + use_s3_regional_url=self._connection.enable_stage_s3_privatelink_for_us_east_1, + ) + sf_file_transfer_agent.execute() + data = sf_file_transfer_agent.result() + self._total_rowcount = len(data["rowset"]) if "rowset" in data else -1 + m = self.ALTER_SESSION_RE.match(query) + if m: + # session parameters + param = m.group(1).upper() + value = m.group(2) + self._connection.converter.set_parameter(param, value) + + if _exec_async: + self.connection._async_sfqids[self._sfqid] = None + if _no_results: + self._total_rowcount = ( + ret["data"]["total"] + if "data" in ret and "total" in ret["data"] + else -1 + ) + return data + self._init_result_and_meta(data) + else: + self._total_rowcount = ( + ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1 + ) + logger.debug(ret) + err = ret["message"] + code = ret.get("code", -1) + if "data" in ret: + err += ret["data"].get("errorMessage", "") + errvalue = { + "msg": err, + "errno": int(code), + "sqlstate": self._sqlstate, + "sfqid": self._sfqid, + } + is_integrity_error = ( + code == "100072" + ) # NULL result in a non-nullable column + error_class = IntegrityError if is_integrity_error else ProgrammingError + Error.errorhandler_wrapper(self.connection, self, error_class, errvalue) + return self + + def execute_async(self, *args, **kwargs): + """Convenience function to execute a query without waiting for results (asynchronously). + + This function takes the same arguments as execute, please refer to that function + for documentation. + """ + kwargs["_exec_async"] = True + return self.execute(*args, **kwargs) + + def describe(self, *args, **kwargs) -> list[ResultMetadata]: + """Obtain the schema of the result without executing the query. + + This function takes the same arguments as execute, please refer to that function + for documentation. + + Returns: + The schema of the result. + """ + kwargs["_describe_only"] = kwargs["_is_internal"] = True + self.execute(*args, **kwargs) + return self._description + + def _format_query_for_log(self, query): + return self._connection._format_query_for_log(query) + + def _is_dml(self, data): + return ( + "statementTypeId" in data + and int(data["statementTypeId"]) in STATEMENT_TYPE_ID_DML_SET + ) + + def _init_result_and_meta(self, data): + is_dml = self._is_dml(data) + self._query_result_format = data.get("queryResultFormat", "json") + logger.debug("Query result format: %s", self._query_result_format) + + if self._total_rowcount == -1 and not is_dml and data.get("total") is not None: + self._total_rowcount = data["total"] + + self._description: list[ResultMetadata] = [ + ResultMetadata.from_column(col) for col in data["rowtype"] + ] + + result_chunks = create_batches_from_response( + self, self._query_result_format, data, self._description + ) + + if not (is_dml or self.is_file_transfer): + logger.info( + "Number of results in first chunk: %s", result_chunks[0].rowcount + ) + + self._result_set = ResultSet( + self, + result_chunks, + self._connection.client_prefetch_threads, + ) + self._rownumber = -1 + self._result_state = ResultState.VALID + + # don't update the row count when the result is returned from `describe` method + if is_dml and "rowset" in data and len(data["rowset"]) > 0: + updated_rows = 0 + for idx, desc in enumerate(self._description): + if desc[0] in ( + "number of rows updated", + "number of multi-joined rows updated", + "number of rows deleted", + ) or desc[0].startswith("number of rows inserted"): + updated_rows += int(data["rowset"][0][idx]) + if self._total_rowcount == -1: + self._total_rowcount = updated_rows + else: + self._total_rowcount += updated_rows + + def check_can_use_arrow_resultset(self): + global CAN_USE_ARROW_RESULT_FORMAT + + if not CAN_USE_ARROW_RESULT_FORMAT: + if self._connection.application == "SnowSQL": + msg = "Currently SnowSQL doesn't support the result set in Apache Arrow format." + errno = ER_NO_PYARROW_SNOWSQL + else: + msg = "The result set in Apache Arrow format is not supported for the platform." + errno = ER_NO_ARROW_RESULT + + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": msg, + "errno": errno, + }, + ) + + def check_can_use_pandas(self): + if not installed_pandas: + msg = ( + "Optional dependency: 'pandas' is not installed, please see the following link for install " + "instructions: https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#installation" + ) + errno = ER_NO_PYARROW + + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": msg, + "errno": errno, + }, + ) + + def query_result(self, qid): + url = f"/queries/{qid}/result" + ret = self._connection.rest.request(url=url, method="get") + self._sfqid = ( + ret["data"]["queryId"] + if "data" in ret and "queryId" in ret["data"] + else None + ) + self._sqlstate = ( + ret["data"]["sqlState"] + if "data" in ret and "sqlState" in ret["data"] + else None + ) + logger.debug("sfqid=%s", self._sfqid) + + if ret.get("success"): + data = ret.get("data") + self._init_result_and_meta(data) + else: + logger.info("failed") + logger.debug(ret) + err = ret["message"] + code = ret.get("code", -1) + if "data" in ret: + err += ret["data"].get("errorMessage", "") + errvalue = { + "msg": err, + "errno": int(code), + "sqlstate": self._sqlstate, + "sfqid": self._sfqid, + } + Error.errorhandler_wrapper( + self.connection, self, ProgrammingError, errvalue + ) + return self + + def fetch_arrow_batches(self) -> Iterator[Table]: + self.check_can_use_arrow_resultset() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data( + TelemetryField.ARROW_FETCH_BATCHES, TelemetryData.TRUE + ) + return self._result_set._fetch_arrow_batches() + + def fetch_arrow_all(self) -> Table | None: + self.check_can_use_arrow_resultset() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data(TelemetryField.ARROW_FETCH_ALL, TelemetryData.TRUE) + return self._result_set._fetch_arrow_all() + + def fetch_pandas_batches(self, **kwargs) -> Iterator[pandas.DataFrame]: + """Fetches a single Arrow Table.""" + self.check_can_use_pandas() + if self._prefetch_hook is not None: + self._prefetch_hook() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data( + TelemetryField.PANDAS_FETCH_BATCHES, TelemetryData.TRUE + ) + return self._result_set._fetch_pandas_batches(**kwargs) + + def fetch_pandas_all(self, **kwargs) -> pandas.DataFrame: + """Fetch Pandas dataframes in batches, where 'batch' refers to Snowflake Chunk.""" + self.check_can_use_pandas() + if self._prefetch_hook is not None: + self._prefetch_hook() + if self._query_result_format != "arrow": + raise NotSupportedError + self._log_telemetry_job_data( + TelemetryField.PANDAS_FETCH_ALL, TelemetryData.TRUE + ) + return self._result_set._fetch_pandas_all(**kwargs) + + def abort_query(self, qid): + url = f"/queries/{qid}/abort-request" + ret = self._connection.rest.request(url=url, method="post") + return ret.get("success") + + def executemany( + self, + command: str, + seqparams: Sequence[Any] | dict[str, Any], + **kwargs: dict[str, Any], + ) -> SnowflakeCursor: + """Executes a command/query with the given set of parameters sequentially.""" + logger.debug("executing many SQLs/commands") + command = command.strip(" \t\n\r") if command else None + + if not seqparams: + return self + + if self.INSERT_SQL_RE.match(command): + if self._connection.is_pyformat: + logger.debug("rewriting INSERT query") + command_wo_comments = re.sub(self.COMMENT_SQL_RE, "", command) + m = self.INSERT_SQL_VALUES_RE.match(command_wo_comments) + if not m: + Error.errorhandler_wrapper( + self.connection, + self, + InterfaceError, + { + "msg": "Failed to rewrite multi-row insert", + "errno": ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT, + }, + ) + + fmt = m.group(1) + values = [] + for param in seqparams: + logger.debug(f"parameter: {param}") + values.append( + fmt % self._connection._process_params_pyformat(param, self) + ) + command = command.replace(fmt, ",".join(values), 1) + self.execute(command, **kwargs) + return self + else: + logger.debug("bulk insert") + # sanity check + row_size = len(seqparams[0]) + for row in seqparams: + if len(row) != row_size: + error_value = { + "msg": f"Bulk data size don't match. expected: {row_size}, " + f"got: {len(row)}, command: {command}", + "errno": ER_INVALID_VALUE, + } + Error.errorhandler_wrapper( + self.connection, self, InterfaceError, error_value + ) + return self + bind_size = len(seqparams) * row_size + bind_stage = None + if ( + bind_size + > self.connection._session_parameters[ + "CLIENT_STAGE_ARRAY_BINDING_THRESHOLD" + ] + > 0 + ): + # bind stage optimization + try: + rows = self.connection._write_params_to_byte_rows(seqparams) + bind_uploader = BindUploadAgent(self, rows) + bind_uploader.upload() + bind_stage = bind_uploader.stage_path + except BindUploadError: + logger.debug( + "Failed to upload binds to stage, sending binds to " + "Snowflake instead." + ) + binding_param = ( + None if bind_stage else list(map(list, zip(*seqparams))) + ) # transpose + self.execute( + command, params=binding_param, _bind_stage=bind_stage, **kwargs + ) + return self + + self.reset() + for param in seqparams: + self.execute(command, params=param, _do_reset=False, **kwargs) + return self + + def _result_iterator( + self, + ) -> Generator[dict, None, None] | Generator[tuple, None, None]: + """Yields the elements from _result and raises an exception when appropriate.""" + try: + for _next in self._result: + if isinstance(_next, Exception): + Error.errorhandler_wrapper_from_ready_exception( + self._connection, + self, + _next, + ) + self._rownumber += 1 + yield _next + except TypeError as err: + if self._result_state == ResultState.DEFAULT: + raise err + else: + yield None + + def fetchone(self) -> dict | tuple | None: + """Fetches one row.""" + if self._prefetch_hook is not None: + self._prefetch_hook() + if self._result is None and self._result_set is not None: + self._result = iter(self._result_set) + self._result_state = ResultState.VALID + try: + return next(self._result_iterator()) + except StopIteration: + return None + + def fetchmany(self, size=None): + """Fetches the number of specified rows.""" + if size is None: + size = self.arraysize + + if size < 0: + errorvalue = { + "msg": ( + "The number of rows is not zero or " "positive number: {}" + ).format(size), + "errno": ER_NOT_POSITIVE_SIZE, + } + Error.errorhandler_wrapper( + self.connection, self, ProgrammingError, errorvalue + ) + ret = [] + while size > 0: + row = self.fetchone() + if row is None: + break + ret.append(row) + if size is not None: + size -= 1 + + return ret + + def fetchall(self) -> list[tuple] | list[dict]: + """Fetches all of the results.""" + ret = [] + while True: + row = self.fetchone() + if row is None: + break + ret.append(row) + return ret + + def nextset(self): + """Not supported.""" + logger.debug("nop") + return None + + def setinputsizes(self, _): + """Not supported.""" + logger.debug("nop") + + def setoutputsize(self, _, column=None): + """Not supported.""" + del column + logger.debug("nop") + + def scroll(self, value, mode="relative"): + Error.errorhandler_wrapper( + self.connection, + self, + NotSupportedError, + { + "msg": "scroll is not supported.", + "errno": ER_UNSUPPORTED_METHOD, + "sqlstate": SQLSTATE_FEATURE_NOT_SUPPORTED, + }, + ) + + def reset(self, closing=False): + """Resets the result set.""" + # SNOW-647539: Do not erase the rowcount + # information when closing the cursor + if not closing: + self._total_rowcount = -1 + if self._result_state != ResultState.DEFAULT: + self._result_state = ResultState.RESET + if self._result is not None: + self._result = None + if self._inner_cursor is not None: + self._inner_cursor.reset(closing=closing) + self._result = None + self._inner_cursor = None + self._prefetch_hook = None + if not self.connection._reuse_results: + self._result_set = None + + def __iter__(self) -> Iterator[dict] | Iterator[tuple]: + """Iteration over the result set.""" + # set _result if _result_set is not None + if self._result is None and self._result_set is not None: + self._result = iter(self._result_set) + self._result_state = ResultState.VALID + return self._result_iterator() + + def __cancel_query(self, query): + if self._sequence_counter >= 0 and not self.is_closed(): + logger.debug("canceled. %s, request_id: %s", query, self._request_id) + with self._lock_canceling: + self._connection._cancel_query(query, self._request_id) + + def _log_telemetry_job_data( + self, telemetry_field: TelemetryField, value: Any + ) -> None: + """Builds an instance of TelemetryData with the given field and logs it.""" + ts = get_time_millis() + try: + self._connection._log_telemetry( + TelemetryData.from_telemetry_data_dict( + from_dict={ + TelemetryField.KEY_TYPE.value: telemetry_field.value, + TelemetryField.KEY_SFQID.value: self._sfqid, + TelemetryField.KEY_VALUE.value: value, + }, + timestamp=ts, + connection=self._connection, + ) + ) + except AttributeError: + logger.warning( + "Cursor failed to log to telemetry. Connection object may be None.", + exc_info=True, + ) + + def __enter__(self): + """Context manager.""" + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Context manager with commit or rollback.""" + self.close() + + def get_results_from_sfqid(self, sfqid: str): + """Gets the results from previously ran query.""" + + def wait_until_ready(): + """Makes sure query has finished executing and once it has retrieves results.""" + no_data_counter = 0 + retry_pattern_pos = 0 + while True: + status = self.connection.get_query_status(sfqid) + if not self.connection.is_still_running(status): + break + if status == QueryStatus.NO_DATA: # pragma: no cover + no_data_counter += 1 + if no_data_counter > ASYNC_NO_DATA_MAX_RETRY: + raise DatabaseError( + "Cannot retrieve data on the status of this query. No information returned " + "from server for query '{}'" + ) + time.sleep( + 0.5 * ASYNC_RETRY_PATTERN[retry_pattern_pos] + ) # Same wait as JDBC + # If we can advance in ASYNC_RETRY_PATTERN then do so + if retry_pattern_pos < (len(ASYNC_RETRY_PATTERN) - 1): + retry_pattern_pos += 1 + if status != QueryStatus.SUCCESS: + raise DatabaseError( + "Status of query '{}' is {}, results are unavailable".format( + sfqid, status.name + ) + ) + self._inner_cursor.execute(f"select * from table(result_scan('{sfqid}'))") + self._result = self._inner_cursor._result + self._query_result_format = self._inner_cursor._query_result_format + self._total_rowcount = self._inner_cursor._total_rowcount + self._description = self._inner_cursor._description + self._result_set = self._inner_cursor._result_set + self._result_state = ResultState.VALID + self._rownumber = 0 + # Unset this function, so that we don't block anymore + self._prefetch_hook = None + + self.connection.get_query_status_throw_if_error( + sfqid + ) # Trigger an exception if query failed + klass = self.__class__ + self._inner_cursor = klass(self.connection) + self._sfqid = sfqid + self._prefetch_hook = wait_until_ready + + def get_result_batches(self) -> list[ResultBatch] | None: + """Get the previously executed query's ``ResultBatch`` s if available. + + If they are unavailable, in case nothing has been executed yet None will + be returned. + + For a detailed description of ``ResultBatch`` s please see the docstring of: + ``snowflake.connector.result_batches.ResultBatch`` + """ + if self._result_set is None: + return None + self._log_telemetry_job_data( + TelemetryField.GET_PARTITIONS_USED, TelemetryData.TRUE + ) + return self._result_set.batches +``` + +## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor.get_file_transfer_type` (lines 198-209) + +```python + def get_file_transfer_type(sql: str) -> FileTransferType | None: + """Decide whether a SQL is a file transfer and return its type. + + None is returned if the SQL isn't a file transfer so that this function can be + used in an if-statement. + """ + if SnowflakeCursor.PUT_SQL_RE.match(sql): + return FileTransferType.PUT + elif SnowflakeCursor.GET_SQL_RE.match(sql): + return FileTransferType.GET + return None +``` + +## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor._execute_helper` (lines 411-567) + +```python + def _execute_helper( + self, + query: str, + timeout: int = 0, + statement_params: dict[str, str] | None = None, + binding_params: tuple | dict[str, dict[str, str]] = None, + binding_stage: str | None = None, + is_internal: bool = False, + describe_only: bool = False, + _no_results: bool = False, + _is_put_get=None, + _no_retry: bool = False, + ): + del self.messages[:] + + if statement_params is not None and not isinstance(statement_params, dict): + Error.errorhandler_wrapper( + self.connection, + self, + ProgrammingError, + { + "msg": "The data type of statement params is invalid. It must be dict.", + "errno": ER_INVALID_VALUE, + }, + ) + + # check if current installation include arrow extension or not, + # if not, we set statement level query result format to be JSON + if not CAN_USE_ARROW_RESULT_FORMAT: + logger.debug("Cannot use arrow result format, fallback to json format") + if statement_params is None: + statement_params = { + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON" + } + else: + result_format_val = statement_params.get( + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ) + if str(result_format_val).upper() == "ARROW": + self.check_can_use_arrow_resultset() + elif result_format_val is None: + statement_params[ + PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + ] = "JSON" + + self._sequence_counter = self._connection._next_sequence_counter() + self._request_id = uuid.uuid4() + + logger.debug(f"Request id: {self._request_id}") + + logger.debug("running query [%s]", self._format_query_for_log(query)) + if _is_put_get is not None: + # if told the query is PUT or GET, use the information + self._is_file_transfer = _is_put_get + else: + # or detect it. + self._is_file_transfer = self.PUT_SQL_RE.match( + query + ) or self.GET_SQL_RE.match(query) + logger.debug("is_file_transfer: %s", self._is_file_transfer is not None) + + real_timeout = ( + timeout if timeout and timeout > 0 else self._connection.network_timeout + ) + + if real_timeout is not None: + self._timebomb = Timer(real_timeout, self.__cancel_query, [query]) + self._timebomb.start() + logger.debug("started timebomb in %ss", real_timeout) + else: + self._timebomb = None + + original_sigint = signal.getsignal(signal.SIGINT) + + def interrupt_handler(*_): # pragma: no cover + try: + signal.signal(signal.SIGINT, exit_handler) + except (ValueError, TypeError): + # ignore failures + pass + try: + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + self._timebomb = None + self.__cancel_query(query) + finally: + if original_sigint: + try: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): + # ignore failures + pass + raise KeyboardInterrupt + + try: + if not original_sigint == exit_handler: + signal.signal(signal.SIGINT, interrupt_handler) + except ValueError: # pragma: no cover + logger.debug( + "Failed to set SIGINT handler. " "Not in main thread. Ignored..." + ) + ret = {"data": {}} + try: + ret = self._connection.cmd_query( + query, + self._sequence_counter, + self._request_id, + binding_params=binding_params, + binding_stage=binding_stage, + is_file_transfer=bool(self._is_file_transfer), + statement_params=statement_params, + is_internal=is_internal, + describe_only=describe_only, + _no_results=_no_results, + _no_retry=_no_retry, + ) + finally: + try: + if original_sigint: + signal.signal(signal.SIGINT, original_sigint) + except (ValueError, TypeError): # pragma: no cover + logger.debug( + "Failed to reset SIGINT handler. Not in main " "thread. Ignored..." + ) + if self._timebomb is not None: + self._timebomb.cancel() + logger.debug("cancelled timebomb in finally") + + if "data" in ret and "parameters" in ret["data"]: + parameters = ret["data"]["parameters"] + # Set session parameters for cursor object + for kv in parameters: + if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_output_format = kv["value"] + if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ntz_output_format = kv["value"] + if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_ltz_output_format = kv["value"] + if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]: + self._timestamp_tz_output_format = kv["value"] + if "DATE_OUTPUT_FORMAT" in kv["name"]: + self._date_output_format = kv["value"] + if "TIME_OUTPUT_FORMAT" in kv["name"]: + self._time_output_format = kv["value"] + if "TIMEZONE" in kv["name"]: + self._timezone = kv["value"] + if "BINARY_OUTPUT_FORMAT" in kv["name"]: + self._binary_output_format = kv["value"] + # Set session parameters for connection object + self._connection._update_parameters( + {p["name"]: p["value"] for p in parameters} + ) + + self.query = query + self._sequence_counter = -1 + return ret +``` + +## `src/snowflake/connector/cursor.py` — `module:@35` (lines 35-35) + +```python +from .bind_upload_agent import BindUploadAgent, BindUploadError +``` + +## `src/snowflake/connector/gcs_storage_client.py` — `class:SnowflakeGCSRestClient` (lines 47-396) + +```python +class SnowflakeGCSRestClient(SnowflakeStorageClient): + def __init__( + self, + meta: SnowflakeFileMeta, + credentials: StorageCredential, + stage_info: dict[str, Any], + cnx: SnowflakeConnection, + command: str, + use_s3_regional_url=False, + ) -> None: + """Creates a client object with given stage credentials. + + Args: + stage_info: Access credentials and info of a stage. + + Returns: + The client to communicate with GCS. + """ + super().__init__( + meta, stage_info, -1, credentials=credentials, chunked_transfer=False + ) + self.stage_info = stage_info + self._command = command + self.meta = meta + self._cursor = cnx.cursor() + # presigned_url in meta is for downloading + self.presigned_url: str = meta.presigned_url or stage_info.get("presignedUrl") + self.security_token = credentials.creds.get("GCS_ACCESS_TOKEN") + + if self.security_token: + logger.debug(f"len(GCS_ACCESS_TOKEN): {len(self.security_token)}") + else: + logger.debug("No access token received from GS, requesting presigned url") + self._update_presigned_url() + + def _has_expired_token(self, response: requests.Response) -> bool: + return self.security_token and response.status_code == 401 + + def _has_expired_presigned_url(self, response: requests.Response) -> bool: + # Presigned urls can be generated for any xml-api operation + # offered by GCS. Hence the error codes expected are similar + # to xml api. + # https://cloud.google.com/storage/docs/xml-api/reference-status + + presigned_url_expired = ( + not self.security_token + ) and response.status_code == 400 + if presigned_url_expired and self.last_err_is_presigned_url: + logger.debug("Presigned url expiration error two times in a row.") + response.raise_for_status() + self.last_err_is_presigned_url = presigned_url_expired + return presigned_url_expired + + def _upload_chunk(self, chunk_id: int, chunk: bytes) -> None: + meta = self.meta + + content_encoding = "" + if meta.dst_compression_type is not None: + content_encoding = meta.dst_compression_type.name.lower() + + # We set the contentEncoding to blank for GZIP files. We don't + # want GCS to think our gzip files are gzips because it makes + # them download uncompressed, and none of the other providers do + # that. There's essentially no way for us to prevent that + # behavior. Bad Google. + if content_encoding and content_encoding == "gzip": + content_encoding = "" + + gcs_headers = { + HTTP_HEADER_CONTENT_ENCODING: content_encoding, + GCS_METADATA_SFC_DIGEST: meta.sha256_digest, + } + + if self.encryption_metadata: + gcs_headers.update( + { + GCS_METADATA_ENCRYPTIONDATAPROP: json.dumps( + { + "EncryptionMode": "FullBlob", + "WrappedContentKey": { + "KeyId": "symmKey1", + "EncryptedKey": self.encryption_metadata.key, + "Algorithm": "AES_CBC_256", + }, + "EncryptionAgent": { + "Protocol": "1.0", + "EncryptionAlgorithm": "AES_CBC_256", + }, + "ContentEncryptionIV": self.encryption_metadata.iv, + "KeyWrappingMetadata": {"EncryptionLibrary": "Java 5.3.0"}, + } + ), + GCS_METADATA_MATDESC_KEY: self.encryption_metadata.matdesc, + } + ) + + def generate_url_and_rest_args() -> tuple[ + str, dict[str, dict[str | Any, str | None] | bytes] + ]: + if not self.presigned_url: + upload_url = self.generate_file_url( + self.stage_info["location"], meta.dst_file_name.lstrip("/") + ) + access_token = self.security_token + else: + upload_url = self.presigned_url + access_token: str | None = None + if access_token: + gcs_headers.update({"Authorization": f"Bearer {access_token}"}) + rest_args = {"headers": gcs_headers, "data": chunk} + return upload_url, rest_args + + response = self._send_request_with_retry( + "PUT", generate_url_and_rest_args, chunk_id + ) + response.raise_for_status() + meta.gcs_file_header_digest = gcs_headers[GCS_METADATA_SFC_DIGEST] + meta.gcs_file_header_content_length = meta.upload_size + meta.gcs_file_header_encryption_metadata = json.loads( + gcs_headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, "null") + ) + + def download_chunk(self, chunk_id: int) -> None: + meta = self.meta + + def generate_url_and_rest_args() -> tuple[ + str, dict[str, dict[str, str] | bool] + ]: + gcs_headers = {} + if not self.presigned_url: + download_url = self.generate_file_url( + self.stage_info["location"], meta.src_file_name.lstrip("/") + ) + access_token = self.security_token + gcs_headers["Authorization"] = f"Bearer {access_token}" + else: + download_url = self.presigned_url + rest_args = {"headers": gcs_headers, "stream": True} + return download_url, rest_args + + response = self._send_request_with_retry( + "GET", generate_url_and_rest_args, chunk_id + ) + response.raise_for_status() + + self.write_downloaded_chunk(chunk_id, response.content) + + encryption_metadata = None + + if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): + encryptiondata = json.loads( + response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] + ) + + if encryptiondata: + encryption_metadata = EncryptionMetadata( + key=encryptiondata["WrappedContentKey"]["EncryptedKey"], + iv=encryptiondata["ContentEncryptionIV"], + matdesc=response.headers[GCS_METADATA_MATDESC_KEY] + if GCS_METADATA_MATDESC_KEY in response.headers + else None, + ) + + meta.gcs_file_header_digest = response.headers.get(GCS_METADATA_SFC_DIGEST) + meta.gcs_file_header_content_length = len(response.content) + meta.gcs_file_header_encryption_metadata = encryption_metadata + + def finish_download(self) -> None: + super().finish_download() + # Sadly, we can only determine the src file size after we've + # downloaded it, unlike the other cloud providers where the + # metadata can be read beforehand. + self.meta.src_file_size = os.path.getsize(self.intermediate_dst_path) + + def _update_presigned_url(self) -> None: + """Updates the file metas with presigned urls if any. + + Currently only the file metas generated for PUT/GET on a GCP account need the presigned urls. + """ + logger.debug("Updating presigned url") + + # Rewrite the command such that a new PUT call is made for each file + # represented by the regex (if present) separately. This is the only + # way to get the presigned url for that file. + file_path_to_be_replaced = self._get_local_file_path_from_put_command() + + if not file_path_to_be_replaced: + # This prevents GET statements to proceed + return + + # At this point the connector has already figured out and + # validated that the local file exists and has also decided + # upon the destination file name and the compression type. + # The only thing that's left to do is to get the presigned + # url for the destination file. If the command originally + # referred to a single file, then the presigned url got in + # that case is simply ignore, since the file name is not what + # we want. + + # GS only looks at the file name at the end of local file + # path to figure out the remote object name. Hence the prefix + # for local path is not necessary in the reconstructed command. + file_path_to_replace_with = self.meta.dst_file_name + command_with_single_file = self._command + command_with_single_file = command_with_single_file.replace( + file_path_to_be_replaced, file_path_to_replace_with + ) + + logger.debug("getting presigned url for %s", file_path_to_replace_with) + ret = self._cursor._execute_helper(command_with_single_file) + + stage_info = ret.get("data", dict()).get("stageInfo", dict()) + self.meta.presigned_url = stage_info.get("presignedUrl") + self.presigned_url = stage_info.get("presignedUrl") + + def _get_local_file_path_from_put_command(self) -> str | None: + """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita). + + Args: + command: Command to be parsed and get the local file path out of. + + Returns: + The local file path. + """ + command = self._command + if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match( + command + ): + return None + + file_path_begin_index = command.find(FILE_PROTOCOL) + is_file_path_quoted = command[file_path_begin_index - 1] == "'" + file_path_begin_index += len(FILE_PROTOCOL) + + file_path = "" + + if is_file_path_quoted: + file_path_end_index = command.find("'", file_path_begin_index) + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + else: + index_list = [] + for delimiter in [" ", "\n", ";"]: + index = command.find(delimiter, file_path_begin_index) + if index != -1: + index_list += [index] + + file_path_end_index = min(index_list) if index_list else -1 + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + elif file_path_end_index == -1: + file_path = command[file_path_begin_index:] + + return file_path + + def get_file_header(self, filename: str) -> FileHeader | None: + """Gets the remote file's metadata. + + Args: + filename: Not applicable to GCS. + + Returns: + The file header, with expected properties populated or None, based on how the request goes with the + storage provider. + + Notes: + Sometimes this method is called to verify that the file has indeed been uploaded. In cases of presigned + url, we have no way of verifying that, except with the http status code of 200 which we have already + confirmed and set the meta.result_status = UPLOADED/DOWNLOADED. + """ + meta = self.meta + if ( + meta.result_status == ResultStatus.UPLOADED + or meta.result_status == ResultStatus.DOWNLOADED + ): + return FileHeader( + digest=meta.gcs_file_header_digest, + content_length=meta.gcs_file_header_content_length, + encryption_metadata=meta.gcs_file_header_encryption_metadata, + ) + elif self.presigned_url: + meta.result_status = ResultStatus.NOT_FOUND_FILE + else: + + def generate_url_and_authenticated_headers(): + url = self.generate_file_url( + self.stage_info["location"], filename.lstrip("/") + ) + gcs_headers = {"Authorization": f"Bearer {self.security_token}"} + rest_args = {"headers": gcs_headers} + return url, rest_args + + retry_id = "HEAD" + self.retry_count[retry_id] = 0 + response = self._send_request_with_retry( + "HEAD", generate_url_and_authenticated_headers, retry_id + ) + if response.status_code == 404: + meta.result_status = ResultStatus.NOT_FOUND_FILE + return None + elif response.status_code == 200: + digest = response.headers.get(GCS_METADATA_SFC_DIGEST, None) + content_length = int(response.headers.get("content-length", "0")) + + encryption_metadata = EncryptionMetadata("", "", "") + if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None): + encryption_data = json.loads( + response.headers[GCS_METADATA_ENCRYPTIONDATAPROP] + ) + + if encryption_data: + encryption_metadata = EncryptionMetadata( + key=encryption_data["WrappedContentKey"]["EncryptedKey"], + iv=encryption_data["ContentEncryptionIV"], + matdesc=response.headers[GCS_METADATA_MATDESC_KEY] + if GCS_METADATA_MATDESC_KEY in response.headers + else None, + ) + meta.result_status = ResultStatus.UPLOADED + return FileHeader( + digest=digest, + content_length=content_length, + encryption_metadata=encryption_metadata, + ) + response.raise_for_status() + return None + + @staticmethod + def extract_bucket_name_and_path(stage_location: str) -> GcsLocation: + container_name = stage_location + path = "" + + # split stage location as bucket name and path + if "/" in stage_location: + container_name = stage_location[0 : stage_location.index("/")] + path = stage_location[stage_location.index("/") + 1 :] + if path and not path.endswith("/"): + path += "/" + + return GcsLocation(bucket_name=container_name, path=path) + + @staticmethod + def generate_file_url(stage_location: str, filename: str) -> str: + gcs_location = SnowflakeGCSRestClient.extract_bucket_name_and_path( + stage_location + ) + full_file_path = f"{gcs_location.path}{filename}" + return f"https://storage.googleapis.com/{gcs_location.bucket_name}/{quote(full_file_path)}" +``` + +## `src/snowflake/connector/gcs_storage_client.py` — `function:SnowflakeGCSRestClient._get_local_file_path_from_put_command` (lines 262-302) + +```python + def _get_local_file_path_from_put_command(self) -> str | None: + """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita). + + Args: + command: Command to be parsed and get the local file path out of. + + Returns: + The local file path. + """ + command = self._command + if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match( + command + ): + return None + + file_path_begin_index = command.find(FILE_PROTOCOL) + is_file_path_quoted = command[file_path_begin_index - 1] == "'" + file_path_begin_index += len(FILE_PROTOCOL) + + file_path = "" + + if is_file_path_quoted: + file_path_end_index = command.find("'", file_path_begin_index) + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + else: + index_list = [] + for delimiter in [" ", "\n", ";"]: + index = command.find(delimiter, file_path_begin_index) + if index != -1: + index_list += [index] + + file_path_end_index = min(index_list) if index_list else -1 + + if file_path_end_index > file_path_begin_index: + file_path = command[file_path_begin_index:file_path_end_index] + elif file_path_end_index == -1: + file_path = command[file_path_begin_index:] + + return file_path +``` + +## `src/snowflake/connector/gcs_storage_client.py` — `module:@13` (lines 13-13) + +```python +from .compat import quote +``` + +## `test/unit/test_cursor.py` — `function:test_get_filetransfer_type` (lines 27-36) + +```python +def test_get_filetransfer_type(sql, _type): + assert SnowflakeCursor.get_file_transfer_type(sql) == _type +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dc39d031650b08e1b8efac15bbbfb41a9796a16a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.json @@ -0,0 +1,71 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-1f5068a3fe5ca0192a07", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-1f5068a3fe5ca0192a07", + "project_id": "pyvul__snowflakedb__snowflake-connector-python", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "src/snowflake/connector/_sql_util.py", + "src/snowflake/connector/cursor.py", + "src/snowflake/connector/gcs_storage_client.py", + "test/unit/test_cursor.py" + ], + "patch_units": { + "before": [ + "class:SnowflakeCursor", + "function:SnowflakeCursor.get_file_transfer_type", + "function:SnowflakeCursor._execute_helper", + "module:@35", + "class:SnowflakeGCSRestClient", + "function:SnowflakeGCSRestClient._get_local_file_path_from_put_command", + "module:@13", + "function:test_get_filetransfer_type" + ], + "after": [ + "function:remove_starting_comments", + "function:get_file_transfer_type", + "function:is_put_statement", + "function:is_get_statement", + "module:@5", + "module:@7", + "module:@9", + "module:@11", + "module:@19", + "module:@20", + "class:SnowflakeCursor", + "function:SnowflakeCursor.get_file_transfer_type", + "function:SnowflakeCursor._execute_helper", + "module:@35", + "class:SnowflakeGCSRestClient", + "function:SnowflakeGCSRestClient._get_local_file_path_from_put_command", + "module:@13", + "function:test_get_filetransfer_type" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/51887dcfe7b812bd843f3a90bce6ab7b253e5b2bcb4f7ac848f4c114825a4951/database", + "cache_key": "51887dcfe7b812bd843f3a90bce6ab7b253e5b2bcb4f7ac848f4c114825a4951", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/4fc5588b7743ee66216e918ba584f47435544a3f20dfa638a54387e954e61737/database", + "cache_key": "4fc5588b7743ee66216e918ba584f47435544a3f20dfa638a54387e954e61737", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/da7a7cda9635f06af5e6e590e9e469862e58d247d08eb71840969ce954b37632/database", + "cache_key": "da7a7cda9635f06af5e6e590e9e469862e58d247d08eb71840969ce954b37632", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-1f5068a3fe5ca0192a07/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-1f5068a3fe5ca0192a07/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dbbf80a421dbf2b06a09f6fa1abff5578867e1fc --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diff @@ -0,0 +1,60 @@ +diff --git a/grappelli/views/switch.py b/grappelli/views/switch.py +index 8e390b13..db2ee680 100644 +--- a/grappelli/views/switch.py ++++ b/grappelli/views/switch.py +@@ -8,6 +8,7 @@ from django.core.exceptions import ObjectDoesNotExist + from django.http import Http404 + from django.shortcuts import redirect + from django.utils.html import escape ++from django.utils.http import url_has_allowed_host_and_scheme + from django.utils.translation import gettext_lazy as _ + + from grappelli.settings import SWITCH_USER_ORIGINAL, SWITCH_USER_TARGET +@@ -28,30 +29,35 @@ def switch_user(request, object_id): + + # check redirect + redirect_url = request.GET.get("redirect", None) +- if redirect_url is None or not redirect_url.startswith("/"): ++ if redirect_url is None or not \ ++ url_has_allowed_host_and_scheme( ++ url=redirect_url, ++ allowed_hosts={request.get_host()}, ++ require_https=request.is_secure(), ++ ): + raise Http404() +- ++ + # check original_user + try: + original_user = User.objects.get(pk=session_user["id"], is_staff=True) + if not SWITCH_USER_ORIGINAL(original_user): + messages.add_message(request, messages.ERROR, _("Permission denied.")) +- return redirect(request.GET.get("redirect")) ++ return redirect(redirect_url) + except ObjectDoesNotExist: + msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])} + messages.add_message(request, messages.ERROR, msg) +- return redirect(request.GET.get("redirect")) ++ return redirect(redirect_url) + + # check new user + try: + target_user = User.objects.get(pk=object_id, is_staff=True) + if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user): + messages.add_message(request, messages.ERROR, _("Permission denied.")) +- return redirect(request.GET.get("redirect")) ++ return redirect(redirect_url) + except ObjectDoesNotExist: + msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)} + messages.add_message(request, messages.ERROR, msg) +- return redirect(request.GET.get("redirect")) ++ return redirect(redirect_url) + + # find backend + if not hasattr(target_user, 'backend'): +@@ -66,4 +72,4 @@ def switch_user(request, object_id): + if original_user.id != target_user.id: + request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()} + +- return redirect(request.GET.get("redirect")) ++ return redirect(redirect_url) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6621a40079bb48c3aeb4c989f6aba16cde5a9413 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.md @@ -0,0 +1,64 @@ +# Patch-overlapping Python context after the fix + +## `grappelli/views/switch.py` — `function:switch_user` (lines 23-75) + +```python +def switch_user(request, object_id): + + # current/session user + current_user = request.user + session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()}) + + # check redirect + redirect_url = request.GET.get("redirect", None) + if redirect_url is None or not \ + url_has_allowed_host_and_scheme( + url=redirect_url, + allowed_hosts={request.get_host()}, + require_https=request.is_secure(), + ): + raise Http404() + + # check original_user + try: + original_user = User.objects.get(pk=session_user["id"], is_staff=True) + if not SWITCH_USER_ORIGINAL(original_user): + messages.add_message(request, messages.ERROR, _("Permission denied.")) + return redirect(redirect_url) + except ObjectDoesNotExist: + msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])} + messages.add_message(request, messages.ERROR, msg) + return redirect(redirect_url) + + # check new user + try: + target_user = User.objects.get(pk=object_id, is_staff=True) + if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user): + messages.add_message(request, messages.ERROR, _("Permission denied.")) + return redirect(redirect_url) + except ObjectDoesNotExist: + msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)} + messages.add_message(request, messages.ERROR, msg) + return redirect(redirect_url) + + # find backend + if not hasattr(target_user, 'backend'): + for backend in settings.AUTHENTICATION_BACKENDS: + if target_user == load_backend(backend).get_user(target_user.pk): + target_user.backend = backend + break + + # target user login, set original as session + if hasattr(target_user, 'backend'): + login(request, target_user) + if original_user.id != target_user.id: + request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()} + + return redirect(redirect_url) +``` + +## `grappelli/views/switch.py` — `module:@11` (lines 11-11) + +```python +from django.utils.http import url_has_allowed_host_and_scheme +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..98b0329b6528d3308460ff03e5eb30d31c1f1d3a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.md @@ -0,0 +1,59 @@ +# Patch-overlapping Python context before the fix + +## `grappelli/views/switch.py` — `function:switch_user` (lines 22-69) + +```python +def switch_user(request, object_id): + + # current/session user + current_user = request.user + session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()}) + + # check redirect + redirect_url = request.GET.get("redirect", None) + if redirect_url is None or not redirect_url.startswith("/"): + raise Http404() + + # check original_user + try: + original_user = User.objects.get(pk=session_user["id"], is_staff=True) + if not SWITCH_USER_ORIGINAL(original_user): + messages.add_message(request, messages.ERROR, _("Permission denied.")) + return redirect(request.GET.get("redirect")) + except ObjectDoesNotExist: + msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])} + messages.add_message(request, messages.ERROR, msg) + return redirect(request.GET.get("redirect")) + + # check new user + try: + target_user = User.objects.get(pk=object_id, is_staff=True) + if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user): + messages.add_message(request, messages.ERROR, _("Permission denied.")) + return redirect(request.GET.get("redirect")) + except ObjectDoesNotExist: + msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)} + messages.add_message(request, messages.ERROR, msg) + return redirect(request.GET.get("redirect")) + + # find backend + if not hasattr(target_user, 'backend'): + for backend in settings.AUTHENTICATION_BACKENDS: + if target_user == load_backend(backend).get_user(target_user.pk): + target_user.backend = backend + break + + # target user login, set original as session + if hasattr(target_user, 'backend'): + login(request, target_user) + if original_user.id != target_user.id: + request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()} + + return redirect(request.GET.get("redirect")) +``` + +## `grappelli/views/switch.py` — `module:@11` (lines 11-11) + +```python +from django.utils.translation import gettext_lazy as _ +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cab3c12c86c598a902bf89b5e28f5d47d4e38752 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-2ab65d62986b80922362", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-2ab65d62986b80922362", + "project_id": "pyvul__sehmaschine__django-grappelli", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "grappelli/views/switch.py" + ], + "patch_units": { + "before": [ + "function:switch_user", + "module:@11" + ], + "after": [ + "function:switch_user", + "module:@11" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/a651d858d8c6a33884674a524fc8f61c7e7ccfccade3966409515abaecba586d/database", + "cache_key": "a651d858d8c6a33884674a524fc8f61c7e7ccfccade3966409515abaecba586d", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/346863e80f97754d1d2004217a3308ad91897bf7891ed868b01ecd17ed39d300/database", + "cache_key": "346863e80f97754d1d2004217a3308ad91897bf7891ed868b01ecd17ed39d300", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/091b842c9e7302a8f7aee586e6738c61c6607f0befe3559f5296b1b32275785b/database", + "cache_key": "091b842c9e7302a8f7aee586e6738c61c6607f0befe3559f5296b1b32275785b", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-2ab65d62986b80922362/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-2ab65d62986b80922362/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..71e56fa32c95b942a571370f375000d08fc86207 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diff @@ -0,0 +1,33 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ba9187c0a3..6149f587ea 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -51,6 +51,9 @@ The types of changes are: + - User preferences from cookie should always override experience preferences [#4405](https://github.com/ethyca/fides/pull/4405) + - Allow fides_consent cookie to be set from a subdirectory [#4426](https://github.com/ethyca/fides/pull/4426) + ++### Security ++-- Use a more cryptographically secure random function for security code generation ++ + ## [2.23.3](https://github.com/ethyca/fides/compare/2.23.2...2.23.3) + + ### Fixed +diff --git a/src/fides/api/service/privacy_request/request_runner_service.py b/src/fides/api/service/privacy_request/request_runner_service.py +index d1154ba3e7..266a981cb1 100644 +--- a/src/fides/api/service/privacy_request/request_runner_service.py ++++ b/src/fides/api/service/privacy_request/request_runner_service.py +@@ -1,4 +1,4 @@ +-import random ++import secrets + from datetime import datetime, timedelta + from typing import Any, Dict, List, Optional, Set, Tuple + +@@ -627,7 +627,7 @@ def generate_id_verification_code() -> str: + """ + Generate one-time identity verification code + """ +- return str(random.choice(range(100000, 999999))) ++ return str(secrets.choice(range(100000, 999999))) + + + def _retrieve_child_results( # pylint: disable=R0911 diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..c7b63b8c8ea7561d5f1255c97ea6f4690fbe70c3 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.md @@ -0,0 +1,17 @@ +# Patch-overlapping Python context after the fix + +## `src/fides/api/service/privacy_request/request_runner_service.py` — `function:generate_id_verification_code` (lines 626-630) + +```python +def generate_id_verification_code() -> str: + """ + Generate one-time identity verification code + """ + return str(secrets.choice(range(100000, 999999))) +``` + +## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:@1` (lines 1-1) + +```python +import secrets +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6aa4a079b32fb578ca3509cc63a368a72975a8f1 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.md @@ -0,0 +1,23 @@ +# Patch-overlapping Python context before the fix + +## `src/fides/api/service/privacy_request/request_runner_service.py` — `function:generate_id_verification_code` (lines 626-630) + +```python +def generate_id_verification_code() -> str: + """ + Generate one-time identity verification code + """ + return str(random.choice(range(100000, 999999))) +``` + +## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:@1` (lines 1-1) + +```python +import random +``` + +## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:@2` (lines 2-2) + +```python +from datetime import datetime, timedelta +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9a0e606e2bb8be9fa2c2b38579f89c6042edc417 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.json @@ -0,0 +1,47 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-3062589ff0b3b95c2ed7", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-3062589ff0b3b95c2ed7", + "project_id": "pyvul__ethyca__fides", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "src/fides/api/service/privacy_request/request_runner_service.py" + ], + "patch_units": { + "before": [ + "function:generate_id_verification_code", + "module:@1", + "module:@2" + ], + "after": [ + "function:generate_id_verification_code", + "module:@1" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/291915565ab089440fa07a9c16ad27e6484f7368a306466a2d88660ed05eb343/database", + "cache_key": "291915565ab089440fa07a9c16ad27e6484f7368a306466a2d88660ed05eb343", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/d92a2bb5d4325e1848a36ffc9bc6d9851def586947106947d01f951ef76928e5/database", + "cache_key": "d92a2bb5d4325e1848a36ffc9bc6d9851def586947106947d01f951ef76928e5", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/f593a9e7147144ea94ddd83cc757db32e281fcd6c70e757a340641032a902d52/database", + "cache_key": "f593a9e7147144ea94ddd83cc757db32e281fcd6c70e757a340641032a902d52", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-3062589ff0b3b95c2ed7/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-3062589ff0b3b95c2ed7/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3e97c24ee32c04860bad3ae477d6bbf82a6dc398 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diff @@ -0,0 +1,39 @@ +diff --git a/requirements.txt b/requirements.txt +index 7d2f3f5..9d73a97 100644 +--- a/requirements.txt ++++ b/requirements.txt +@@ -1,7 +1,7 @@ + Markdown==2.6.8 + Pygments==1.6 + Jinja2==2.7.3 +-PyYAML==3.11 ++PyYAML==5.1 + docopt==0.6.1 + ordereddict==1.1 + watchdog==0.8.3 +diff --git a/simiki/config.py b/simiki/config.py +index c0a1ef3..790178b 100644 +--- a/simiki/config.py ++++ b/simiki/config.py +@@ -61,7 +61,7 @@ def parse_config(config_file): + default_config = _set_default_config() + + with io.open(config_file, "rt", encoding="utf-8") as fd: +- config = yaml.load(fd) ++ config = yaml.load(fd, Loader=yaml.FullLoader) + + default_config.update(config) + config = _post_process(default_config) +diff --git a/simiki/generators.py b/simiki/generators.py +index 9816df0..148908b 100644 +--- a/simiki/generators.py ++++ b/simiki/generators.py +@@ -208,7 +208,7 @@ class PageGenerator(BaseGenerator): + def parse_meta(self, yaml_str): + """Parse meta from yaml string, and validate yaml filed, return dict""" + try: +- meta = yaml.load(yaml_str) ++ meta = yaml.load(yaml_str, Loader=yaml.FullLoader) + except yaml.YAMLError as e: + e.extra_msg = 'yaml format error' + raise diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..73b66f41602aea853db946baec8c5129b3918f84 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.md @@ -0,0 +1,244 @@ +# Patch-overlapping Python context after the fix + +## `simiki/config.py` — `function:parse_config` (lines 57-69) + +```python +def parse_config(config_file): + if not os.path.exists(config_file): + raise ConfigFileNotFound("{0} not exists".format(config_file)) + + default_config = _set_default_config() + + with io.open(config_file, "rt", encoding="utf-8") as fd: + config = yaml.load(fd, Loader=yaml.FullLoader) + + default_config.update(config) + config = _post_process(default_config) + + return config +``` + +## `simiki/generators.py` — `class:PageGenerator` (lines 92-284) + +```python +class PageGenerator(BaseGenerator): + + def __init__(self, site_config, base_path, tags=None): + super(PageGenerator, self).__init__(site_config, base_path) + self._tags = tags + self._reset() + + def _reset(self): + """Reset the global self variables""" + self._src_file = None # source file path relative to base_path + self.meta = None + self.content = None + + def to_html(self, src_file, include_draft=False): + """Load template, and generate html + + :src_file: the filename of the source file. This can either be an + absolute filename or a filename relative to the base path. + :include_draft: True/False, include draft pages or not to generate + """ + self._reset() + self._src_file = os.path.relpath(src_file, self.base_path) + self.meta, self.content = self.get_meta_and_content() + # Page set `draft: True' mark current page as draft, and will + # be ignored if not forced generate include draft pages + if not include_draft and self.meta.get('draft', False): + return None + layout = self.get_layout(self.meta) + template_vars = self.get_template_vars(self.meta, self.content) + template = self.get_template(layout) + html = template.render(template_vars) + + return html + + @property + def src_file(self): + return self._src_file + + @src_file.setter + def src_file(self, filename): + self._src_file = os.path.relpath(filename, self.base_path) + + def get_meta_and_content(self, do_render=True): + meta_str, content_str = self.extract_page(self._src_file) + meta = self.parse_meta(meta_str) + # This is the most time consuming part + if do_render and meta.get('render', True): + content = self._parse_markup(content_str) + else: + content = content_str + + return meta, content + + def get_layout(self, meta): + """Get layout config in meta, default is `page'""" + if "layout" in meta: + # Compatible with previous version, which default layout is "post" + # XXX Will remove this checker in v2.0 + if meta["layout"] == "post": + warn_msg = "{0}: layout `post' is deprecated, use `page'" \ + .format(self._src_file) + if is_py2: + # XXX: warnings message require str, no matter whether + # py2 or py3; but in py3, bytes message is ok in simple + # test, but failed in unittest with py3.3, ok with py3.4? + warn_msg = warn_msg.encode('utf-8') + warnings.warn(warn_msg, DeprecationWarning) + layout = "page" + else: + layout = meta["layout"] + else: + layout = "page" + + return layout + + def get_template_vars(self, meta, content): + """Get template variables, include site config and page config""" + template_vars = copy.deepcopy(self._template_vars) + page = {"content": content} + page.update(meta) + page.update({'relation': self.get_relation()}) + + template_vars.update({'page': page}) + + return template_vars + + def get_category_and_file(self): + """Get the name of category and file(with extension)""" + src_file_relpath_to_source = \ + os.path.relpath(self._src_file, self.site_config['source']) + category, filename = os.path.split(src_file_relpath_to_source) + return (category, filename) + + @staticmethod + def extract_page(filename): + """Split the page file texts by triple-dashed lines, return the mata + and content. + + :param filename: the filename of markup page + + returns: + meta_str (str): page's meta string + content_str (str): html parsed from markdown or other markup text. + """ + regex = re.compile('(?sm)^---(?P.*?)^---(?P.*)') + with io.open(filename, "rt", encoding="utf-8") as fd: + match_obj = re.match(regex, fd.read()) + if match_obj: + meta_str = match_obj.group('meta') + content_str = match_obj.group('body') + else: + raise Exception('extracting page with format error, ' + 'see ') + + return meta_str, content_str + + def parse_meta(self, yaml_str): + """Parse meta from yaml string, and validate yaml filed, return dict""" + try: + meta = yaml.load(yaml_str, Loader=yaml.FullLoader) + except yaml.YAMLError as e: + e.extra_msg = 'yaml format error' + raise + + category, src_fname = self.get_category_and_file() + dst_fname = src_fname.replace( + ".{0}".format(self.site_config['default_ext']), '.html') + meta.update({'category': category, 'filename': dst_fname}) + + if 'tag' in meta: + if isinstance(meta['tag'], basestring): + _tags = [t.strip() for t in meta['tag'].split(',')] + meta.update({'tag': _tags}) + + if "title" not in meta: + raise Exception("no 'title' in meta") + + return meta + + def _parse_markup(self, markup_text): + """Parse markup text to html + + Only support Markdown for now. + """ + markdown_extensions = self._set_markdown_extensions() + + html_content = markdown.markdown( + markup_text, + extensions=markdown_extensions, + ) + + return html_content + + def _set_markdown_extensions(self): + """Set the extensions for markdown parser""" + # Default enabled extensions + markdown_extensions_config = { + "fenced_code": {}, + "nl2br": {}, + "toc": {"title": "Table of Contents"}, + "extra": {}, + } + # Handle pygments + if self.site_config["pygments"]: + markdown_extensions_config.update({ + "codehilite": {"css_class": "hlcode"} + }) + # Handle markdown_ext + # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa + if "markdown_ext" in self.site_config: + markdown_extensions_config.update(self.site_config["markdown_ext"]) + + markdown_extensions = [] + for k, v in markdown_extensions_config.items(): + ext = import_string("markdown.extensions." + k).makeExtension() + if v: + for i, j in v.items(): + ext.setConfig(i, j) + markdown_extensions.append(ext) + + return markdown_extensions + + def get_relation(self): + rn = [] + if self._tags and 'tag' in self.meta: + for t in self.meta['tag']: + rn.extend(self._tags[t]) + # remove itself + rn = [r for r in rn if self.meta['title'] != r['title']] + # remove the duplicate items + # note this will change the items order + rn = [r for n, r in enumerate(rn) if r not in rn[n+1:]] # noqa: E226 + return rn +``` + +## `simiki/generators.py` — `function:PageGenerator.parse_meta` (lines 208-229) + +```python + def parse_meta(self, yaml_str): + """Parse meta from yaml string, and validate yaml filed, return dict""" + try: + meta = yaml.load(yaml_str, Loader=yaml.FullLoader) + except yaml.YAMLError as e: + e.extra_msg = 'yaml format error' + raise + + category, src_fname = self.get_category_and_file() + dst_fname = src_fname.replace( + ".{0}".format(self.site_config['default_ext']), '.html') + meta.update({'category': category, 'filename': dst_fname}) + + if 'tag' in meta: + if isinstance(meta['tag'], basestring): + _tags = [t.strip() for t in meta['tag'].split(',')] + meta.update({'tag': _tags}) + + if "title" not in meta: + raise Exception("no 'title' in meta") + + return meta +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..d865c0ab060e4e2521d263c71f648fa5390e84dd --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.md @@ -0,0 +1,244 @@ +# Patch-overlapping Python context before the fix + +## `simiki/config.py` — `function:parse_config` (lines 57-69) + +```python +def parse_config(config_file): + if not os.path.exists(config_file): + raise ConfigFileNotFound("{0} not exists".format(config_file)) + + default_config = _set_default_config() + + with io.open(config_file, "rt", encoding="utf-8") as fd: + config = yaml.load(fd) + + default_config.update(config) + config = _post_process(default_config) + + return config +``` + +## `simiki/generators.py` — `class:PageGenerator` (lines 92-284) + +```python +class PageGenerator(BaseGenerator): + + def __init__(self, site_config, base_path, tags=None): + super(PageGenerator, self).__init__(site_config, base_path) + self._tags = tags + self._reset() + + def _reset(self): + """Reset the global self variables""" + self._src_file = None # source file path relative to base_path + self.meta = None + self.content = None + + def to_html(self, src_file, include_draft=False): + """Load template, and generate html + + :src_file: the filename of the source file. This can either be an + absolute filename or a filename relative to the base path. + :include_draft: True/False, include draft pages or not to generate + """ + self._reset() + self._src_file = os.path.relpath(src_file, self.base_path) + self.meta, self.content = self.get_meta_and_content() + # Page set `draft: True' mark current page as draft, and will + # be ignored if not forced generate include draft pages + if not include_draft and self.meta.get('draft', False): + return None + layout = self.get_layout(self.meta) + template_vars = self.get_template_vars(self.meta, self.content) + template = self.get_template(layout) + html = template.render(template_vars) + + return html + + @property + def src_file(self): + return self._src_file + + @src_file.setter + def src_file(self, filename): + self._src_file = os.path.relpath(filename, self.base_path) + + def get_meta_and_content(self, do_render=True): + meta_str, content_str = self.extract_page(self._src_file) + meta = self.parse_meta(meta_str) + # This is the most time consuming part + if do_render and meta.get('render', True): + content = self._parse_markup(content_str) + else: + content = content_str + + return meta, content + + def get_layout(self, meta): + """Get layout config in meta, default is `page'""" + if "layout" in meta: + # Compatible with previous version, which default layout is "post" + # XXX Will remove this checker in v2.0 + if meta["layout"] == "post": + warn_msg = "{0}: layout `post' is deprecated, use `page'" \ + .format(self._src_file) + if is_py2: + # XXX: warnings message require str, no matter whether + # py2 or py3; but in py3, bytes message is ok in simple + # test, but failed in unittest with py3.3, ok with py3.4? + warn_msg = warn_msg.encode('utf-8') + warnings.warn(warn_msg, DeprecationWarning) + layout = "page" + else: + layout = meta["layout"] + else: + layout = "page" + + return layout + + def get_template_vars(self, meta, content): + """Get template variables, include site config and page config""" + template_vars = copy.deepcopy(self._template_vars) + page = {"content": content} + page.update(meta) + page.update({'relation': self.get_relation()}) + + template_vars.update({'page': page}) + + return template_vars + + def get_category_and_file(self): + """Get the name of category and file(with extension)""" + src_file_relpath_to_source = \ + os.path.relpath(self._src_file, self.site_config['source']) + category, filename = os.path.split(src_file_relpath_to_source) + return (category, filename) + + @staticmethod + def extract_page(filename): + """Split the page file texts by triple-dashed lines, return the mata + and content. + + :param filename: the filename of markup page + + returns: + meta_str (str): page's meta string + content_str (str): html parsed from markdown or other markup text. + """ + regex = re.compile('(?sm)^---(?P.*?)^---(?P.*)') + with io.open(filename, "rt", encoding="utf-8") as fd: + match_obj = re.match(regex, fd.read()) + if match_obj: + meta_str = match_obj.group('meta') + content_str = match_obj.group('body') + else: + raise Exception('extracting page with format error, ' + 'see ') + + return meta_str, content_str + + def parse_meta(self, yaml_str): + """Parse meta from yaml string, and validate yaml filed, return dict""" + try: + meta = yaml.load(yaml_str) + except yaml.YAMLError as e: + e.extra_msg = 'yaml format error' + raise + + category, src_fname = self.get_category_and_file() + dst_fname = src_fname.replace( + ".{0}".format(self.site_config['default_ext']), '.html') + meta.update({'category': category, 'filename': dst_fname}) + + if 'tag' in meta: + if isinstance(meta['tag'], basestring): + _tags = [t.strip() for t in meta['tag'].split(',')] + meta.update({'tag': _tags}) + + if "title" not in meta: + raise Exception("no 'title' in meta") + + return meta + + def _parse_markup(self, markup_text): + """Parse markup text to html + + Only support Markdown for now. + """ + markdown_extensions = self._set_markdown_extensions() + + html_content = markdown.markdown( + markup_text, + extensions=markdown_extensions, + ) + + return html_content + + def _set_markdown_extensions(self): + """Set the extensions for markdown parser""" + # Default enabled extensions + markdown_extensions_config = { + "fenced_code": {}, + "nl2br": {}, + "toc": {"title": "Table of Contents"}, + "extra": {}, + } + # Handle pygments + if self.site_config["pygments"]: + markdown_extensions_config.update({ + "codehilite": {"css_class": "hlcode"} + }) + # Handle markdown_ext + # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa + if "markdown_ext" in self.site_config: + markdown_extensions_config.update(self.site_config["markdown_ext"]) + + markdown_extensions = [] + for k, v in markdown_extensions_config.items(): + ext = import_string("markdown.extensions." + k).makeExtension() + if v: + for i, j in v.items(): + ext.setConfig(i, j) + markdown_extensions.append(ext) + + return markdown_extensions + + def get_relation(self): + rn = [] + if self._tags and 'tag' in self.meta: + for t in self.meta['tag']: + rn.extend(self._tags[t]) + # remove itself + rn = [r for r in rn if self.meta['title'] != r['title']] + # remove the duplicate items + # note this will change the items order + rn = [r for n, r in enumerate(rn) if r not in rn[n+1:]] # noqa: E226 + return rn +``` + +## `simiki/generators.py` — `function:PageGenerator.parse_meta` (lines 208-229) + +```python + def parse_meta(self, yaml_str): + """Parse meta from yaml string, and validate yaml filed, return dict""" + try: + meta = yaml.load(yaml_str) + except yaml.YAMLError as e: + e.extra_msg = 'yaml format error' + raise + + category, src_fname = self.get_category_and_file() + dst_fname = src_fname.replace( + ".{0}".format(self.site_config['default_ext']), '.html') + meta.update({'category': category, 'filename': dst_fname}) + + if 'tag' in meta: + if isinstance(meta['tag'], basestring): + _tags = [t.strip() for t in meta['tag'].split(',')] + meta.update({'tag': _tags}) + + if "title" not in meta: + raise Exception("no 'title' in meta") + + return meta +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.json new file mode 100644 index 0000000000000000000000000000000000000000..da84e632d60debe11f335d7a8414da75c51d279f --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.json @@ -0,0 +1,49 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-3187445bcbbf39128a26", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-3187445bcbbf39128a26", + "project_id": "pyvul__tankywoo__simiki", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "simiki/config.py", + "simiki/generators.py" + ], + "patch_units": { + "before": [ + "function:parse_config", + "class:PageGenerator", + "function:PageGenerator.parse_meta" + ], + "after": [ + "function:parse_config", + "class:PageGenerator", + "function:PageGenerator.parse_meta" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/6c677522fd3c28ce7e1472d351798d0e087b50dd4e508e0f5fcc1bee0af173f1/database", + "cache_key": "6c677522fd3c28ce7e1472d351798d0e087b50dd4e508e0f5fcc1bee0af173f1", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/7e613b7efe30230563633a9a574d8c2fa71dcc345fff934fc4de7ceb656cf8fe/database", + "cache_key": "7e613b7efe30230563633a9a574d8c2fa71dcc345fff934fc4de7ceb656cf8fe", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/8d8b60dfa034c14268f005e72f669accfdfac1fb52182a03fea8cd89a0322db3/database", + "cache_key": "8d8b60dfa034c14268f005e72f669accfdfac1fb52182a03fea8cd89a0322db3", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-3187445bcbbf39128a26/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-3187445bcbbf39128a26/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c21dd6d75e644e41e62dc3b3dddab02453ac6f14 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diff @@ -0,0 +1,39 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 225fced44..7bfe08edb 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -663,9 +663,13 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). + + - Fixed an issue where `HorovodStrategy.teardown()` did not complete gracefully if an exception was thrown during callback setup [#11752](https://github.com/PyTorchLightning/pytorch-lightning/pull/11752) + ++ + - Fixed security vulnerabilities CVE-2020-1747 and CVE-2020-14343 caused by the `PyYAML` dependency ([#11099](https://github.com/PyTorchLightning/pytorch-lightning/pull/11099)) + + ++- Fixed security vulnerability "CWE-94: Improper Control of Generation of Code (Code Injection)" ([#12212](https://github.com/PyTorchLightning/pytorch-lightning/pull/12212)) ++ ++ + - Fixed logging on `{test,validation}_epoch_end` with multiple dataloaders ([#11132](https://github.com/PyTorchLightning/pytorch-lightning/pull/11132)) + + +diff --git a/pytorch_lightning/utilities/argparse.py b/pytorch_lightning/utilities/argparse.py +index e729f862c..8927ff093 100644 +--- a/pytorch_lightning/utilities/argparse.py ++++ b/pytorch_lightning/utilities/argparse.py +@@ -17,6 +17,7 @@ import inspect + import os + from abc import ABC + from argparse import _ArgumentGroup, ArgumentParser, Namespace ++from ast import literal_eval + from contextlib import suppress + from functools import wraps + from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union +@@ -121,7 +122,7 @@ def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name) + # todo: specify the possible exception + with suppress(Exception): + # converting to native types like int/float/bool +- val = eval(val) ++ val = literal_eval(val) + env_args[arg_name] = val + return Namespace(**env_args) + diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..4eee86bb47a792c49ba03f37f7458ada3cf59acc --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.md @@ -0,0 +1,40 @@ +# Patch-overlapping Python context after the fix + +## `pytorch_lightning/utilities/argparse.py` — `function:parse_env_variables` (lines 100-127) + +```python +def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: + """Parse environment arguments if they are defined. + + Examples: + + >>> from pytorch_lightning import Trainer + >>> parse_env_variables(Trainer) + Namespace() + >>> import os + >>> os.environ["PL_TRAINER_GPUS"] = '42' + >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' + >>> parse_env_variables(Trainer) + Namespace(gpus=42) + >>> del os.environ["PL_TRAINER_GPUS"] + """ + cls_arg_defaults = get_init_arguments_and_types(cls) + + env_args = {} + for arg_name, _, _ in cls_arg_defaults: + env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} + val = os.environ.get(env) + if not (val is None or val == ""): + # todo: specify the possible exception + with suppress(Exception): + # converting to native types like int/float/bool + val = literal_eval(val) + env_args[arg_name] = val + return Namespace(**env_args) +``` + +## `pytorch_lightning/utilities/argparse.py` — `module:@20` (lines 20-20) + +```python +from ast import literal_eval +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..13fe96a596203169d8a5225f967d06218aa988b9 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.md @@ -0,0 +1,40 @@ +# Patch-overlapping Python context before the fix + +## `pytorch_lightning/utilities/argparse.py` — `function:parse_env_variables` (lines 99-126) + +```python +def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: + """Parse environment arguments if they are defined. + + Examples: + + >>> from pytorch_lightning import Trainer + >>> parse_env_variables(Trainer) + Namespace() + >>> import os + >>> os.environ["PL_TRAINER_GPUS"] = '42' + >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' + >>> parse_env_variables(Trainer) + Namespace(gpus=42) + >>> del os.environ["PL_TRAINER_GPUS"] + """ + cls_arg_defaults = get_init_arguments_and_types(cls) + + env_args = {} + for arg_name, _, _ in cls_arg_defaults: + env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} + val = os.environ.get(env) + if not (val is None or val == ""): + # todo: specify the possible exception + with suppress(Exception): + # converting to native types like int/float/bool + val = eval(val) + env_args[arg_name] = val + return Namespace(**env_args) +``` + +## `pytorch_lightning/utilities/argparse.py` — `module:@20` (lines 20-20) + +```python +from contextlib import suppress +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.json new file mode 100644 index 0000000000000000000000000000000000000000..66a51d4c123c3b8de76c829cae09974f641d342c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-36a40541d7c74a9a7777", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-36a40541d7c74a9a7777", + "project_id": "pyvul__pytorchlightning__pytorch-lightning", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "pytorch_lightning/utilities/argparse.py" + ], + "patch_units": { + "before": [ + "function:parse_env_variables", + "module:@20" + ], + "after": [ + "function:parse_env_variables", + "module:@20" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/f904a001805ca2a12850f3d3056b70f7b209467a621d3da7fe0e4e98faa4b9c9/database", + "cache_key": "f904a001805ca2a12850f3d3056b70f7b209467a621d3da7fe0e4e98faa4b9c9", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/f9a6566d69a61c361650443ebcecb4d650d674333e5dda7f6c57320a8ff0a764/database", + "cache_key": "f9a6566d69a61c361650443ebcecb4d650d674333e5dda7f6c57320a8ff0a764", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/0e9729244a800a484f57498b45d84807d5007185f2cdaea70346b3a3ea9f43bc/database", + "cache_key": "0e9729244a800a484f57498b45d84807d5007185f2cdaea70346b3a3ea9f43bc", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-36a40541d7c74a9a7777/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-36a40541d7c74a9a7777/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..59d978e54ecb55f9936d0f837e7c762e33fe5477 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diff @@ -0,0 +1,32 @@ +diff --git a/templated_dictionary/__init__.py b/templated_dictionary/__init__.py +index 994166a..ec004c0 100644 +--- a/templated_dictionary/__init__.py ++++ b/templated_dictionary/__init__.py +@@ -2,7 +2,7 @@ + # vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:textwidth=0: + + from collections.abc import MutableMapping +-import jinja2 ++from jinja2 import sandbox + + + # pylint: disable=no-member,unsupported-assignment-operation +@@ -19,6 +19,8 @@ class TemplatedDictionary(MutableMapping): + ''' + self.__dict__.update(*args, **kwargs) + ++ self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True) ++ + self._aliases = {} + if alias_spec: + for aliased_to, aliases in alias_spec.items(): +@@ -80,8 +82,7 @@ class TemplatedDictionary(MutableMapping): + orig = last = value + max_recursion = self.__dict__.get('jinja_max_recursion', 5) + for _ in range(max_recursion): +- template = jinja2.Template(value, keep_trailing_newline=True) +- value = _to_native(template.render(self.__dict__)) ++ value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) + if value == last: + return value + last = value diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..27687ed1e88d2af01e1856e2a56966101f89d642 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.md @@ -0,0 +1,130 @@ +# Patch-overlapping Python context after the fix + +## `templated_dictionary/__init__.py` — `class:TemplatedDictionary` (lines 9-89) + +```python +class TemplatedDictionary(MutableMapping): + """ Dictionary where __getitem__() is run through Jinja2 template """ + def __init__(self, *args, alias_spec=None, **kwargs): + ''' + Use the object dict. + + Optional parameter 'alias_spec' is dictionary of form: + {'aliased_to': ['alias_one', 'alias_two', ...], ...} + When specified, and one of the aliases is accessed - the + 'aliased_to' config option is returned. + ''' + self.__dict__.update(*args, **kwargs) + + self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True) + + self._aliases = {} + if alias_spec: + for aliased_to, aliases in alias_spec.items(): + for alias in aliases: + self._aliases[alias] = aliased_to + + # The next five methods are requirements of the ABC. + def __setitem__(self, key, value): + key = self._aliases.get(key, key) + self.__dict__[key] = value + + def __getitem__(self, key): + key = self._aliases.get(key, key) + if '__jinja_expand' in self.__dict__ and self.__dict__['__jinja_expand']: + return self.__render_value(self.__dict__[key]) + return self.__dict__[key] + + def __delitem__(self, key): + del self.__dict__[key] + + def __iter__(self): + return iter(self.__dict__) + + def __len__(self): + return len(self.__dict__) + + # The final two methods aren't required, but nice to have + def __str__(self): + '''returns simple dict representation of the mapping''' + return str(self.__dict__) + + def __repr__(self): + '''echoes class, id, & reproducible representation in the REPL''' + return '{}, TemplatedDictionary({})'.format(super(TemplatedDictionary, self).__repr__(), + self.__dict__) + + def copy(self): + return TemplatedDictionary(self.__dict__) + + def __render_value(self, value): + if isinstance(value, str): + return self.__render_string(value) + elif isinstance(value, list): + # we cannot use list comprehension here, as we need to NOT modify the list (pointer to list) + # and we need to modifiy only individual values in the list + # If we would create new list, we cannot assign to it, which often happens in configs (e.g. plugins) + for i in range(len(value)): # pylint: disable=consider-using-enumerate + value[i] = self.__render_value(value[i]) + return value + elif isinstance(value, dict): + # we cannot use list comprehension here, same reasoning as for `list` above + for k in value.keys(): + value[k] = self.__render_value(value[k]) + return value + else: + return value + + def __render_string(self, value): + orig = last = value + max_recursion = self.__dict__.get('jinja_max_recursion', 5) + for _ in range(max_recursion): + value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) + if value == last: + return value + last = value + raise ValueError("too deep jinja re-evaluation on '{}'".format(orig)) +``` + +## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__init__` (lines 11-28) + +```python + def __init__(self, *args, alias_spec=None, **kwargs): + ''' + Use the object dict. + + Optional parameter 'alias_spec' is dictionary of form: + {'aliased_to': ['alias_one', 'alias_two', ...], ...} + When specified, and one of the aliases is accessed - the + 'aliased_to' config option is returned. + ''' + self.__dict__.update(*args, **kwargs) + + self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True) + + self._aliases = {} + if alias_spec: + for aliased_to, aliases in alias_spec.items(): + for alias in aliases: + self._aliases[alias] = aliased_to +``` + +## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__render_string` (lines 81-89) + +```python + def __render_string(self, value): + orig = last = value + max_recursion = self.__dict__.get('jinja_max_recursion', 5) + for _ in range(max_recursion): + value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) + if value == last: + return value + last = value + raise ValueError("too deep jinja re-evaluation on '{}'".format(orig)) +``` + +## `templated_dictionary/__init__.py` — `module:@5` (lines 5-5) + +```python +from jinja2 import sandbox +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..4cf743e68b9c9617e3613e91b3319858393dc9bf --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.md @@ -0,0 +1,128 @@ +# Patch-overlapping Python context before the fix + +## `templated_dictionary/__init__.py` — `class:TemplatedDictionary` (lines 9-88) + +```python +class TemplatedDictionary(MutableMapping): + """ Dictionary where __getitem__() is run through Jinja2 template """ + def __init__(self, *args, alias_spec=None, **kwargs): + ''' + Use the object dict. + + Optional parameter 'alias_spec' is dictionary of form: + {'aliased_to': ['alias_one', 'alias_two', ...], ...} + When specified, and one of the aliases is accessed - the + 'aliased_to' config option is returned. + ''' + self.__dict__.update(*args, **kwargs) + + self._aliases = {} + if alias_spec: + for aliased_to, aliases in alias_spec.items(): + for alias in aliases: + self._aliases[alias] = aliased_to + + # The next five methods are requirements of the ABC. + def __setitem__(self, key, value): + key = self._aliases.get(key, key) + self.__dict__[key] = value + + def __getitem__(self, key): + key = self._aliases.get(key, key) + if '__jinja_expand' in self.__dict__ and self.__dict__['__jinja_expand']: + return self.__render_value(self.__dict__[key]) + return self.__dict__[key] + + def __delitem__(self, key): + del self.__dict__[key] + + def __iter__(self): + return iter(self.__dict__) + + def __len__(self): + return len(self.__dict__) + + # The final two methods aren't required, but nice to have + def __str__(self): + '''returns simple dict representation of the mapping''' + return str(self.__dict__) + + def __repr__(self): + '''echoes class, id, & reproducible representation in the REPL''' + return '{}, TemplatedDictionary({})'.format(super(TemplatedDictionary, self).__repr__(), + self.__dict__) + + def copy(self): + return TemplatedDictionary(self.__dict__) + + def __render_value(self, value): + if isinstance(value, str): + return self.__render_string(value) + elif isinstance(value, list): + # we cannot use list comprehension here, as we need to NOT modify the list (pointer to list) + # and we need to modifiy only individual values in the list + # If we would create new list, we cannot assign to it, which often happens in configs (e.g. plugins) + for i in range(len(value)): # pylint: disable=consider-using-enumerate + value[i] = self.__render_value(value[i]) + return value + elif isinstance(value, dict): + # we cannot use list comprehension here, same reasoning as for `list` above + for k in value.keys(): + value[k] = self.__render_value(value[k]) + return value + else: + return value + + def __render_string(self, value): + orig = last = value + max_recursion = self.__dict__.get('jinja_max_recursion', 5) + for _ in range(max_recursion): + template = jinja2.Template(value, keep_trailing_newline=True) + value = _to_native(template.render(self.__dict__)) + if value == last: + return value + last = value + raise ValueError("too deep jinja re-evaluation on '{}'".format(orig)) +``` + +## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__init__` (lines 11-26) + +```python + def __init__(self, *args, alias_spec=None, **kwargs): + ''' + Use the object dict. + + Optional parameter 'alias_spec' is dictionary of form: + {'aliased_to': ['alias_one', 'alias_two', ...], ...} + When specified, and one of the aliases is accessed - the + 'aliased_to' config option is returned. + ''' + self.__dict__.update(*args, **kwargs) + + self._aliases = {} + if alias_spec: + for aliased_to, aliases in alias_spec.items(): + for alias in aliases: + self._aliases[alias] = aliased_to +``` + +## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__render_string` (lines 79-88) + +```python + def __render_string(self, value): + orig = last = value + max_recursion = self.__dict__.get('jinja_max_recursion', 5) + for _ in range(max_recursion): + template = jinja2.Template(value, keep_trailing_newline=True) + value = _to_native(template.render(self.__dict__)) + if value == last: + return value + last = value + raise ValueError("too deep jinja re-evaluation on '{}'".format(orig)) +``` + +## `templated_dictionary/__init__.py` — `module:@5` (lines 5-5) + +```python +import jinja2 +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2d969eb31a285a0dd8a936419bbcfc9857b59cdb --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-3819b1a7530257524a75", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-3819b1a7530257524a75", + "project_id": "pyvul__xsuchy__templated-dictionary", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "templated_dictionary/__init__.py" + ], + "patch_units": { + "before": [ + "class:TemplatedDictionary", + "function:TemplatedDictionary.__init__", + "function:TemplatedDictionary.__render_string", + "module:@5" + ], + "after": [ + "class:TemplatedDictionary", + "function:TemplatedDictionary.__init__", + "function:TemplatedDictionary.__render_string", + "module:@5" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/60090dd1e3d668fdc545d407347c4a6ba0250326e30297f90b2d463919aae8b3/database", + "cache_key": "60090dd1e3d668fdc545d407347c4a6ba0250326e30297f90b2d463919aae8b3", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/95b9d1bbebc8c5a413369012e35afae0fd0b6205fae69cab5ce281dfe2a80f3d/database", + "cache_key": "95b9d1bbebc8c5a413369012e35afae0fd0b6205fae69cab5ce281dfe2a80f3d", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/9782c933de0fe5c1d90834d158773b8aa4076e68abc282bfc920352b51cc5b7b/database", + "cache_key": "9782c933de0fe5c1d90834d158773b8aa4076e68abc282bfc920352b51cc5b7b", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-3819b1a7530257524a75/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-3819b1a7530257524a75/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6d4fc9b67b4209bb4a84eff23b95d7c87c426c5d --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diff @@ -0,0 +1,53 @@ +diff --git a/petl/io/xml.py b/petl/io/xml.py +index 983d9f6..b63287c 100644 +--- a/petl/io/xml.py ++++ b/petl/io/xml.py +@@ -133,6 +133,9 @@ def fromxml(source, *args, **kwargs): + or list of paths can be provided, e.g., + ``fromxml('example.html', './/tr', ('th', 'td'))``. + ++ Optionally a custom parser can be provided, e.g., ++ ``etl.fromxml('example1.xml', 'tr', 'td', parser=my_parser)``. ++ + """ + + source = read_source_from_arg(source) +@@ -162,14 +165,15 @@ class XmlView(Table): + else: + assert False, 'bad parameters' + self.missing = kwargs.get('missing', None) ++ self.user_parser = kwargs.get('parser', None) + + def __iter__(self): + vmatch = self.vmatch + vdict = self.vdict + + with self.source.open('rb') as xmlf: +- +- tree = etree.parse(xmlf) ++ parser2 = _create_xml_parser(self.user_parser) ++ tree = etree.parse(xmlf, parser=parser2) + if not hasattr(tree, 'iterfind'): + # Python 2.6 compatibility + tree.iterfind = tree.findall +@@ -219,6 +223,20 @@ class XmlView(Table): + for f in flds) + + ++def _create_xml_parser(user_parser): ++ if user_parser is not None: ++ return user_parser ++ try: ++ # Default lxml parser. ++ # This will throw an error if parser is not set and lxml could not be imported ++ # because Python's built XML parser doesn't like the `resolve_entities` kwarg. ++ # return etree.XMLParser(resolve_entities=False) ++ return etree.XMLParser(resolve_entities=False) ++ except TypeError: ++ # lxml not available ++ return None ++ ++ + def element_text_getter(missing): + def _get(v): + if len(v) > 1: diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6c1e9723273b6d52f4d4f23a2ba0bb6ae1a2879c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.md @@ -0,0 +1,314 @@ +# Patch-overlapping Python context after the fix + +## `petl/io/xml.py` — `function:fromxml` (lines 22-142) + +```python +def fromxml(source, *args, **kwargs): + """ + Extract data from an XML file. E.g.:: + + >>> import petl as etl + >>> # setup a file to demonstrate with + ... d = ''' + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ...
foobar
a1
b2
c2
''' + >>> with open('example1.xml', 'w') as f: + ... f.write(d) + ... + 212 + >>> table1 = etl.fromxml('example1.xml', 'tr', 'td') + >>> table1 + +-----+-----+ + | foo | bar | + +=====+=====+ + | 'a' | '1' | + +-----+-----+ + | 'b' | '2' | + +-----+-----+ + | 'c' | '2' | + +-----+-----+ + + + If the data values are stored in an attribute, provide the attribute + name as an extra positional argument:: + + >>> d = ''' + ... + ... + ... + ... + ... + ... + ... + ... + ...
+ ...
+ ...
+ ...
+ ...
''' + >>> with open('example2.xml', 'w') as f: + ... f.write(d) + ... + 220 + >>> table2 = etl.fromxml('example2.xml', 'tr', 'td', 'v') + >>> table2 + +-----+-----+ + | foo | bar | + +=====+=====+ + | 'a' | '1' | + +-----+-----+ + | 'b' | '2' | + +-----+-----+ + | 'c' | '2' | + +-----+-----+ + + Data values can also be extracted by providing a mapping of field + names to element paths:: + + >>> d = ''' + ... + ... a + ... + ... + ... b + ... + ... + ... c + ... + ...
''' + >>> with open('example3.xml', 'w') as f: + ... f.write(d) + ... + 223 + >>> table3 = etl.fromxml('example3.xml', 'row', + ... {'foo': 'foo', 'bar': ('baz/bar', 'v')}) + >>> table3 + +------------+-----+ + | bar | foo | + +============+=====+ + | ('1', '3') | 'a' | + +------------+-----+ + | '2' | 'b' | + +------------+-----+ + | '2' | 'c' | + +------------+-----+ + + If `lxml `_ is installed, full XPath expressions can be + used. + + Note that the implementation is currently **not** streaming, i.e., + the whole document is loaded into memory. + + If multiple elements match a given field, all values are reported as a + tuple. + + If there is more than one element name used for row values, a tuple + or list of paths can be provided, e.g., + ``fromxml('example.html', './/tr', ('th', 'td'))``. + + Optionally a custom parser can be provided, e.g., + ``etl.fromxml('example1.xml', 'tr', 'td', parser=my_parser)``. + + """ + + source = read_source_from_arg(source) + return XmlView(source, *args, **kwargs) +``` + +## `petl/io/xml.py` — `class:XmlView` (lines 145-223) + +```python +class XmlView(Table): + + def __init__(self, source, *args, **kwargs): + self.source = source + self.args = args + if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)): + self.rmatch = args[0] + self.vmatch = args[1] + self.vdict = None + self.attr = None + elif len(args) == 2 and isinstance(args[1], dict): + self.rmatch = args[0] + self.vmatch = None + self.vdict = args[1] + self.attr = None + elif len(args) == 3: + self.rmatch = args[0] + self.vmatch = args[1] + self.vdict = None + self.attr = args[2] + else: + assert False, 'bad parameters' + self.missing = kwargs.get('missing', None) + self.user_parser = kwargs.get('parser', None) + + def __iter__(self): + vmatch = self.vmatch + vdict = self.vdict + + with self.source.open('rb') as xmlf: + parser2 = _create_xml_parser(self.user_parser) + tree = etree.parse(xmlf, parser=parser2) + if not hasattr(tree, 'iterfind'): + # Python 2.6 compatibility + tree.iterfind = tree.findall + + if vmatch is not None: + # simple case, all value paths are the same + for rowelm in tree.iterfind(self.rmatch): + if self.attr is None: + getv = attrgetter('text') + else: + getv = lambda e: e.get(self.attr) + if isinstance(vmatch, string_types): + # match only one path + velms = rowelm.findall(vmatch) + else: + # match multiple paths + velms = itertools.chain(*[rowelm.findall(enm) + for enm in vmatch]) + yield tuple(getv(velm) + for velm in velms) + + else: + # difficult case, deal with different paths for each field + + # determine output header + flds = tuple(sorted(map(text_type, vdict.keys()))) + yield flds + + # setup value getters + vmatches = dict() + vgetters = dict() + for f in flds: + vmatch = self.vdict[f] + if isinstance(vmatch, string_types): + # match element path + vmatches[f] = vmatch + vgetters[f] = element_text_getter(self.missing) + else: + # match element path and attribute name + vmatches[f] = vmatch[0] + attr = vmatch[1] + vgetters[f] = attribute_text_getter(attr, self.missing) + + # determine data rows + for rowelm in tree.iterfind(self.rmatch): + yield tuple(vgetters[f](rowelm.findall(vmatches[f])) + for f in flds) +``` + +## `petl/io/xml.py` — `function:XmlView.__init__` (lines 147-168) + +```python + def __init__(self, source, *args, **kwargs): + self.source = source + self.args = args + if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)): + self.rmatch = args[0] + self.vmatch = args[1] + self.vdict = None + self.attr = None + elif len(args) == 2 and isinstance(args[1], dict): + self.rmatch = args[0] + self.vmatch = None + self.vdict = args[1] + self.attr = None + elif len(args) == 3: + self.rmatch = args[0] + self.vmatch = args[1] + self.vdict = None + self.attr = args[2] + else: + assert False, 'bad parameters' + self.missing = kwargs.get('missing', None) + self.user_parser = kwargs.get('parser', None) +``` + +## `petl/io/xml.py` — `function:XmlView.__iter__` (lines 170-223) + +```python + def __iter__(self): + vmatch = self.vmatch + vdict = self.vdict + + with self.source.open('rb') as xmlf: + parser2 = _create_xml_parser(self.user_parser) + tree = etree.parse(xmlf, parser=parser2) + if not hasattr(tree, 'iterfind'): + # Python 2.6 compatibility + tree.iterfind = tree.findall + + if vmatch is not None: + # simple case, all value paths are the same + for rowelm in tree.iterfind(self.rmatch): + if self.attr is None: + getv = attrgetter('text') + else: + getv = lambda e: e.get(self.attr) + if isinstance(vmatch, string_types): + # match only one path + velms = rowelm.findall(vmatch) + else: + # match multiple paths + velms = itertools.chain(*[rowelm.findall(enm) + for enm in vmatch]) + yield tuple(getv(velm) + for velm in velms) + + else: + # difficult case, deal with different paths for each field + + # determine output header + flds = tuple(sorted(map(text_type, vdict.keys()))) + yield flds + + # setup value getters + vmatches = dict() + vgetters = dict() + for f in flds: + vmatch = self.vdict[f] + if isinstance(vmatch, string_types): + # match element path + vmatches[f] = vmatch + vgetters[f] = element_text_getter(self.missing) + else: + # match element path and attribute name + vmatches[f] = vmatch[0] + attr = vmatch[1] + vgetters[f] = attribute_text_getter(attr, self.missing) + + # determine data rows + for rowelm in tree.iterfind(self.rmatch): + yield tuple(vgetters[f](rowelm.findall(vmatches[f])) + for f in flds) +``` + +## `petl/io/xml.py` — `function:_create_xml_parser` (lines 226-237) + +```python +def _create_xml_parser(user_parser): + if user_parser is not None: + return user_parser + try: + # Default lxml parser. + # This will throw an error if parser is not set and lxml could not be imported + # because Python's built XML parser doesn't like the `resolve_entities` kwarg. + # return etree.XMLParser(resolve_entities=False) + return etree.XMLParser(resolve_entities=False) + except TypeError: + # lxml not available + return None +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..c05c0671bb1da890d7282cf74174029b357b9242 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.md @@ -0,0 +1,280 @@ +# Patch-overlapping Python context before the fix + +## `petl/io/xml.py` — `function:fromxml` (lines 22-139) + +```python +def fromxml(source, *args, **kwargs): + """ + Extract data from an XML file. E.g.:: + + >>> import petl as etl + >>> # setup a file to demonstrate with + ... d = ''' + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ...
foobar
a1
b2
c2
''' + >>> with open('example1.xml', 'w') as f: + ... f.write(d) + ... + 212 + >>> table1 = etl.fromxml('example1.xml', 'tr', 'td') + >>> table1 + +-----+-----+ + | foo | bar | + +=====+=====+ + | 'a' | '1' | + +-----+-----+ + | 'b' | '2' | + +-----+-----+ + | 'c' | '2' | + +-----+-----+ + + + If the data values are stored in an attribute, provide the attribute + name as an extra positional argument:: + + >>> d = ''' + ... + ... + ... + ... + ... + ... + ... + ... + ...
+ ...
+ ...
+ ...
+ ...
''' + >>> with open('example2.xml', 'w') as f: + ... f.write(d) + ... + 220 + >>> table2 = etl.fromxml('example2.xml', 'tr', 'td', 'v') + >>> table2 + +-----+-----+ + | foo | bar | + +=====+=====+ + | 'a' | '1' | + +-----+-----+ + | 'b' | '2' | + +-----+-----+ + | 'c' | '2' | + +-----+-----+ + + Data values can also be extracted by providing a mapping of field + names to element paths:: + + >>> d = ''' + ... + ... a + ... + ... + ... b + ... + ... + ... c + ... + ...
''' + >>> with open('example3.xml', 'w') as f: + ... f.write(d) + ... + 223 + >>> table3 = etl.fromxml('example3.xml', 'row', + ... {'foo': 'foo', 'bar': ('baz/bar', 'v')}) + >>> table3 + +------------+-----+ + | bar | foo | + +============+=====+ + | ('1', '3') | 'a' | + +------------+-----+ + | '2' | 'b' | + +------------+-----+ + | '2' | 'c' | + +------------+-----+ + + If `lxml `_ is installed, full XPath expressions can be + used. + + Note that the implementation is currently **not** streaming, i.e., + the whole document is loaded into memory. + + If multiple elements match a given field, all values are reported as a + tuple. + + If there is more than one element name used for row values, a tuple + or list of paths can be provided, e.g., + ``fromxml('example.html', './/tr', ('th', 'td'))``. + + """ + + source = read_source_from_arg(source) + return XmlView(source, *args, **kwargs) +``` + +## `petl/io/xml.py` — `class:XmlView` (lines 142-219) + +```python +class XmlView(Table): + + def __init__(self, source, *args, **kwargs): + self.source = source + self.args = args + if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)): + self.rmatch = args[0] + self.vmatch = args[1] + self.vdict = None + self.attr = None + elif len(args) == 2 and isinstance(args[1], dict): + self.rmatch = args[0] + self.vmatch = None + self.vdict = args[1] + self.attr = None + elif len(args) == 3: + self.rmatch = args[0] + self.vmatch = args[1] + self.vdict = None + self.attr = args[2] + else: + assert False, 'bad parameters' + self.missing = kwargs.get('missing', None) + + def __iter__(self): + vmatch = self.vmatch + vdict = self.vdict + + with self.source.open('rb') as xmlf: + + tree = etree.parse(xmlf) + if not hasattr(tree, 'iterfind'): + # Python 2.6 compatibility + tree.iterfind = tree.findall + + if vmatch is not None: + # simple case, all value paths are the same + for rowelm in tree.iterfind(self.rmatch): + if self.attr is None: + getv = attrgetter('text') + else: + getv = lambda e: e.get(self.attr) + if isinstance(vmatch, string_types): + # match only one path + velms = rowelm.findall(vmatch) + else: + # match multiple paths + velms = itertools.chain(*[rowelm.findall(enm) + for enm in vmatch]) + yield tuple(getv(velm) + for velm in velms) + + else: + # difficult case, deal with different paths for each field + + # determine output header + flds = tuple(sorted(map(text_type, vdict.keys()))) + yield flds + + # setup value getters + vmatches = dict() + vgetters = dict() + for f in flds: + vmatch = self.vdict[f] + if isinstance(vmatch, string_types): + # match element path + vmatches[f] = vmatch + vgetters[f] = element_text_getter(self.missing) + else: + # match element path and attribute name + vmatches[f] = vmatch[0] + attr = vmatch[1] + vgetters[f] = attribute_text_getter(attr, self.missing) + + # determine data rows + for rowelm in tree.iterfind(self.rmatch): + yield tuple(vgetters[f](rowelm.findall(vmatches[f])) + for f in flds) +``` + +## `petl/io/xml.py` — `function:XmlView.__iter__` (lines 166-219) + +```python + def __iter__(self): + vmatch = self.vmatch + vdict = self.vdict + + with self.source.open('rb') as xmlf: + + tree = etree.parse(xmlf) + if not hasattr(tree, 'iterfind'): + # Python 2.6 compatibility + tree.iterfind = tree.findall + + if vmatch is not None: + # simple case, all value paths are the same + for rowelm in tree.iterfind(self.rmatch): + if self.attr is None: + getv = attrgetter('text') + else: + getv = lambda e: e.get(self.attr) + if isinstance(vmatch, string_types): + # match only one path + velms = rowelm.findall(vmatch) + else: + # match multiple paths + velms = itertools.chain(*[rowelm.findall(enm) + for enm in vmatch]) + yield tuple(getv(velm) + for velm in velms) + + else: + # difficult case, deal with different paths for each field + + # determine output header + flds = tuple(sorted(map(text_type, vdict.keys()))) + yield flds + + # setup value getters + vmatches = dict() + vgetters = dict() + for f in flds: + vmatch = self.vdict[f] + if isinstance(vmatch, string_types): + # match element path + vmatches[f] = vmatch + vgetters[f] = element_text_getter(self.missing) + else: + # match element path and attribute name + vmatches[f] = vmatch[0] + attr = vmatch[1] + vgetters[f] = attribute_text_getter(attr, self.missing) + + # determine data rows + for rowelm in tree.iterfind(self.rmatch): + yield tuple(vgetters[f](rowelm.findall(vmatches[f])) + for f in flds) +``` + +## `petl/io/xml.py` — `function:element_text_getter` (lines 222-230) + +```python +def element_text_getter(missing): + def _get(v): + if len(v) > 1: + return tuple(e.text for e in v) + elif len(v) == 1: + return v[0].text + else: + return missing + return _get +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.json new file mode 100644 index 0000000000000000000000000000000000000000..27953a573a7d887cfe47a94071193ccbf1bae635 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-394adf7b067d96b356ca", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-394adf7b067d96b356ca", + "project_id": "pyvul__petl-developers__petl", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "petl/io/xml.py" + ], + "patch_units": { + "before": [ + "function:fromxml", + "class:XmlView", + "function:XmlView.__iter__", + "function:element_text_getter" + ], + "after": [ + "function:fromxml", + "class:XmlView", + "function:XmlView.__init__", + "function:XmlView.__iter__", + "function:_create_xml_parser" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/fcb47a17185a332c24eecb3d2d4506cc6dd1ab2f313ab3bcf087aed38ddb4ecb/database", + "cache_key": "fcb47a17185a332c24eecb3d2d4506cc6dd1ab2f313ab3bcf087aed38ddb4ecb", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/c269b96e8d78a0ff93ceeec45f19adcb8bd0807c764fc5ff1ddf3e141ec1e71a/database", + "cache_key": "c269b96e8d78a0ff93ceeec45f19adcb8bd0807c764fc5ff1ddf3e141ec1e71a", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/83698b843f83dfc980db192656c5e8ad2835066c6e096f242e89cf727ededf65/database", + "cache_key": "83698b843f83dfc980db192656c5e8ad2835066c6e096f242e89cf727ededf65", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-394adf7b067d96b356ca/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-394adf7b067d96b356ca/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a839901a8b1b14d6293ecc1880b73ee934b07308 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diff @@ -0,0 +1,912 @@ +diff --git a/poetry.lock b/poetry.lock +index a7197f5f28b..78b0adedf13 100644 +--- a/poetry.lock ++++ b/poetry.lock +@@ -242,14 +242,14 @@ numpy = ">=1.15.0" + + [[package]] + name = "boto3" +-version = "1.18.52" ++version = "1.18.58" + description = "The AWS SDK for Python" + category = "main" + optional = false + python-versions = ">= 3.6" + + [package.dependencies] +-botocore = ">=1.21.52,<1.22.0" ++botocore = ">=1.21.58,<1.22.0" + jmespath = ">=0.7.1,<1.0.0" + s3transfer = ">=0.5.0,<0.6.0" + +@@ -258,7 +258,7 @@ crt = ["botocore[crt] (>=1.21.0,<2.0a0)"] + + [[package]] + name = "botocore" +-version = "1.21.52" ++version = "1.21.58" + description = "Low-level, data-driven core of boto 3." + category = "main" + optional = false +@@ -302,7 +302,7 @@ zipp = {version = ">=0.5", markers = "python_version < \"3.8\""} + + [[package]] + name = "certifi" +-version = "2021.5.30" ++version = "2021.10.8" + description = "Python package for providing Mozilla's CA Bundle." + category = "main" + optional = false +@@ -440,7 +440,7 @@ yaml = ["PyYAML (>=3.10)"] + + [[package]] + name = "cryptography" +-version = "3.4.8" ++version = "35.0.0" + description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." + category = "main" + optional = false +@@ -453,9 +453,9 @@ cffi = ">=1.12" + docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx-rtd-theme"] + docstest = ["doc8", "pyenchant (>=1.6.11)", "twine (>=1.12.0)", "sphinxcontrib-spelling (>=4.0.1)"] + pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"] +-sdist = ["setuptools-rust (>=0.11.4)"] ++sdist = ["setuptools_rust (>=0.11.4)"] + ssh = ["bcrypt (>=3.1.5)"] +-test = ["pytest (>=6.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"] ++test = ["pytest (>=6.2.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"] + + [[package]] + name = "cycler" +@@ -603,15 +603,15 @@ requests = ">=2.0" + + [[package]] + name = "filelock" +-version = "3.2.0" ++version = "3.3.0" + description = "A platform independent file lock." + category = "main" + optional = true +-python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" ++python-versions = ">=3.6" + + [package.extras] + docs = ["furo (>=2021.8.17b43)", "sphinx (>=4.1)", "sphinx-autodoc-typehints (>=1.12)"] +-testing = ["coverage (>=4)", "pytest (>=4)", "pytest-cov", "pytest-timeout (>=1.4.2)"] ++testing = ["covdefaults (>=1.2.0)", "coverage (>=4)", "pytest (>=4)", "pytest-cov", "pytest-timeout (>=1.4.2)"] + + [[package]] + name = "flake8" +@@ -717,7 +717,7 @@ typing-extensions = {version = ">=3.7.4.3", markers = "python_version < \"3.10\" + + [[package]] + name = "google-api-core" +-version = "2.0.1" ++version = "2.1.0" + description = "Google API client core library" + category = "dev" + optional = false +@@ -770,7 +770,7 @@ tool = ["click (>=6.0.0)"] + + [[package]] + name = "google-cloud-core" +-version = "2.0.0" ++version = "2.1.0" + description = "Google Cloud API client core library" + category = "dev" + optional = false +@@ -802,7 +802,7 @@ six = "*" + + [[package]] + name = "google-crc32c" +-version = "1.2.0" ++version = "1.3.0" + description = "A python wrapper of the C library 'Google CRC32C'" + category = "dev" + optional = false +@@ -930,11 +930,11 @@ python-versions = ">=3.6" + + [[package]] + name = "httplib2" +-version = "0.19.1" ++version = "0.20.1" + description = "A comprehensive HTTP client library." + category = "main" + optional = false +-python-versions = "*" ++python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + + [package.dependencies] + pyparsing = ">=2.4.2,<3" +@@ -1087,7 +1087,7 @@ python-versions = "*" + + [[package]] + name = "jinja2" +-version = "3.0.1" ++version = "3.0.2" + description = "A very fast and expressive template engine." + category = "main" + optional = false +@@ -1706,11 +1706,11 @@ wcwidth = "*" + + [[package]] + name = "protobuf" +-version = "3.18.0" ++version = "3.18.1" + description = "Protocol Buffers" + category = "main" + optional = false +-python-versions = "*" ++python-versions = ">=3.5" + + [[package]] + name = "psutil" +@@ -1849,18 +1849,18 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + + [[package]] + name = "pyjwt" +-version = "2.1.0" ++version = "2.2.0" + description = "JSON Web Token implementation in Python" + category = "main" + optional = false + python-versions = ">=3.6" + + [package.dependencies] +-cryptography = {version = ">=3.3.1,<4.0.0", optional = true, markers = "extra == \"crypto\""} ++cryptography = {version = ">=3.3.1", optional = true, markers = "extra == \"crypto\""} + + [package.extras] +-crypto = ["cryptography (>=3.3.1,<4.0.0)"] +-dev = ["sphinx", "sphinx-rtd-theme", "zope.interface", "cryptography (>=3.3.1,<4.0.0)", "pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)", "mypy", "pre-commit"] ++crypto = ["cryptography (>=3.3.1)"] ++dev = ["sphinx", "sphinx-rtd-theme", "zope.interface", "cryptography (>=3.3.1)", "pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)", "mypy", "pre-commit"] + docs = ["sphinx", "sphinx-rtd-theme", "zope.interface"] + tests = ["pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)"] + +@@ -2100,7 +2100,7 @@ client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] + + [[package]] + name = "pytz" +-version = "2021.1" ++version = "2021.3" + description = "World timezone definitions, modern and historical" + category = "main" + optional = false +@@ -2656,6 +2656,14 @@ python-versions = "*" + [package.extras] + widechars = ["wcwidth"] + ++[[package]] ++name = "tarsafe" ++version = "0.0.3" ++description = "A safe subclass of the TarFile class for interacting with tar files. Can be used as a direct drop-in replacement for safe usage of extractall()" ++category = "main" ++optional = false ++python-versions = ">=3.6" ++ + [[package]] + name = "tensorboard" + version = "2.6.0" +@@ -2854,7 +2862,7 @@ torch = ["torch (>=1.5.0)"] + + [[package]] + name = "threadpoolctl" +-version = "2.2.0" ++version = "3.0.0" + description = "threadpoolctl" + category = "main" + optional = false +@@ -2970,7 +2978,7 @@ python-versions = "*" + + [[package]] + name = "typeguard" +-version = "2.12.1" ++version = "2.13.0" + description = "Run-time type checker for Python" + category = "main" + optional = false +@@ -3066,11 +3074,11 @@ python-versions = ">=3.6" + + [[package]] + name = "uritemplate" +-version = "3.0.1" +-description = "URI templates" ++version = "4.0.0" ++description = "Implementation of RFC 6570 URI Templates" + category = "main" + optional = true +-python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" ++python-versions = ">=3.6" + + [[package]] + name = "urllib3" +@@ -3144,7 +3152,7 @@ python-versions = ">=3.6" + + [[package]] + name = "werkzeug" +-version = "2.0.1" ++version = "2.0.2" + description = "The comprehensive WSGI web application library." + category = "main" + optional = false +@@ -3174,7 +3182,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + + [[package]] + name = "yarl" +-version = "1.6.3" ++version = "1.7.0" + description = "Yet another URL library" + category = "main" + optional = false +@@ -3207,7 +3215,7 @@ transformers = ["transformers"] + [metadata] + lock-version = "1.1" + python-versions = ">=3.6,<3.9" +-content-hash = "209f285fcf47fff7c9fbcec651ed96156f03eb286f49b23c8047579fdd5adf8a" ++content-hash = "2fc451ce1e7553b33a12596867363114792c8ab2cde3148b60f57126e6cc635c" + + [metadata.files] + absl-py = [ +@@ -3333,12 +3341,12 @@ blis = [ + {file = "blis-0.7.4.tar.gz", hash = "sha256:7daa615a97d4f28db0f332b710bfe1900b15d0c25841c6d727965e4fd91e09cf"}, + ] + boto3 = [ +- {file = "boto3-1.18.52-py3-none-any.whl", hash = "sha256:27824d3767c5213f0006f71e552b912bc4659241b77ca8b0be0b813cf0518a9e"}, +- {file = "boto3-1.18.52.tar.gz", hash = "sha256:5b585a279478bd6df4b07db7d6150f413ba6add1f38e68aaa533d3337efd0b22"}, ++ {file = "boto3-1.18.58-py3-none-any.whl", hash = "sha256:7309552da6ef9e610f8a9712c8abe29a8d3d45b514188cc3efad47bd1774bf77"}, ++ {file = "boto3-1.18.58.tar.gz", hash = "sha256:f680dee9c670d42ab4a6da5539ca3691d1ccbbcbf041e7021025029776864156"}, + ] + botocore = [ +- {file = "botocore-1.21.52-py3-none-any.whl", hash = "sha256:e8797c0933c660e130cf2f51667f5003950d7e592f4c3944e8f04f201493d17a"}, +- {file = "botocore-1.21.52.tar.gz", hash = "sha256:04c071aec4f1981b38e3be760838b976337fd6ebd95a31ceeca9f9e4b4733c1f"}, ++ {file = "botocore-1.21.58-py3-none-any.whl", hash = "sha256:9d84a97015c0565a81c0b6d55e60af5ab1a2da28039ad93976388014a14186da"}, ++ {file = "botocore-1.21.58.tar.gz", hash = "sha256:87e881569c32b218a1b82ecb607a4dddb4dca3b80a5d1016571b99b51cef3158"}, + ] + cached-property = [ + {file = "cached-property-1.5.2.tar.gz", hash = "sha256:9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130"}, +@@ -3353,8 +3361,8 @@ catalogue = [ + {file = "catalogue-2.0.6.tar.gz", hash = "sha256:336a35603f447167042ef504114d6befa46688f03f4c14dabdc633a44587b245"}, + ] + certifi = [ +- {file = "certifi-2021.5.30-py2.py3-none-any.whl", hash = "sha256:50b1e4f8446b06f41be7dd6338db18e0990601dce795c2b1686458aa7e8fa7d8"}, +- {file = "certifi-2021.5.30.tar.gz", hash = "sha256:2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee"}, ++ {file = "certifi-2021.10.8-py2.py3-none-any.whl", hash = "sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569"}, ++ {file = "certifi-2021.10.8.tar.gz", hash = "sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872"}, + ] + cffi = [ + {file = "cffi-1.14.6-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:22b9c3c320171c108e903d61a3723b51e37aaa8c81255b5e7ce102775bd01e2c"}, +@@ -3499,23 +3507,26 @@ coveralls = [ + {file = "coveralls-3.2.0.tar.gz", hash = "sha256:15a987d9df877fff44cd81948c5806ffb6eafb757b3443f737888358e96156ee"}, + ] + cryptography = [ +- {file = "cryptography-3.4.8-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:a00cf305f07b26c351d8d4e1af84ad7501eca8a342dedf24a7acb0e7b7406e14"}, +- {file = "cryptography-3.4.8-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:f44d141b8c4ea5eb4dbc9b3ad992d45580c1d22bf5e24363f2fbf50c2d7ae8a7"}, +- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0a7dcbcd3f1913f664aca35d47c1331fce738d44ec34b7be8b9d332151b0b01e"}, +- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:34dae04a0dce5730d8eb7894eab617d8a70d0c97da76b905de9efb7128ad7085"}, +- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1eb7bb0df6f6f583dd8e054689def236255161ebbcf62b226454ab9ec663746b"}, +- {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:9965c46c674ba8cc572bc09a03f4c649292ee73e1b683adb1ce81e82e9a6a0fb"}, +- {file = "cryptography-3.4.8-cp36-abi3-win32.whl", hash = "sha256:21ca464b3a4b8d8e86ba0ee5045e103a1fcfac3b39319727bc0fc58c09c6aff7"}, +- {file = "cryptography-3.4.8-cp36-abi3-win_amd64.whl", hash = "sha256:3520667fda779eb788ea00080124875be18f2d8f0848ec00733c0ec3bb8219fc"}, +- {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d2a6e5ef66503da51d2110edf6c403dc6b494cc0082f85db12f54e9c5d4c3ec5"}, +- {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a305600e7a6b7b855cd798e00278161b681ad6e9b7eca94c721d5f588ab212af"}, +- {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:3fa3a7ccf96e826affdf1a0a9432be74dc73423125c8f96a909e3835a5ef194a"}, +- {file = "cryptography-3.4.8-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:d9ec0e67a14f9d1d48dd87a2531009a9b251c02ea42851c060b25c782516ff06"}, +- {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5b0fbfae7ff7febdb74b574055c7466da334a5371f253732d7e2e7525d570498"}, +- {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:94fff993ee9bc1b2440d3b7243d488c6a3d9724cc2b09cdb297f6a886d040ef7"}, +- {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:8695456444f277af73a4877db9fc979849cd3ee74c198d04fc0776ebc3db52b9"}, +- {file = "cryptography-3.4.8-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:cd65b60cfe004790c795cc35f272e41a3df4631e2fb6b35aa7ac6ef2859d554e"}, +- {file = "cryptography-3.4.8.tar.gz", hash = "sha256:94cc5ed4ceaefcbe5bf38c8fba6a21fc1d365bb8fb826ea1688e3370b2e24a1c"}, ++ {file = "cryptography-35.0.0-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:d57e0cdc1b44b6cdf8af1d01807db06886f10177469312fbde8f44ccbb284bc9"}, ++ {file = "cryptography-35.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:ced40344e811d6abba00295ced98c01aecf0c2de39481792d87af4fa58b7b4d6"}, ++ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:54b2605e5475944e2213258e0ab8696f4f357a31371e538ef21e8d61c843c28d"}, ++ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:7b7ceeff114c31f285528ba8b390d3e9cfa2da17b56f11d366769a807f17cbaa"}, ++ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d69645f535f4b2c722cfb07a8eab916265545b3475fdb34e0be2f4ee8b0b15e"}, ++ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4a2d0e0acc20ede0f06ef7aa58546eee96d2592c00f450c9acb89c5879b61992"}, ++ {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:07bb7fbfb5de0980590ddfc7f13081520def06dc9ed214000ad4372fb4e3c7f6"}, ++ {file = "cryptography-35.0.0-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:7eba2cebca600a7806b893cb1d541a6e910afa87e97acf2021a22b32da1df52d"}, ++ {file = "cryptography-35.0.0-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:18d90f4711bf63e2fb21e8c8e51ed8189438e6b35a6d996201ebd98a26abbbe6"}, ++ {file = "cryptography-35.0.0-cp36-abi3-win32.whl", hash = "sha256:c10c797ac89c746e488d2ee92bd4abd593615694ee17b2500578b63cad6b93a8"}, ++ {file = "cryptography-35.0.0-cp36-abi3-win_amd64.whl", hash = "sha256:7075b304cd567694dc692ffc9747f3e9cb393cc4aa4fb7b9f3abd6f5c4e43588"}, ++ {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a688ebcd08250eab5bb5bca318cc05a8c66de5e4171a65ca51db6bd753ff8953"}, ++ {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d99915d6ab265c22873f1b4d6ea5ef462ef797b4140be4c9d8b179915e0985c6"}, ++ {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:928185a6d1ccdb816e883f56ebe92e975a262d31cc536429041921f8cb5a62fd"}, ++ {file = "cryptography-35.0.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ebeddd119f526bcf323a89f853afb12e225902a24d29b55fe18dd6fcb2838a76"}, ++ {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:22a38e96118a4ce3b97509443feace1d1011d0571fae81fc3ad35f25ba3ea999"}, ++ {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb80e8a1f91e4b7ef8b33041591e6d89b2b8e122d787e87eeb2b08da71bb16ad"}, ++ {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:abb5a361d2585bb95012a19ed9b2c8f412c5d723a9836418fab7aaa0243e67d2"}, ++ {file = "cryptography-35.0.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:1ed82abf16df40a60942a8c211251ae72858b25b7421ce2497c2eb7a1cee817c"}, ++ {file = "cryptography-35.0.0.tar.gz", hash = "sha256:9933f28f70d0517686bd7de36166dda42094eac49415459d9bdf5e7df3e0086d"}, + ] + cycler = [ + {file = "cycler-0.10.0-py2.py3-none-any.whl", hash = "sha256:1d8a5ae1ff6c5cf9b93e8811e581232ad8920aeec647c37316ceac982b08cb2d"}, +@@ -3595,8 +3606,8 @@ fbmessenger = [ + {file = "fbmessenger-6.0.0.tar.gz", hash = "sha256:6e42c4588a4c942547be228886278bbc7a084e0b34799c7e6ebd786129f021e6"}, + ] + filelock = [ +- {file = "filelock-3.2.0-py2.py3-none-any.whl", hash = "sha256:61a99e9b12b47b685d1389f4cf969c1eba0efd2348a8471f86e01e8c622267af"}, +- {file = "filelock-3.2.0.tar.gz", hash = "sha256:85ecb30757aa19d06bfcdad29cc332b9a3e4851bf59976aea1e8dadcbd9ef883"}, ++ {file = "filelock-3.3.0-py3-none-any.whl", hash = "sha256:bbc6a0382fe8ec4744ecdf6683a2e07f65eb10ff1aff53fc02a202565446cde0"}, ++ {file = "filelock-3.3.0.tar.gz", hash = "sha256:8c7eab13dc442dc249e95158bcc12dec724465919bdc9831fdbf0660f03d1785"}, + ] + flake8 = [ + {file = "flake8-3.9.2-py2.py3-none-any.whl", hash = "sha256:bf8fd333346d844f616e8d47905ef3a3384edae6b4e9beb0c5101e25e3110907"}, +@@ -3634,8 +3645,8 @@ gitpython = [ + {file = "GitPython-3.1.20.tar.gz", hash = "sha256:df0e072a200703a65387b0cfdf0466e3bab729c0458cf6b7349d0e9877636519"}, + ] + google-api-core = [ +- {file = "google-api-core-2.0.1.tar.gz", hash = "sha256:d6760f21b3a064a8397916b33be7383fc169d1a3c3d7fae7b47eb92bba7892b8"}, +- {file = "google_api_core-2.0.1-py2.py3-none-any.whl", hash = "sha256:b8ad41f72a70dd709dd13a08478936172aecf5f2d34a18ab378efa6d2d6ab575"}, ++ {file = "google-api-core-2.1.0.tar.gz", hash = "sha256:5ec27b942b34d04559cbf3674430bb83fc3d74e7d32b8bbd31c4466e71740b83"}, ++ {file = "google_api_core-2.1.0-py2.py3-none-any.whl", hash = "sha256:c344e1aacd8330527c5130bdfe03118d8859ce798bcf0e5d23770ab6873e0615"}, + ] + google-auth = [ + {file = "google-auth-1.35.0.tar.gz", hash = "sha256:b7033be9028c188ee30200b204ea00ed82ea1162e8ac1df4aa6ded19a191d88e"}, +@@ -3646,57 +3657,57 @@ google-auth-oauthlib = [ + {file = "google_auth_oauthlib-0.4.6-py2.py3-none-any.whl", hash = "sha256:3f2a6e802eebbb6fb736a370fbf3b055edcb6b52878bf2f26330b5e041316c73"}, + ] + google-cloud-core = [ +- {file = "google-cloud-core-2.0.0.tar.gz", hash = "sha256:90ee99648ccf9e11a16781a7fc58d13e58f662b439c737d48c24ef18662c2702"}, +- {file = "google_cloud_core-2.0.0-py2.py3-none-any.whl", hash = "sha256:31785d1e1d02f90ad3f1b020d4aed63db4865c3394ff7c128a296b6995eef31f"}, ++ {file = "google-cloud-core-2.1.0.tar.gz", hash = "sha256:35a1f5f02a86e0fa2e28c669f0db4a76d928671a28fbbbb493ab59ba9d1cb9a9"}, ++ {file = "google_cloud_core-2.1.0-py2.py3-none-any.whl", hash = "sha256:8d5fed11731dae8bc8656a2c9fa8ff17bdfdfd083cba97569324e35b94e7e002"}, + ] + google-cloud-storage = [ + {file = "google-cloud-storage-1.42.3.tar.gz", hash = "sha256:7754d4dcaa45975514b404ece0da2bb4292acbc67ca559a69e12a19d54fcdb06"}, + {file = "google_cloud_storage-1.42.3-py2.py3-none-any.whl", hash = "sha256:71ee3a0dcf2c139f034a054181cd7658f1ec8f12837d2769c450a8a00fcd4c6d"}, + ] + google-crc32c = [ +- {file = "google-crc32c-1.2.0.tar.gz", hash = "sha256:258caf72c4ab03d91e593ed9f988c13c118754f5ce46d8bcbc40b109d14cb8b7"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b64bd23a66410883c22c156834b73515e3f3d8c890c0407620f960b4c25cc8a3"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:61080f164ea51e156153c601b1de35ccb574d77efb669c11ade75f8635ce2d29"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:f563a48074de0a4ebf1ef1d55aeb16bdaa6715c33091dad3b6a32716d2a5d4a4"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:242274e127e349e6ede67d7232872bdac9f6c36da6233216e8e4f5923eef1a7c"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:93f1377269cf30b15b296e760ac3f6e13ea52556a764739410fa2e7b32a39e93"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-win32.whl", hash = "sha256:60f9e93e29cbaa47f57230907733af884685dbac78d462019ffe02d514bbfddc"}, +- {file = "google_crc32c-1.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:b28e81707257802d1e07aee4a2513d1316f623a1b48b78885c1ca2a9ec47949d"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:837a17d940dac5b0d0a88868a2be924bbb31578de20c250620c09ac7c3f9d1fd"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:966186c535fec30606cb7787e3caa283631f80c50cbd7226e7db1589ede0f177"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:617ec1f65d769e670dd35d9e8db0244d03bb09b8728262e28ebeab82de8d1341"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca0f7bcb47dbd1367bb8f2d7dfc90568a7f69e4062dd70b21a365fc361c9929d"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e7b98a2dabe06a460219ecad21113d1c9d793910ceeeae8b4fb64871ef203c4c"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-win32.whl", hash = "sha256:a6307368bc04f07d3bdf554109d5ebd64b350c12e1a3604686e7a2d913585b1e"}, +- {file = "google_crc32c-1.2.0-cp36-cp36m-win_amd64.whl", hash = "sha256:4b2f3a9f61f264029ffbaf9f503340da1e72e602650eb46d34940a431e3a2676"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ce877f9ce49db4f465d942ea910475d79148b390e5890efb2e505df9596d5ced"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c9a057c13a268c3a03d1fc8aa08358952b7ff560bb2893fe46dd5823cc0f47b7"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:ad1cfabad6e9d4affd03684fde2763fa47b6d5a9696a03df3bb23f197cf55af1"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b19ee0a14107fc29a24129982f16648908363b0c43cf6a2b68ece7768c4d038b"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:fd55f480bb87e1f03b08a8bff13a0689efa7bf10426f1b58f2081168a05b3463"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-win32.whl", hash = "sha256:6690bbdbfafc39f7031e19e07965b28b91cf41f3a66267e9e9f75b7bcbcd8ac6"}, +- {file = "google_crc32c-1.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:8331f0cbf8d91e868858a95c3608c26c2b8872f0ed8464c58425995aa92cb70b"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:96e7057e29abfe763db02877b7cafff8a076145feb446106409f4fc12549d281"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:496d7d6ac406f3a8e9f1e2fea93bc5470d5ff02c6ea34745c9aa5f22c876f30e"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8a862ea73b86c3b6589847224195e1027a876c85dc1f87475509b58d2aaafcda"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:eb32e021526e905500c08aa030461621e5af934bf68a910322f5ddebb8c2bbf9"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e720b0c9df6a58d4786c299407c2561993e9abd41d37c38e09d33288a3aca0d"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:8aa4de2ffad9d5521d9ba105a1a59126423389598cb4f9af9d28d4da845c0414"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-win32.whl", hash = "sha256:adb721315435d8530a9eabce2cf3731db015ca0af5f8f983bf5c6e5272385c02"}, +- {file = "google_crc32c-1.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:a7920ea4770ec6b98a30e99f9ab90aacc0a447a316c165701f264234d8dbf731"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c242c82eef7fb75ee698ecc65596e324b3273ae3dd78a8e5f05bf3cb627caa3b"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a6694773dd45c88b2babef6b702b6233723ae4f42cca0fbc68114e81ed389188"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:70670518d50babd6012de3206472aa406a41b79acb11b6e46931f842e25a356a"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:dc12aef85a7b8e5c52d7639cf23e27548f09fba798b8050f59fdd5bee08051f2"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e13c8f1fbde9b543f693c42c0f82ba6c57683d66cc2c5960c6c66fccb42a736"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:483694ccb1d0ceab8219afc4f20939565b09f81531bf8dd2bf3efb3ea84766fe"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-win32.whl", hash = "sha256:618c304e803fb5e4b1dbe4d529e1047450d913b64dc4e49826bb3e5a0ef73a9e"}, +- {file = "google_crc32c-1.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:60c4f32d1fbd25234ff9468de24c1c8a9556e90ac94818a99c8cfc83328214d1"}, +- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:4b8c7579269e3c64dda1d63cc9b9ba7615b51092c905b68d43c907be80fc641f"}, +- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c24e7e78756f617ebf006adcb0edb74aaf93a31a45440266e66f5fb2b8c75512"}, +- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:81c2e088041fb38b099b5a7fb2407deff74ee9bec3b36c38180564b4686bc1fa"}, +- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c422331bdeb5214ecc8a98f85dcbbc5b3222d173b1348874f1087b1f938313d8"}, +- {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:9caf25a7f2551b117e063ce1e1f3959ef64d8c4e96587e4ce6ee1be7b441b3b7"}, ++ {file = "google-crc32c-1.3.0.tar.gz", hash = "sha256:276de6273eb074a35bc598f8efbc00c7869c5cf2e29c90748fccc8c898c244df"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:cb6994fff247987c66a8a4e550ef374671c2b82e3c0d2115e689d21e511a652d"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c9da0a39b53d2fab3e5467329ed50e951eb91386e9d0d5b12daf593973c3b168"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:eb0b14523758e37802f27b7f8cd973f5f3d33be7613952c0df904b68c4842f0e"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:95c68a4b9b7828ba0428f8f7e3109c5d476ca44996ed9a5f8aac6269296e2d59"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c3cf890c3c0ecfe1510a452a165431b5831e24160c5fcf2071f0f85ca5a47cd"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-win32.whl", hash = "sha256:3bbce1be3687bbfebe29abdb7631b83e6b25da3f4e1856a1611eb21854b689ea"}, ++ {file = "google_crc32c-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:c124b8c8779bf2d35d9b721e52d4adb41c9bfbde45e6a3f25f0820caa9aba73f"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:42ae4781333e331a1743445931b08ebdad73e188fd554259e772556fc4937c48"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ff71073ebf0e42258a42a0b34f2c09ec384977e7f6808999102eedd5b49920e3"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:fe31de3002e7b08eb20823b3735b97c86c5926dd0581c7710a680b418a8709d4"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dd7760a88a8d3d705ff562aa93f8445ead54f58fd482e4f9e2bafb7e177375d4"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a0b9e622c3b2b8d0ce32f77eba617ab0d6768b82836391e4f8f9e2074582bf02"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-win32.whl", hash = "sha256:779cbf1ce375b96111db98fca913c1f5ec11b1d870e529b1dc7354b2681a8c3a"}, ++ {file = "google_crc32c-1.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:04e7c220798a72fd0f08242bc8d7a05986b2a08a0573396187fd32c1dcdd58b3"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e7a539b9be7b9c00f11ef16b55486141bc2cdb0c54762f84e3c6fc091917436d"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ca60076c388728d3b6ac3846842474f4250c91efbfe5afa872d3ffd69dd4b318"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:05340b60bf05b574159e9bd940152a47d38af3fb43803ffe71f11d704b7696a6"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:318f73f5484b5671f0c7f5f63741ab020a599504ed81d209b5c7129ee4667407"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9f58099ad7affc0754ae42e6d87443299f15d739b0ce03c76f515153a5cda06c"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-win32.whl", hash = "sha256:f52a4ad2568314ee713715b1e2d79ab55fab11e8b304fd1462ff5cccf4264b3e"}, ++ {file = "google_crc32c-1.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:bab4aebd525218bab4ee615786c4581952eadc16b1ff031813a2fd51f0cc7b08"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:dda4d8a3bb0b50f540f6ff4b6033f3a74e8bf0bd5320b70fab2c03e512a62812"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:fec221a051150eeddfdfcff162e6db92c65ecf46cb0f7bb1bf812a1520ec026b"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:226f2f9b8e128a6ca6a9af9b9e8384f7b53a801907425c9a292553a3a7218ce0"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a7f9cbea4245ee36190f85fe1814e2d7b1e5f2186381b082f5d59f99b7f11328"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6a4db36f9721fdf391646685ecffa404eb986cbe007a3289499020daf72e88a2"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:12674a4c3b56b706153a358eaa1018c4137a5a04635b92b4652440d3d7386206"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-win32.whl", hash = "sha256:650e2917660e696041ab3dcd7abac160b4121cd9a484c08406f24c5964099829"}, ++ {file = "google_crc32c-1.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:58be56ae0529c664cc04a9c76e68bb92b091e0194d6e3c50bea7e0f266f73713"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:96a8918a78d5d64e07c8ea4ed2bc44354e3f93f46a4866a40e8db934e4c0d74b"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:13af315c3a0eec8bb8b8d80b8b128cb3fcd17d7e4edafc39647846345a3f003a"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:6311853aa2bba4064d0c28ca54e7b50c4d48e3de04f6770f6c60ebda1e975267"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:ed447680ff21c14aaceb6a9f99a5f639f583ccfe4ce1a5e1d48eb41c3d6b3217"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d1c1d6236feab51200272d79b3d3e0f12cf2cbb12b208c835b175a21efdb0a73"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e0f1ff55dde0ebcfbef027edc21f71c205845585fffe30d4ec4979416613e9b3"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-win32.whl", hash = "sha256:fbd60c6aaa07c31d7754edbc2334aef50601b7f1ada67a96eb1eb57c7c72378f"}, ++ {file = "google_crc32c-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:127f9cc3ac41b6a859bd9dc4321097b1a4f6aa7fdf71b4f9227b9e3ebffb4422"}, ++ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:fc28e0db232c62ca0c3600884933178f0825c99be4474cdd645e378a10588125"}, ++ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1926fd8de0acb9d15ee757175ce7242e235482a783cd4ec711cc999fc103c24e"}, ++ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5da2c81575cc3ccf05d9830f9e8d3c70954819ca9a63828210498c0774fda1a3"}, ++ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:891f712ce54e0d631370e1f4997b3f182f3368179198efc30d477c75d1f44942"}, ++ {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:7f6fe42536d9dcd3e2ffb9d3053f5d05221ae3bbcefbe472bdf2c71c793e3183"}, + ] + google-pasta = [ + {file = "google-pasta-0.2.0.tar.gz", hash = "sha256:c9f2c8dfc8f96d0d5808299920721be30c9eec37f2389f28904f454565c8a16e"}, +@@ -3841,8 +3852,8 @@ hstspreload = [ + {file = "hstspreload-2021.10.1.tar.gz", hash = "sha256:5bb90f438bec40faf320170ee48cf1978f40423ee1ba39a57bb686f3f9c061c7"}, + ] + httplib2 = [ +- {file = "httplib2-0.19.1-py3-none-any.whl", hash = "sha256:2ad195faf9faf079723f6714926e9a9061f694d07724b846658ce08d40f522b4"}, +- {file = "httplib2-0.19.1.tar.gz", hash = "sha256:0b12617eeca7433d4c396a100eaecfa4b08ee99aa881e6df6e257a7aad5d533d"}, ++ {file = "httplib2-0.20.1-py3-none-any.whl", hash = "sha256:8fa4dbf2fbf839b71f8c7837a831e00fcdc860feca99b8bda58ceae4bc53d185"}, ++ {file = "httplib2-0.20.1.tar.gz", hash = "sha256:0efbcb8bfbfbc11578130d87d8afcc65c2274c6eb446e59fc674e4d7c972d327"}, + ] + httptools = [ + {file = "httptools-0.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:4137137de8976511a392e27bfdcf231bd926ac13d375e0414e927b08217d779e"}, +@@ -3942,8 +3953,8 @@ jieba = [ + {file = "jieba-0.42.1.tar.gz", hash = "sha256:055ca12f62674fafed09427f176506079bc135638a14e23e25be909131928db2"}, + ] + jinja2 = [ +- {file = "Jinja2-3.0.1-py3-none-any.whl", hash = "sha256:1f06f2da51e7b56b8f238affdd6b4e2c61e39598a378cc49345bc1bd42a978a4"}, +- {file = "Jinja2-3.0.1.tar.gz", hash = "sha256:703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4"}, ++ {file = "Jinja2-3.0.2-py3-none-any.whl", hash = "sha256:8569982d3f0889eed11dd620c706d39b60c36d6d25843961f33f77fb6bc6b20c"}, ++ {file = "Jinja2-3.0.2.tar.gz", hash = "sha256:827a0e32839ab1600d4eb1c4c33ec5a8edfbc5cb42dafa13b81f182f97784b45"}, + ] + jmespath = [ + {file = "jmespath-0.10.0-py2.py3-none-any.whl", hash = "sha256:cdf6525904cc597730141d61b36f2e4b8ecc257c420fa2f4549bac2c2d0cb72f"}, +@@ -3991,14 +4002,18 @@ kiwisolver = [ + {file = "kiwisolver-1.3.1-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:1e1bc12fb773a7b2ffdeb8380609f4f8064777877b2225dec3da711b421fda31"}, + {file = "kiwisolver-1.3.1-cp37-cp37m-win32.whl", hash = "sha256:72c99e39d005b793fb7d3d4e660aed6b6281b502e8c1eaf8ee8346023c8e03bc"}, + {file = "kiwisolver-1.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:8be8d84b7d4f2ba4ffff3665bcd0211318aa632395a1a41553250484a871d454"}, ++ {file = "kiwisolver-1.3.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:24cc411232d14c8abafbd0dddb83e1a4f54d77770b53db72edcfe1d611b3bf11"}, + {file = "kiwisolver-1.3.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:31dfd2ac56edc0ff9ac295193eeaea1c0c923c0355bf948fbd99ed6018010b72"}, ++ {file = "kiwisolver-1.3.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ef6eefcf3944e75508cdfa513c06cf80bafd7d179e14c1334ebdca9ebb8c2c66"}, + {file = "kiwisolver-1.3.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:563c649cfdef27d081c84e72a03b48ea9408c16657500c312575ae9d9f7bc1c3"}, + {file = "kiwisolver-1.3.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:78751b33595f7f9511952e7e60ce858c6d64db2e062afb325985ddbd34b5c131"}, + {file = "kiwisolver-1.3.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:a357fd4f15ee49b4a98b44ec23a34a95f1e00292a139d6015c11f55774ef10de"}, + {file = "kiwisolver-1.3.1-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:5989db3b3b34b76c09253deeaf7fbc2707616f130e166996606c284395da3f18"}, + {file = "kiwisolver-1.3.1-cp38-cp38-win32.whl", hash = "sha256:c08e95114951dc2090c4a630c2385bef681cacf12636fb0241accdc6b303fd81"}, + {file = "kiwisolver-1.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:44a62e24d9b01ba94ae7a4a6c3fb215dc4af1dde817e7498d901e229aaf50e4e"}, ++ {file = "kiwisolver-1.3.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:6d9d8d9b31aa8c2d80a690693aebd8b5e2b7a45ab065bb78f1609995d2c79240"}, + {file = "kiwisolver-1.3.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:50af681a36b2a1dee1d3c169ade9fdc59207d3c31e522519181e12f1b3ba7000"}, ++ {file = "kiwisolver-1.3.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:792e69140828babe9649de583e1a03a0f2ff39918a71782c76b3c683a67c6dfd"}, + {file = "kiwisolver-1.3.1-cp39-cp39-manylinux1_i686.whl", hash = "sha256:a53d27d0c2a0ebd07e395e56a1fbdf75ffedc4a05943daf472af163413ce9598"}, + {file = "kiwisolver-1.3.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:834ee27348c4aefc20b479335fd422a2c69db55f7d9ab61721ac8cd83eb78882"}, + {file = "kiwisolver-1.3.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:5c3e6455341008a054cccee8c5d24481bcfe1acdbc9add30aa95798e95c65621"}, +@@ -4008,6 +4023,7 @@ kiwisolver = [ + {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-macosx_10_9_x86_64.whl", hash = "sha256:0cd53f403202159b44528498de18f9285b04482bab2a6fc3f5dd8dbb9352e30d"}, + {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-manylinux2010_x86_64.whl", hash = "sha256:33449715e0101e4d34f64990352bce4095c8bf13bed1b390773fc0a7295967b3"}, + {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-win32.whl", hash = "sha256:401a2e9afa8588589775fe34fc22d918ae839aaaf0c0e96441c0fdbce6d8ebe6"}, ++ {file = "kiwisolver-1.3.1-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d6563ccd46b645e966b400bb8a95d3457ca6cf3bba1e908f9e0927901dfebeb1"}, + {file = "kiwisolver-1.3.1.tar.gz", hash = "sha256:950a199911a8d94683a6b10321f9345d5a3a8433ec58b217ace979e18f16e248"}, + ] + markdown = [ +@@ -4015,12 +4031,22 @@ markdown = [ + {file = "Markdown-3.3.4.tar.gz", hash = "sha256:31b5b491868dcc87d6c24b7e3d19a0d730d59d3e46f4eea6430a321bed387a49"}, + ] + markupsafe = [ ++ {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d8446c54dc28c01e5a2dbac5a25f071f6653e6e40f3a8818e8b45d790fe6ef53"}, ++ {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:36bc903cbb393720fad60fc28c10de6acf10dc6cc883f3e24ee4012371399a38"}, ++ {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d7d807855b419fc2ed3e631034685db6079889a1f01d5d9dac950f764da3dad"}, ++ {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:add36cb2dbb8b736611303cd3bfcee00afd96471b09cda130da3581cbdc56a6d"}, ++ {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:168cd0a3642de83558a5153c8bd34f175a9a6e7f6dc6384b9655d2697312a646"}, ++ {file = "MarkupSafe-2.0.1-cp310-cp310-win32.whl", hash = "sha256:99df47edb6bda1249d3e80fdabb1dab8c08ef3975f69aed437cb69d0a5de1e28"}, ++ {file = "MarkupSafe-2.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:e0f138900af21926a02425cf736db95be9f4af72ba1bb21453432a07f6082134"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f9081981fe268bd86831e5c75f7de206ef275defcb82bc70740ae6dc507aee51"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:0955295dd5eec6cb6cc2fe1698f4c6d84af2e92de33fbcac4111913cd100a6ff"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:0446679737af14f45767963a1a9ef7620189912317d095f2d9ffa183a4d25d2b"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:f826e31d18b516f653fe296d967d700fddad5901ae07c622bb3705955e1faa94"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:fa130dd50c57d53368c9d59395cb5526eda596d3ffe36666cd81a44d56e48872"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:905fec760bd2fa1388bb5b489ee8ee5f7291d692638ea5f67982d968366bef9f"}, ++ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf5d821ffabf0ef3533c39c518f3357b171a1651c1ff6827325e4489b0e46c3c"}, ++ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:0d4b31cc67ab36e3392bbf3862cfbadac3db12bdd8b02a2731f509ed5b829724"}, ++ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:baa1a4e8f868845af802979fcdbf0bb11f94f1cb7ced4c4b8a351bb60d108145"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-win32.whl", hash = "sha256:6c4ca60fa24e85fe25b912b01e62cb969d69a23a5d5867682dd3e80b5b02581d"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b2f4bf27480f5e5e8ce285a8c8fd176c0b03e93dcc6646477d4630e83440c6a9"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0717a7390a68be14b8c793ba258e075c6f4ca819f15edfc2a3a027c823718567"}, +@@ -4029,14 +4055,21 @@ markupsafe = [ + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:d7f9850398e85aba693bb640262d3611788b1f29a79f0c93c565694658f4071f"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:6a7fae0dd14cf60ad5ff42baa2e95727c3d81ded453457771d02b7d2b3f9c0c2"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:b7f2d075102dc8c794cbde1947378051c4e5180d52d276987b8d28a3bd58c17d"}, ++ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e9936f0b261d4df76ad22f8fee3ae83b60d7c3e871292cd42f40b81b70afae85"}, ++ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:2a7d351cbd8cfeb19ca00de495e224dea7e7d919659c2841bbb7f420ad03e2d6"}, ++ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:60bf42e36abfaf9aff1f50f52644b336d4f0a3fd6d8a60ca0d054ac9f713a864"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-win32.whl", hash = "sha256:a30e67a65b53ea0a5e62fe23682cfe22712e01f453b95233b25502f7c61cb415"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:611d1ad9a4288cf3e3c16014564df047fe08410e628f89805e475368bd304914"}, ++ {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5bb28c636d87e840583ee3adeb78172efc47c8b26127267f54a9c0ec251d41a9"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:be98f628055368795d818ebf93da628541e10b75b41c559fdf36d104c5787066"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:1d609f577dc6e1aa17d746f8bd3c31aa4d258f4070d61b2aa5c4166c1539de35"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:7d91275b0245b1da4d4cfa07e0faedd5b0812efc15b702576d103293e252af1b"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:01a9b8ea66f1658938f65b93a85ebe8bc016e6769611be228d797c9d998dd298"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:47ab1e7b91c098ab893b828deafa1203de86d0bc6ab587b160f78fe6c4011f75"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:97383d78eb34da7e1fa37dd273c20ad4320929af65d156e35a5e2d89566d9dfb"}, ++ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6fcf051089389abe060c9cd7caa212c707e58153afa2c649f00346ce6d260f1b"}, ++ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:5855f8438a7d1d458206a2466bf82b0f104a3724bf96a1c781ab731e4201731a"}, ++ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3dd007d54ee88b46be476e293f48c85048603f5f516008bee124ddd891398ed6"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-win32.whl", hash = "sha256:023cb26ec21ece8dc3907c0e8320058b2e0cb3c55cf9564da612bc325bed5e64"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:984d76483eb32f1bcb536dc27e4ad56bba4baa70be32fa87152832cdd9db0833"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2ef54abee730b502252bcdf31b10dacb0a416229b72c18b19e24a4509f273d26"}, +@@ -4046,6 +4079,9 @@ markupsafe = [ + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:4efca8f86c54b22348a5467704e3fec767b2db12fc39c6d963168ab1d3fc9135"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:ab3ef638ace319fa26553db0624c4699e31a28bb2a835c5faca8f8acf6a5a902"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f8ba0e8349a38d3001fae7eadded3f6606f0da5d748ee53cc1dab1d6527b9509"}, ++ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c47adbc92fc1bb2b3274c4b3a43ae0e4573d9fbff4f54cd484555edbf030baf1"}, ++ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:37205cac2a79194e3750b0af2a5720d95f786a55ce7df90c3af697bfa100eaac"}, ++ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1f2ade76b9903f39aa442b4aadd2177decb66525062db244b35d71d0ee8599b6"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-win32.whl", hash = "sha256:10f82115e21dc0dfec9ab5c0223652f7197feb168c940f3ef61563fc2d6beb74"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8"}, + {file = "MarkupSafe-2.0.1.tar.gz", hash = "sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a"}, +@@ -4369,27 +4405,27 @@ prompt-toolkit = [ + {file = "prompt_toolkit-2.0.10.tar.gz", hash = "sha256:f15af68f66e664eaa559d4ac8a928111eebd5feda0c11738b5998045224829db"}, + ] + protobuf = [ +- {file = "protobuf-3.18.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9072cb18fca8998b77f969fb74d25a11d7f4a39a8b1ddc3cf76cd5abda8499cb"}, +- {file = "protobuf-3.18.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f589346b5b3f702c1d30e2343c9897e6c35e7bd495c10a0e17d11ecb5ee5bd06"}, +- {file = "protobuf-3.18.0-cp36-cp36m-win32.whl", hash = "sha256:93c077fd83879cf48f327a2491c24da447a09da6a7ab3cc311a6f5a61fcb5de0"}, +- {file = "protobuf-3.18.0-cp36-cp36m-win_amd64.whl", hash = "sha256:3b5b81bb665aac548b413480f4e0d8c38a74bc4dea57835f288a3ce74f63dfe9"}, +- {file = "protobuf-3.18.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:d11465040cadcea8ecf5f0b131af5099a9696f9d0bef6f88148b372bacc1c52d"}, +- {file = "protobuf-3.18.0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:f6138462643adce0ed6e49007a63b7fd7dc4fda1ef4e15a70fcebe76c1407a71"}, +- {file = "protobuf-3.18.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:877664b1b8d1e23553634f625e4e12aae4ff16cbbef473f8118c239d478f422a"}, +- {file = "protobuf-3.18.0-cp37-cp37m-win32.whl", hash = "sha256:5201333b7aa711965c5769b250f8565a9924e8e27f8b622bbc5e6847aeaab1b1"}, +- {file = "protobuf-3.18.0-cp37-cp37m-win_amd64.whl", hash = "sha256:1f3ecec3038c2fb4dad952d3d6cb9ca301999903a09e43794fb348da48f7577f"}, +- {file = "protobuf-3.18.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:17181fc0814655812aac108e755bd5185d71aa8d81bd241cec6e232c84097918"}, +- {file = "protobuf-3.18.0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:7646c20605fbee57e77fdbc4a90175538281b152f46ba17019916593f8062c2a"}, +- {file = "protobuf-3.18.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80b0a5157f3a53043daf8eb7cfa1220b27a5a63dd6655dbd8e1e6f7b5dcd6347"}, +- {file = "protobuf-3.18.0-cp38-cp38-win32.whl", hash = "sha256:5730de255c95b3403eedd1a568eb28203b913b6192ff5a3fdc3ff30f37107a38"}, +- {file = "protobuf-3.18.0-cp38-cp38-win_amd64.whl", hash = "sha256:9147565f93e6699d7512747766598afe63205f226ac7b61f47954974c9aab852"}, +- {file = "protobuf-3.18.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:568c049ff002a7523ed33fb612e6b97da002bf87ffb619a1fc3eadf2257a3b31"}, +- {file = "protobuf-3.18.0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:7e791a94db391ae22b3943fc88f6ba0e1f62b6ad58b33db7517df576c7834d23"}, +- {file = "protobuf-3.18.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42c04e66ec5a38ad2171639dc9860c2f9594668f709ea3a4a192acf7346853a7"}, +- {file = "protobuf-3.18.0-cp39-cp39-win32.whl", hash = "sha256:0a59ea8da307118372750e2fdfe0961622e675b8dd35e05c42384d618189a938"}, +- {file = "protobuf-3.18.0-cp39-cp39-win_amd64.whl", hash = "sha256:f7c8193ec805324ff6024242b00f64a24b94d56b895f62bf28a9d72a228d4fca"}, +- {file = "protobuf-3.18.0-py2.py3-none-any.whl", hash = "sha256:615099e52e9fbc9fde00177267a94ca820ecf4e80093e390753568b7d8cb3c1a"}, +- {file = "protobuf-3.18.0.tar.gz", hash = "sha256:18b308946a592e245299391e53c01b5b8efc2794f49986e80f37d7b5e60a270f"}, ++ {file = "protobuf-3.18.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:fa6d1049d5315566f55c04d0b50c0033415144f96a9d25c820dc542fe2bb7f45"}, ++ {file = "protobuf-3.18.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0e2790c580070cff2921b93d562539ae027064340151c50db6aaf94c33048cd"}, ++ {file = "protobuf-3.18.1-cp36-cp36m-win32.whl", hash = "sha256:7e2f0677d68ecdd1cfda2abea65873f5bc7c3f5aae199404a3f5c1d1198c1a63"}, ++ {file = "protobuf-3.18.1-cp36-cp36m-win_amd64.whl", hash = "sha256:6f714f5de9d40b3bec90ede4a688cce52f637ccdc5403afcda1f67598f4fdcd7"}, ++ {file = "protobuf-3.18.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:7a7be937c319146cc9f2626f0181e6809062c353e1fe449ecd0df374ba1036b2"}, ++ {file = "protobuf-3.18.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:10544fc7ace885a882623083c24da5b14148c77563acddc3c58d66f6153c09cd"}, ++ {file = "protobuf-3.18.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2ee8b11e3eb2ed38f12137c3c132270a0b1dd509e317228ac47b67f21a583f1"}, ++ {file = "protobuf-3.18.1-cp37-cp37m-win32.whl", hash = "sha256:c492c217d3f69f4d2d5619571e52ab98538edbf53caf67e53ea92bd0a3b5670f"}, ++ {file = "protobuf-3.18.1-cp37-cp37m-win_amd64.whl", hash = "sha256:3c1644f8a7f19b45c7a4c32278e2a55ae9e7e2f9e5f02d960a61f04a4890d3e6"}, ++ {file = "protobuf-3.18.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e9ac691f7b24e4371dcd3980e4f5d6c840a2010da37986203053fee995786ec5"}, ++ {file = "protobuf-3.18.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:93bad12895d8b0ebc66b605c2ef1802311595f881aef032d9f13282b7550e6b2"}, ++ {file = "protobuf-3.18.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0851b5b89191e1976d34fa2e8eb8659829dfb45252053224cf9df857fb5f6a45"}, ++ {file = "protobuf-3.18.1-cp38-cp38-win32.whl", hash = "sha256:09d9268f6f9da81b7657adcf2fb397524c82f20cdf9e0db3ff4e7567977abd67"}, ++ {file = "protobuf-3.18.1-cp38-cp38-win_amd64.whl", hash = "sha256:d6d927774c0ec746fed15a4faff5f44aad0b7a3421fadb6f3ae5ca1f2f8ae26e"}, ++ {file = "protobuf-3.18.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4d19c9cb805fd2be1d59eee39e152367ee92a30167e77bd06c8819f8f0009a4c"}, ++ {file = "protobuf-3.18.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:387f621bf7295a331f8c8a6962d097ceddeb85356792888cfa6a5c6bfc6886a4"}, ++ {file = "protobuf-3.18.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8c1c5d3966c856f60a9d8d62f4455d70c31026422acdd5c228edf22b65b16c38"}, ++ {file = "protobuf-3.18.1-cp39-cp39-win32.whl", hash = "sha256:f20f803892f2135e8b96dc58c9a0c6a7ad8436794bf8784af229498d939b4c77"}, ++ {file = "protobuf-3.18.1-cp39-cp39-win_amd64.whl", hash = "sha256:d76201380f41a2d83fb613a4683059d1fcafbe969518b3e409e279a8788fde2f"}, ++ {file = "protobuf-3.18.1-py2.py3-none-any.whl", hash = "sha256:61ca58e14033ca0dfa484a31d57237c1be3b6013454c7f53876a20fc88dd69b1"}, ++ {file = "protobuf-3.18.1.tar.gz", hash = "sha256:1c9bb40503751087300dd12ce2e90899d68628977905c76effc48e66d089391e"}, + ] + psutil = [ + {file = "psutil-5.8.0-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:0066a82f7b1b37d334e68697faba68e5ad5e858279fd6351c8ca6024e8d6ba64"}, +@@ -4535,8 +4571,8 @@ pyflakes = [ + {file = "pyflakes-2.3.1.tar.gz", hash = "sha256:f5bc8ecabc05bb9d291eb5203d6810b49040f6ff446a756326104746cc00c1db"}, + ] + pyjwt = [ +- {file = "PyJWT-2.1.0-py3-none-any.whl", hash = "sha256:934d73fbba91b0483d3857d1aff50e96b2a892384ee2c17417ed3203f173fca1"}, +- {file = "PyJWT-2.1.0.tar.gz", hash = "sha256:fba44e7898bbca160a2b2b501f492824fc8382485d3a6f11ba5d0c1937ce6130"}, ++ {file = "PyJWT-2.2.0-py3-none-any.whl", hash = "sha256:b0ed5824c8ecc5362e540c65dc6247567db130c4226670bf7699aec92fb4dae1"}, ++ {file = "PyJWT-2.2.0.tar.gz", hash = "sha256:a0b9a3b4e5ca5517cac9f1a6e9cd30bf1aa80be74fcdf4e28eded582ecfcfbae"}, + ] + pykwalify = [ + {file = "pykwalify-1.8.0-py2.py3-none-any.whl", hash = "sha256:731dfa87338cca9f559d1fca2bdea37299116e3139b73f78ca90a543722d6651"}, +@@ -4713,8 +4749,8 @@ python-socketio = [ + {file = "python_socketio-5.4.0-py3-none-any.whl", hash = "sha256:7ed57f6c024abdfeb9b25c74c0c00ffc18da47d903e8d72deecb87584370d1fc"}, + ] + pytz = [ +- {file = "pytz-2021.1-py2.py3-none-any.whl", hash = "sha256:eb10ce3e7736052ed3623d49975ce333bcd712c7bb19a58b9e2089d4057d0798"}, +- {file = "pytz-2021.1.tar.gz", hash = "sha256:83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da"}, ++ {file = "pytz-2021.3-py2.py3-none-any.whl", hash = "sha256:3672058bc3453457b622aab7a1c3bfd5ab0bdae451512f6cf25f64ed37f5b87c"}, ++ {file = "pytz-2021.3.tar.gz", hash = "sha256:acad2d8b20a1af07d4e4c9d2e9285c5ed9104354062f275f3fcd88dcef4f1326"}, + ] + pyyaml = [ + {file = "PyYAML-5.4.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:3b2b1824fe7112845700f815ff6a489360226a5609b96ec2190a45e62a9fc922"}, +@@ -4768,6 +4804,10 @@ regex = [ + {file = "regex-2021.7.6-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:b85ac458354165405c8a84725de7bbd07b00d9f72c31a60ffbf96bb38d3e25fa"}, + {file = "regex-2021.7.6-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:3f5716923d3d0bfb27048242a6e0f14eecdb2e2a7fac47eda1d055288595f222"}, + {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e5983c19d0beb6af88cb4d47afb92d96751fb3fa1784d8785b1cdf14c6519407"}, ++ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf1d2d183abc7faa101ebe0b8d04fd19cb9138820abc8589083035c9440b8ca6"}, ++ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1947e7de155063e1c495c50590229fb98720d4c383af5031bbcb413db33fa1be"}, ++ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:17d8a3f99b18d87ac54a449b836d485cc8c195bb6f5e4379c84c8519045facc9"}, ++ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d30895ec80cc80358392841add9dde81ea1d54a4949049269115e6b0555d0498"}, + {file = "regex-2021.7.6-cp36-cp36m-win32.whl", hash = "sha256:c92831dac113a6e0ab28bc98f33781383fe294df1a2c3dfd1e850114da35fd5b"}, + {file = "regex-2021.7.6-cp36-cp36m-win_amd64.whl", hash = "sha256:791aa1b300e5b6e5d597c37c346fb4d66422178566bbb426dd87eaae475053fb"}, + {file = "regex-2021.7.6-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:59506c6e8bd9306cd8a41511e32d16d5d1194110b8cfe5a11d102d8b63cf945d"}, +@@ -4778,6 +4818,10 @@ regex = [ + {file = "regex-2021.7.6-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:173bc44ff95bc1e96398c38f3629d86fa72e539c79900283afa895694229fe6a"}, + {file = "regex-2021.7.6-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:15dddb19823f5147e7517bb12635b3c82e6f2a3a6b696cc3e321522e8b9308ad"}, + {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2ddeabc7652024803666ea09f32dd1ed40a0579b6fbb2a213eba590683025895"}, ++ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8244c681018423a0d1784bc6b9af33bdf55f2ab8acb1f3cd9dd83d90e0813253"}, ++ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8a4c742089faf0e51469c6a1ad7e3d3d21afae54a16a6cead85209dfe0a1ce65"}, ++ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:914e626dc8e75fe4fc9b7214763f141d9f40165d00dfe680b104fa1b24063bbf"}, ++ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3fabb19c82ecf39832a3f5060dfea9a7ab270ef156039a1143a29a83a09a62de"}, + {file = "regex-2021.7.6-cp37-cp37m-win32.whl", hash = "sha256:f080248b3e029d052bf74a897b9d74cfb7643537fbde97fe8225a6467fb559b5"}, + {file = "regex-2021.7.6-cp37-cp37m-win_amd64.whl", hash = "sha256:d8bbce0c96462dbceaa7ac4a7dfbbee92745b801b24bce10a98d2f2b1ea9432f"}, + {file = "regex-2021.7.6-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:edd1a68f79b89b0c57339bce297ad5d5ffcc6ae7e1afdb10f1947706ed066c9c"}, +@@ -4788,6 +4832,10 @@ regex = [ + {file = "regex-2021.7.6-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:bc84fb254a875a9f66616ed4538542fb7965db6356f3df571d783f7c8d256edd"}, + {file = "regex-2021.7.6-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:598c0a79b4b851b922f504f9f39a863d83ebdfff787261a5ed061c21e67dd761"}, + {file = "regex-2021.7.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:875c355360d0f8d3d827e462b29ea7682bf52327d500a4f837e934e9e4656068"}, ++ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dfc0957c4a4b91eff5ad036088769e600a25774256cd0e1154378591ce573f08"}, ++ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:efb4af05fa4d2fc29766bf516f1f5098d6b5c3ed846fde980c18bf8646ad3979"}, ++ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7423aca7cc30a6228ccdcf2ea76f12923d652c5c7c6dc1959a0b004e308f39fb"}, ++ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:bb9834c1e77493efd7343b8e38950dee9797d2d6f2d5fd91c008dfaef64684b9"}, + {file = "regex-2021.7.6-cp38-cp38-win32.whl", hash = "sha256:e586f448df2bbc37dfadccdb7ccd125c62b4348cb90c10840d695592aa1b29e0"}, + {file = "regex-2021.7.6-cp38-cp38-win_amd64.whl", hash = "sha256:2fe5e71e11a54e3355fa272137d521a40aace5d937d08b494bed4529964c19c4"}, + {file = "regex-2021.7.6-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6110bab7eab6566492618540c70edd4d2a18f40ca1d51d704f1d81c52d245026"}, +@@ -4798,6 +4846,10 @@ regex = [ + {file = "regex-2021.7.6-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:2bceeb491b38225b1fee4517107b8491ba54fba77cf22a12e996d96a3c55613d"}, + {file = "regex-2021.7.6-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:f98dc35ab9a749276f1a4a38ab3e0e2ba1662ce710f6530f5b0a6656f1c32b58"}, + {file = "regex-2021.7.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:319eb2a8d0888fa6f1d9177705f341bc9455a2c8aca130016e52c7fe8d6c37a3"}, ++ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:598ee917dbe961dcf827217bf2466bb86e4ee5a8559705af57cbabb3489dd37e"}, ++ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:56fc7045a1999a8d9dd1896715bc5c802dfec5b9b60e883d2cbdecb42adedea4"}, ++ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e8363ac90ea63c3dd0872dfdb695f38aff3334bfa5712cffb238bd3ffef300e3"}, ++ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:716a6db91b3641f566531ffcc03ceec00b2447f0db9942b3c6ea5d2827ad6be3"}, + {file = "regex-2021.7.6-cp39-cp39-win32.whl", hash = "sha256:eaf58b9e30e0e546cdc3ac06cf9165a1ca5b3de8221e9df679416ca667972035"}, + {file = "regex-2021.7.6-cp39-cp39-win_amd64.whl", hash = "sha256:4c9c3155fe74269f61e27617529b7f09552fbb12e44b1189cebbdb24294e6e1c"}, + {file = "regex-2021.7.6.tar.gz", hash = "sha256:8394e266005f2d8c6f0bc6780001f7afa3ef81a7a2111fa35058ded6fce79e4d"}, +@@ -5100,6 +5152,10 @@ tabulate = [ + {file = "tabulate-0.8.9-py3-none-any.whl", hash = "sha256:d7c013fe7abbc5e491394e10fa845f8f32fe54f8dc60c6622c6cf482d25d47e4"}, + {file = "tabulate-0.8.9.tar.gz", hash = "sha256:eb1d13f25760052e8931f2ef80aaf6045a6cceb47514db8beab24cded16f13a7"}, + ] ++tarsafe = [ ++ {file = "tarsafe-0.0.3-py3-none-any.whl", hash = "sha256:f8181c5559aea70af2579a0dc0811d2e9e3eabd706dd594555b4dfa52c0be51a"}, ++ {file = "tarsafe-0.0.3.tar.gz", hash = "sha256:7acf73a11b576fcbb003b52adecf4706d6c3009c6af28a01fd21949235ffd806"}, ++] + tensorboard = [ + {file = "tensorboard-2.6.0-py3-none-any.whl", hash = "sha256:f7dac4cdfb52d14c9e3f74585ce2aaf8e6203620a864e51faf84988b09f7bbdb"}, + ] +@@ -5184,8 +5240,8 @@ thinc = [ + {file = "thinc-8.0.10.tar.gz", hash = "sha256:b5e4db8d24e6be8a5f1e4a17854772b79a2b560224519f50a21f3951ca24001f"}, + ] + threadpoolctl = [ +- {file = "threadpoolctl-2.2.0-py3-none-any.whl", hash = "sha256:e5a995e3ffae202758fa8a90082e35783b9370699627ae2733cd1c3a73553616"}, +- {file = "threadpoolctl-2.2.0.tar.gz", hash = "sha256:86d4b6801456d780e94681d155779058759eaef3c3564758b17b6c99db5f81cb"}, ++ {file = "threadpoolctl-3.0.0-py3-none-any.whl", hash = "sha256:4fade5b3b48ae4b1c30f200b28f39180371104fccc642e039e0f2435ec8cc211"}, ++ {file = "threadpoolctl-3.0.0.tar.gz", hash = "sha256:d03115321233d0be715f0d3a5ad1d6c065fe425ddc2d671ca8e45e9fd5d7a52a"}, + ] + tokenizers = [ + {file = "tokenizers-0.7.0-cp35-cp35m-macosx_10_10_x86_64.whl", hash = "sha256:c9edc043bc14462faf8b261b528661718e9c4f0b8424fb25be71cae26187432a"}, +@@ -5258,8 +5314,8 @@ typed-ast = [ + {file = "typed_ast-1.4.3.tar.gz", hash = "sha256:fb1bbeac803adea29cedd70781399c99138358c26d05fcbd23c13016b7f5ec65"}, + ] + typeguard = [ +- {file = "typeguard-2.12.1-py3-none-any.whl", hash = "sha256:cc15ef2704c9909ef9c80e19c62fb8468c01f75aad12f651922acf4dbe822e02"}, +- {file = "typeguard-2.12.1.tar.gz", hash = "sha256:c2af8b9bdd7657f4bd27b45336e7930171aead796711bc4cfc99b4731bb9d051"}, ++ {file = "typeguard-2.13.0-py3-none-any.whl", hash = "sha256:0bc44d1ff865b522eda969627868b0e001c8329296ce50aededbea03febc79ee"}, ++ {file = "typeguard-2.13.0.tar.gz", hash = "sha256:04e38f92eb59410c9375d3be23df65e0a7643f2e8bcbd421423d808d2f9e99df"}, + ] + typer = [ + {file = "typer-0.4.0-py3-none-any.whl", hash = "sha256:d81169725140423d072df464cad1ff25ee154ef381aaf5b8225352ea187ca338"}, +@@ -5341,8 +5397,8 @@ ujson = [ + {file = "ujson-4.2.0.tar.gz", hash = "sha256:fffe509f556861c7343c6cba57ed05fe7bcf4b48a934a5b946ccb45428cf8883"}, + ] + uritemplate = [ +- {file = "uritemplate-3.0.1-py2.py3-none-any.whl", hash = "sha256:07620c3f3f8eed1f12600845892b0e036a2420acf513c53f7de0abd911a5894f"}, +- {file = "uritemplate-3.0.1.tar.gz", hash = "sha256:5af8ad10cec94f215e3f48112de2022e1d5a37ed427fbd88652fa908f2ab7cae"}, ++ {file = "uritemplate-4.0.0-py2.py3-none-any.whl", hash = "sha256:9de62e39c3f7f7584982a4159d70e6aafda5a479a91cccc18e89ae865eab4ae4"}, ++ {file = "uritemplate-4.0.0.tar.gz", hash = "sha256:6f4c5b093c915d269df69f291028a72dfdcaf68c8345b92e180f31daf53c4971"}, + ] + urllib3 = [ + {file = "urllib3-1.26.7-py2.py3-none-any.whl", hash = "sha256:c4fdf4019605b6e5423637e01bc9fe4daef873709a7973e195ceba0a62bbc844"}, +@@ -5404,8 +5460,8 @@ websockets = [ + {file = "websockets-8.0.2.tar.gz", hash = "sha256:882a7266fa867a2ebb2c0baaa0f9159cabf131cf18c1b4270d79ad42f9208dc5"}, + ] + werkzeug = [ +- {file = "Werkzeug-2.0.1-py3-none-any.whl", hash = "sha256:6c1ec500dcdba0baa27600f6a22f6333d8b662d22027ff9f6202e3367413caa8"}, +- {file = "Werkzeug-2.0.1.tar.gz", hash = "sha256:1de1db30d010ff1af14a009224ec49ab2329ad2cde454c8a708130642d579c42"}, ++ {file = "Werkzeug-2.0.2-py3-none-any.whl", hash = "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f"}, ++ {file = "Werkzeug-2.0.2.tar.gz", hash = "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a"}, + ] + wrapt = [ + {file = "wrapt-1.12.1.tar.gz", hash = "sha256:b62ffa81fb85f4332a4f609cab4ac40709470da05643a082ec1eb88e6d9b97d7"}, +@@ -5415,43 +5471,78 @@ xmltodict = [ + {file = "xmltodict-0.12.0.tar.gz", hash = "sha256:50d8c638ed7ecb88d90561beedbf720c9b4e851a9fa6c47ebd64e99d166d8a21"}, + ] + yarl = [ +- {file = "yarl-1.6.3-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:0355a701b3998dcd832d0dc47cc5dedf3874f966ac7f870e0f3a6788d802d434"}, +- {file = "yarl-1.6.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:bafb450deef6861815ed579c7a6113a879a6ef58aed4c3a4be54400ae8871478"}, +- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:547f7665ad50fa8563150ed079f8e805e63dd85def6674c97efd78eed6c224a6"}, +- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:63f90b20ca654b3ecc7a8d62c03ffa46999595f0167d6450fa8383bab252987e"}, +- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_ppc64le.whl", hash = "sha256:97b5bdc450d63c3ba30a127d018b866ea94e65655efaf889ebeabc20f7d12406"}, +- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:d8d07d102f17b68966e2de0e07bfd6e139c7c02ef06d3a0f8d2f0f055e13bb76"}, +- {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:15263c3b0b47968c1d90daa89f21fcc889bb4b1aac5555580d74565de6836366"}, +- {file = "yarl-1.6.3-cp36-cp36m-win32.whl", hash = "sha256:b5dfc9a40c198334f4f3f55880ecf910adebdcb2a0b9a9c23c9345faa9185721"}, +- {file = "yarl-1.6.3-cp36-cp36m-win_amd64.whl", hash = "sha256:b2e9a456c121e26d13c29251f8267541bd75e6a1ccf9e859179701c36a078643"}, +- {file = "yarl-1.6.3-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:ce3beb46a72d9f2190f9e1027886bfc513702d748047b548b05dab7dfb584d2e"}, +- {file = "yarl-1.6.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:2ce4c621d21326a4a5500c25031e102af589edb50c09b321049e388b3934eec3"}, +- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:d26608cf178efb8faa5ff0f2d2e77c208f471c5a3709e577a7b3fd0445703ac8"}, +- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:4c5bcfc3ed226bf6419f7a33982fb4b8ec2e45785a0561eb99274ebbf09fdd6a"}, +- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:4736eaee5626db8d9cda9eb5282028cc834e2aeb194e0d8b50217d707e98bb5c"}, +- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:68dc568889b1c13f1e4745c96b931cc94fdd0defe92a72c2b8ce01091b22e35f"}, +- {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:7356644cbed76119d0b6bd32ffba704d30d747e0c217109d7979a7bc36c4d970"}, +- {file = "yarl-1.6.3-cp37-cp37m-win32.whl", hash = "sha256:00d7ad91b6583602eb9c1d085a2cf281ada267e9a197e8b7cae487dadbfa293e"}, +- {file = "yarl-1.6.3-cp37-cp37m-win_amd64.whl", hash = "sha256:69ee97c71fee1f63d04c945f56d5d726483c4762845400a6795a3b75d56b6c50"}, +- {file = "yarl-1.6.3-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:e46fba844f4895b36f4c398c5af062a9808d1f26b2999c58909517384d5deda2"}, +- {file = "yarl-1.6.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:31ede6e8c4329fb81c86706ba8f6bf661a924b53ba191b27aa5fcee5714d18ec"}, +- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:fcbb48a93e8699eae920f8d92f7160c03567b421bc17362a9ffbbd706a816f71"}, +- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:72a660bdd24497e3e84f5519e57a9ee9220b6f3ac4d45056961bf22838ce20cc"}, +- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:324ba3d3c6fee56e2e0b0d09bf5c73824b9f08234339d2b788af65e60040c959"}, +- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:e6b5460dc5ad42ad2b36cca524491dfcaffbfd9c8df50508bddc354e787b8dc2"}, +- {file = "yarl-1.6.3-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:6d6283d8e0631b617edf0fd726353cb76630b83a089a40933043894e7f6721e2"}, +- {file = "yarl-1.6.3-cp38-cp38-win32.whl", hash = "sha256:9ede61b0854e267fd565e7527e2f2eb3ef8858b301319be0604177690e1a3896"}, +- {file = "yarl-1.6.3-cp38-cp38-win_amd64.whl", hash = "sha256:f0b059678fd549c66b89bed03efcabb009075bd131c248ecdf087bdb6faba24a"}, +- {file = "yarl-1.6.3-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:329412812ecfc94a57cd37c9d547579510a9e83c516bc069470db5f75684629e"}, +- {file = "yarl-1.6.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:c49ff66d479d38ab863c50f7bb27dee97c6627c5fe60697de15529da9c3de724"}, +- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f040bcc6725c821a4c0665f3aa96a4d0805a7aaf2caf266d256b8ed71b9f041c"}, +- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:d5c32c82990e4ac4d8150fd7652b972216b204de4e83a122546dce571c1bdf25"}, +- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:d597767fcd2c3dc49d6eea360c458b65643d1e4dbed91361cf5e36e53c1f8c96"}, +- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:8aa3decd5e0e852dc68335abf5478a518b41bf2ab2f330fe44916399efedfae0"}, +- {file = "yarl-1.6.3-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:73494d5b71099ae8cb8754f1df131c11d433b387efab7b51849e7e1e851f07a4"}, +- {file = "yarl-1.6.3-cp39-cp39-win32.whl", hash = "sha256:5b883e458058f8d6099e4420f0cc2567989032b5f34b271c0827de9f1079a424"}, +- {file = "yarl-1.6.3-cp39-cp39-win_amd64.whl", hash = "sha256:4953fb0b4fdb7e08b2f3b3be80a00d28c5c8a2056bb066169de00e6501b986b6"}, +- {file = "yarl-1.6.3.tar.gz", hash = "sha256:8a9066529240171b68893d60dca86a763eae2139dd42f42106b03cf4b426bf10"}, ++ {file = "yarl-1.7.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e35d8230e4b08d86ea65c32450533b906a8267a87b873f2954adeaecede85169"}, ++ {file = "yarl-1.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:eb4b3f277880c314e47720b4b6bb2c85114ab3c04c5442c9bc7006b3787904d8"}, ++ {file = "yarl-1.7.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c7015dcedb91d90a138eebdc7e432aec8966e0147ab2a55f2df27b1904fa7291"}, ++ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb3e478175e15e00d659fb0354a6a8db71a7811a2a5052aed98048bc972e5d2b"}, ++ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8c409aa3a7966647e7c1c524846b362a6bcbbe120bf8a176431f940d2b9a2e"}, ++ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b22ea41c7e98170474a01e3eded1377d46b2dfaef45888a0005c683eaaa49285"}, ++ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:a7dfc46add4cfe5578013dbc4127893edc69fe19132d2836ff2f6e49edc5ecd6"}, ++ {file = "yarl-1.7.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:82ff6f85f67500a4f74885d81659cd270eb24dfe692fe44e622b8a2fd57e7279"}, ++ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:f3cd2158b2ed0fb25c6811adfdcc47224efe075f2d68a750071dacc03a7a66e4"}, ++ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:59c0f13f9592820c51280d1cf811294d753e4a18baf90f0139d1dc93d4b6fc5f"}, ++ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:7f7655ad83d1a8afa48435a449bf2f3009293da1604f5dd95b5ddcf5f673bd69"}, ++ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:aa9f0d9b62d15182341b3e9816582f46182cab91c1a57b2d308b9a3c4e2c4f78"}, ++ {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fdd1b90c225a653b1bd1c0cae8edf1957892b9a09c8bf7ee6321eeb8208eac0f"}, ++ {file = "yarl-1.7.0-cp310-cp310-win32.whl", hash = "sha256:7c8d0bb76eabc5299db203e952ec55f8f4c53f08e0df4285aac8c92bd9e12675"}, ++ {file = "yarl-1.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:622a36fa779efb4ff9eff5fe52730ff17521431379851a31e040958fc251670c"}, ++ {file = "yarl-1.7.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:3d461b7a8e139b9e4b41f62eb417ffa0b98d1c46d4caf14c845e6a3b349c0bb1"}, ++ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81cfacdd1e40bc931b5519499342efa388d24d262c30a3d31187bfa04f4a7001"}, ++ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:821b978f2152be7695d4331ef0621d207aedf9bbd591ba23a63412a3efc29a01"}, ++ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b64bd24c8c9a487f4a12260dc26732bf41028816dbf0c458f17864fbebdb3131"}, ++ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:98c9ddb92b60a83c21be42c776d3d9d5ec632a762a094c41bda37b7dfbd2cd83"}, ++ {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a532d75ca74431c053a88a802e161fb3d651b8bf5821a3440bc3616e38754583"}, ++ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:053e09817eafb892e94e172d05406c1b3a22a93bc68f6eff5198363a3d764459"}, ++ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:98c51f02d542945d306c8e934aa2c1e66ba5e9c1c86b5bf37f3a51c8a747067e"}, ++ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:15ec41a5a5fdb7bace6d7b16701f9440007a82734f69127c0fbf6d87e10f4a1e"}, ++ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:a7f08819dba1e1255d6991ed37448a1bf4b1352c004bcd899b9da0c47958513d"}, ++ {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:8e3ffab21db0542ffd1887f3b9575ddd58961f2cf61429cb6458afc00c4581e0"}, ++ {file = "yarl-1.7.0-cp36-cp36m-win32.whl", hash = "sha256:50127634f519b2956005891507e3aa4ac345f66a7ea7bbc2d7dcba7401f41898"}, ++ {file = "yarl-1.7.0-cp36-cp36m-win_amd64.whl", hash = "sha256:36ec44f15193f6d5288d42ebb8e751b967ebdfb72d6830983838d45ab18edb4f"}, ++ {file = "yarl-1.7.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ec1b5a25a25c880c976d0bb3d107def085bb08dbb3db7f4442e0a2b980359d24"}, ++ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b36f5a63c891f813c6f04ef19675b382efc190fd5ce7e10ab19386d2548bca06"}, ++ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:38173b8c3a29945e7ecade9a3f6ff39581eee8201338ee6a2c8882db5df3e806"}, ++ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8ba402f32184f0b405fb281b93bd0d8ab7e3257735b57b62a6ed2e94cdf4fe50"}, ++ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:be52bc5208d767cdd8308a9e93059b3b36d1e048fecbea0e0346d0d24a76adc0"}, ++ {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:08c2044a956f4ef30405f2f433ce77f1f57c2c773bf81ae43201917831044d5a"}, ++ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:484d61c047c45670ef5967653a1d0783e232c54bf9dd786a7737036828fa8d54"}, ++ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:b7de92a4af85cfcaf4081f8aa6165b1d63ee5de150af3ee85f954145f93105a7"}, ++ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:376e41775aab79c5575534924a386c8e0f1a5d91db69fc6133fd27a489bcaf10"}, ++ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:8a8b10d0e7bac154f959b709fcea593cda527b234119311eb950096653816a86"}, ++ {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:f46cd4c43e6175030e2a56def8f1d83b64e6706eeb2bb9ab0ef4756f65eab23f"}, ++ {file = "yarl-1.7.0-cp37-cp37m-win32.whl", hash = "sha256:b28cfb46140efe1a6092b8c5c4994a1fe70dc83c38fbcea4992401e0c6fb9cce"}, ++ {file = "yarl-1.7.0-cp37-cp37m-win_amd64.whl", hash = "sha256:9624154ec9c02a776802da1086eed7f5034bd1971977f5146233869c2ac80297"}, ++ {file = "yarl-1.7.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:69945d13e1bbf81784a9bc48824feb9cd66491e6a503d4e83f6cd7c7cc861361"}, ++ {file = "yarl-1.7.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:46a742ed9e363bd01be64160ce7520e92e11989bd4cb224403cfd31c101cc83d"}, ++ {file = "yarl-1.7.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:cb4ff1ac7cb4500f43581b3f4cbd627d702143aa6be1fdc1fa3ebffaf4dc1be5"}, ++ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3ad51e17cd65ea3debb0e10f0120cf8dd987c741fe423ed2285087368090b33d"}, ++ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7e37786ea89a5d3ffbbf318ea9790926f8dfda83858544f128553c347ad143c6"}, ++ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c63c1e208f800daad71715786bfeb1cecdc595d87e2e9b1cd234fd6e597fd71d"}, ++ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:91cbe24300c11835ef186436363352b3257db7af165e0a767f4f17aa25761388"}, ++ {file = "yarl-1.7.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e510dbec7c59d32eaa61ffa48173d5e3d7170a67f4a03e8f5e2e9e3971aca622"}, ++ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:3def6e681cc02397e5d8141ee97b41d02932b2bcf0fb34532ad62855eab7c60e"}, ++ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:263c81b94e6431942b27f6f671fa62f430a0a5c14bb255f2ab69eeb9b2b66ff7"}, ++ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:e78c91faefe88d601ddd16e3882918dbde20577a2438e2320f8239c8b7507b8f"}, ++ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:22b2430c49713bfb2f0a0dd4a8d7aab218b28476ba86fd1c78ad8899462cbcf2"}, ++ {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2e7ad9db939082f5d0b9269cfd92c025cb8f2fbbb1f1b9dc5a393c639db5bd92"}, ++ {file = "yarl-1.7.0-cp38-cp38-win32.whl", hash = "sha256:3a31e4a8dcb1beaf167b7e7af61b88cb961b220db8d3ba1c839723630e57eef7"}, ++ {file = "yarl-1.7.0-cp38-cp38-win_amd64.whl", hash = "sha256:d579957439933d752358c6a300c93110f84aae67b63dd0c19dde6ecbf4056f6b"}, ++ {file = "yarl-1.7.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:87721b549505a546eb003252185103b5ec8147de6d3ad3714d148a5a67b6fe53"}, ++ {file = "yarl-1.7.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a1fa866fa24d9f4108f9e58ea8a2135655419885cdb443e36b39a346e1181532"}, ++ {file = "yarl-1.7.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1d3b8449dfedfe94eaff2b77954258b09b24949f6818dfa444b05dbb05ae1b7e"}, ++ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:db2372e350794ce8b9f810feb094c606b7e0e4aa6807141ac4fadfe5ddd75bb0"}, ++ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a06d9d0b9a97fa99b84fee71d9dd11e69e21ac8a27229089f07b5e5e50e8d63c"}, ++ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a3455c2456d6307bcfa80bc1157b8603f7d93573291f5bdc7144489ca0df4628"}, ++ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:d30d67e3486aea61bb2cbf7cf81385364c2e4f7ce7469a76ed72af76a5cdfe6b"}, ++ {file = "yarl-1.7.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:c18a4b286e8d780c3a40c31d7b79836aa93b720f71d5743f20c08b7e049ca073"}, ++ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:d54c925396e7891666cabc0199366ca55b27d003393465acef63fd29b8b7aa92"}, ++ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:64773840952de17851a1c7346ad7f71688c77e74248d1f0bc230e96680f84028"}, ++ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:acbf1756d9dc7cd0ae943d883be72e84e04396f6c2ff93a6ddeca929d562039f"}, ++ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:2e48f27936aa838939c798f466c851ba4ae79e347e8dfce43b009c64b930df12"}, ++ {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1beef4734ca1ad40a9d8c6b20a76ab46e3a2ed09f38561f01e4aa2ea82cafcef"}, ++ {file = "yarl-1.7.0-cp39-cp39-win32.whl", hash = "sha256:8ee78c9a5f3c642219d4607680a4693b59239c27a3aa608b64ef79ddc9698039"}, ++ {file = "yarl-1.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:d750503682605088a14d29a4701548c15c510da4f13c8b17409c4097d5b04c52"}, ++ {file = "yarl-1.7.0.tar.gz", hash = "sha256:8e7ebaf62e19c2feb097ffb7c94deb0f0c9fab52590784c8cd679d30ab009162"}, + ] + zipp = [ + {file = "zipp-3.6.0-py3-none-any.whl", hash = "sha256:9fe5ea21568a0a70e50f273397638d39b03353731e6cbbb3fd8502a33fec40bc"}, +diff --git a/pyproject.toml b/pyproject.toml +index 69364c5f6e5..0be486aa0e9 100644 +--- a/pyproject.toml ++++ b/pyproject.toml +@@ -122,6 +122,7 @@ joblib = ">=0.15.1,<1.1.0" + sentry-sdk = ">=0.17.0,<1.3.0" + aio-pika = "^6.7.1" + pyTelegramBotAPI = "^3.7.3" ++tarsafe = "^0.0.3" + + [tool.poetry.dev-dependencies] + pytest-cov = "^2.10.0" +diff --git a/rasa/model.py b/rasa/model.py +index 78be4034060..21ff2b14de0 100644 +--- a/rasa/model.py ++++ b/rasa/model.py +@@ -222,13 +222,14 @@ def unpack_model( + + """ + import tarfile ++ from tarsafe import TarSafe + + if working_directory is None: + working_directory = tempfile.mkdtemp() + + # All files are in a subdirectory. + try: +- with tarfile.open(model_file, mode="r:gz") as tar: ++ with TarSafe.open(model_file, mode="r:gz") as tar: + tar.extractall(working_directory) + logger.debug(f"Extracted model to '{working_directory}'.") + except (tarfile.TarError, ValueError) as e: +diff --git a/rasa/nlu/persistor.py b/rasa/nlu/persistor.py +index 9ba50b8e0ed..9f777aeb659 100644 +--- a/rasa/nlu/persistor.py ++++ b/rasa/nlu/persistor.py +@@ -2,7 +2,7 @@ import abc + import logging + import os + import shutil +-import tarfile ++from tarsafe import TarSafe + from typing import Optional, Text, Tuple, TYPE_CHECKING + + import rasa.shared.utils.common +@@ -103,7 +103,7 @@ class Persistor(abc.ABC): + @staticmethod + def _decompress(compressed_path: Text, target_path: Text) -> None: + +- with tarfile.open(compressed_path, "r:gz") as tar: ++ with TarSafe.open(compressed_path, "r:gz") as tar: + tar.extractall(target_path) # target dir will be created if it not exists + + +diff --git a/rasa/utils/io.py b/rasa/utils/io.py +index 65aa2069759..c0831be91d2 100644 +--- a/rasa/utils/io.py ++++ b/rasa/utils/io.py +@@ -3,6 +3,7 @@ import logging + import os + import pickle + import tarfile ++from tarsafe import TarSafe + import tempfile + import warnings + import zipfile +@@ -87,7 +88,7 @@ def unarchive(byte_array: bytes, directory: Text) -> Text: + Tries to use tar first to unpack, if that fails, zip will be used.""" + + try: +- tar = tarfile.open(fileobj=IOReader(byte_array)) ++ tar = TarSafe.open(fileobj=IOReader(byte_array)) + tar.extractall(directory) + tar.close() + return directory diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..67ea715d836be088b0e1d4ccabac47ccd3b25729 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.md @@ -0,0 +1,140 @@ +# Patch-overlapping Python context after the fix + +## `rasa/model.py` — `function:unpack_model` (lines 210-239) + +```python +def unpack_model( + model_file: Text, working_directory: Optional[Union[Path, Text]] = None +) -> TempDirectoryPath: + """Unpack a zipped Rasa model. + + Args: + model_file: Path to zipped model. + working_directory: Location where the model should be unpacked to. + If `None` a temporary directory will be created. + + Returns: + Path to unpacked Rasa model. + + """ + import tarfile + from tarsafe import TarSafe + + if working_directory is None: + working_directory = tempfile.mkdtemp() + + # All files are in a subdirectory. + try: + with TarSafe.open(model_file, mode="r:gz") as tar: + tar.extractall(working_directory) + logger.debug(f"Extracted model to '{working_directory}'.") + except (tarfile.TarError, ValueError) as e: + logger.error(f"Failed to extract model at {model_file}. Error: {e}") + raise + + return TempDirectoryPath(working_directory) +``` + +## `rasa/nlu/persistor.py` — `class:Persistor` (lines 50-107) + +```python +class Persistor(abc.ABC): + """Store models in cloud and fetch them when needed.""" + + def persist(self, model_directory: Text, model_name: Text) -> None: + """Uploads a model persisted in the `target_dir` to cloud storage.""" + if not os.path.isdir(model_directory): + raise ValueError(f"Target directory '{model_directory}' not found.") + + file_key, tar_path = self._compress(model_directory, model_name) + self._persist_tar(file_key, tar_path) + + def retrieve(self, model_name: Text, target_path: Text) -> None: + """Downloads a model that has been persisted to cloud storage.""" + tar_name = model_name + + if not model_name.endswith("tar.gz"): + # ensure backward compatibility + tar_name = self._tar_name(model_name) + + self._retrieve_tar(tar_name) + self._decompress(os.path.basename(tar_name), target_path) + + @abc.abstractmethod + def _retrieve_tar(self, filename: Text) -> Text: + """Downloads a model previously persisted to cloud storage.""" + raise NotImplementedError + + @abc.abstractmethod + def _persist_tar(self, filekey: Text, tarname: Text) -> None: # noqa: F841 + """Uploads a model persisted in the `target_dir` to cloud storage.""" + raise NotImplementedError + + def _compress(self, model_directory: Text, model_name: Text) -> Tuple[Text, Text]: + """Creates a compressed archive and returns key and tar.""" + import tempfile + + dirpath = tempfile.mkdtemp() + base_name = self._tar_name(model_name, include_extension=False) + tar_name = shutil.make_archive( + os.path.join(dirpath, base_name), + "gztar", + root_dir=model_directory, + base_dir=".", + ) + file_key = os.path.basename(tar_name) + return file_key, tar_name + + @staticmethod + def _tar_name(model_name: Text, include_extension: bool = True) -> Text: + + ext = ".tar.gz" if include_extension else "" + return f"{model_name}{ext}" + + @staticmethod + def _decompress(compressed_path: Text, target_path: Text) -> None: + + with TarSafe.open(compressed_path, "r:gz") as tar: + tar.extractall(target_path) # target dir will be created if it not exists +``` + +## `rasa/nlu/persistor.py` — `function:Persistor._decompress` (lines 103-107) + +```python + def _decompress(compressed_path: Text, target_path: Text) -> None: + + with TarSafe.open(compressed_path, "r:gz") as tar: + tar.extractall(target_path) # target dir will be created if it not exists +``` + +## `rasa/nlu/persistor.py` — `module:@5` (lines 5-5) + +```python +from tarsafe import TarSafe +``` + +## `rasa/utils/io.py` — `function:unarchive` (lines 85-99) + +```python +def unarchive(byte_array: bytes, directory: Text) -> Text: + """Tries to unpack a byte array interpreting it as an archive. + + Tries to use tar first to unpack, if that fails, zip will be used.""" + + try: + tar = TarSafe.open(fileobj=IOReader(byte_array)) + tar.extractall(directory) + tar.close() + return directory + except tarfile.TarError: + zip_ref = zipfile.ZipFile(IOReader(byte_array)) + zip_ref.extractall(directory) + zip_ref.close() + return directory +``` + +## `rasa/utils/io.py` — `module:@6` (lines 6-6) + +```python +from tarsafe import TarSafe +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..c2dd388e64a04d93159920e1a5449db83740ce87 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.md @@ -0,0 +1,145 @@ +# Patch-overlapping Python context before the fix + +## `rasa/model.py` — `function:unpack_model` (lines 210-238) + +```python +def unpack_model( + model_file: Text, working_directory: Optional[Union[Path, Text]] = None +) -> TempDirectoryPath: + """Unpack a zipped Rasa model. + + Args: + model_file: Path to zipped model. + working_directory: Location where the model should be unpacked to. + If `None` a temporary directory will be created. + + Returns: + Path to unpacked Rasa model. + + """ + import tarfile + + if working_directory is None: + working_directory = tempfile.mkdtemp() + + # All files are in a subdirectory. + try: + with tarfile.open(model_file, mode="r:gz") as tar: + tar.extractall(working_directory) + logger.debug(f"Extracted model to '{working_directory}'.") + except (tarfile.TarError, ValueError) as e: + logger.error(f"Failed to extract model at {model_file}. Error: {e}") + raise + + return TempDirectoryPath(working_directory) +``` + +## `rasa/nlu/persistor.py` — `class:Persistor` (lines 50-107) + +```python +class Persistor(abc.ABC): + """Store models in cloud and fetch them when needed.""" + + def persist(self, model_directory: Text, model_name: Text) -> None: + """Uploads a model persisted in the `target_dir` to cloud storage.""" + if not os.path.isdir(model_directory): + raise ValueError(f"Target directory '{model_directory}' not found.") + + file_key, tar_path = self._compress(model_directory, model_name) + self._persist_tar(file_key, tar_path) + + def retrieve(self, model_name: Text, target_path: Text) -> None: + """Downloads a model that has been persisted to cloud storage.""" + tar_name = model_name + + if not model_name.endswith("tar.gz"): + # ensure backward compatibility + tar_name = self._tar_name(model_name) + + self._retrieve_tar(tar_name) + self._decompress(os.path.basename(tar_name), target_path) + + @abc.abstractmethod + def _retrieve_tar(self, filename: Text) -> Text: + """Downloads a model previously persisted to cloud storage.""" + raise NotImplementedError + + @abc.abstractmethod + def _persist_tar(self, filekey: Text, tarname: Text) -> None: # noqa: F841 + """Uploads a model persisted in the `target_dir` to cloud storage.""" + raise NotImplementedError + + def _compress(self, model_directory: Text, model_name: Text) -> Tuple[Text, Text]: + """Creates a compressed archive and returns key and tar.""" + import tempfile + + dirpath = tempfile.mkdtemp() + base_name = self._tar_name(model_name, include_extension=False) + tar_name = shutil.make_archive( + os.path.join(dirpath, base_name), + "gztar", + root_dir=model_directory, + base_dir=".", + ) + file_key = os.path.basename(tar_name) + return file_key, tar_name + + @staticmethod + def _tar_name(model_name: Text, include_extension: bool = True) -> Text: + + ext = ".tar.gz" if include_extension else "" + return f"{model_name}{ext}" + + @staticmethod + def _decompress(compressed_path: Text, target_path: Text) -> None: + + with tarfile.open(compressed_path, "r:gz") as tar: + tar.extractall(target_path) # target dir will be created if it not exists +``` + +## `rasa/nlu/persistor.py` — `function:Persistor._decompress` (lines 103-107) + +```python + def _decompress(compressed_path: Text, target_path: Text) -> None: + + with tarfile.open(compressed_path, "r:gz") as tar: + tar.extractall(target_path) # target dir will be created if it not exists +``` + +## `rasa/nlu/persistor.py` — `module:@5` (lines 5-5) + +```python +import tarfile +``` + +## `rasa/nlu/persistor.py` — `module:@6` (lines 6-6) + +```python +from typing import Optional, Text, Tuple, TYPE_CHECKING +``` + +## `rasa/utils/io.py` — `function:unarchive` (lines 84-98) + +```python +def unarchive(byte_array: bytes, directory: Text) -> Text: + """Tries to unpack a byte array interpreting it as an archive. + + Tries to use tar first to unpack, if that fails, zip will be used.""" + + try: + tar = tarfile.open(fileobj=IOReader(byte_array)) + tar.extractall(directory) + tar.close() + return directory + except tarfile.TarError: + zip_ref = zipfile.ZipFile(IOReader(byte_array)) + zip_ref.extractall(directory) + zip_ref.close() + return directory +``` + +## `rasa/utils/io.py` — `module:@6` (lines 6-6) + +```python +import tempfile +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.json new file mode 100644 index 0000000000000000000000000000000000000000..503543bc79d130c8fc5fc7eacb974f16b9780366 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.json @@ -0,0 +1,57 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-3994e3622b21c396ef8a", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-3994e3622b21c396ef8a", + "project_id": "pyvul__rasahq__rasa", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "rasa/model.py", + "rasa/nlu/persistor.py", + "rasa/utils/io.py" + ], + "patch_units": { + "before": [ + "function:unpack_model", + "class:Persistor", + "function:Persistor._decompress", + "module:@5", + "module:@6", + "function:unarchive", + "module:@6" + ], + "after": [ + "function:unpack_model", + "class:Persistor", + "function:Persistor._decompress", + "module:@5", + "function:unarchive", + "module:@6" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/c55507b377561f903462ad5cec29b5fc43df8b9f6e8a1eb5bc87da87c5348d2f/database", + "cache_key": "c55507b377561f903462ad5cec29b5fc43df8b9f6e8a1eb5bc87da87c5348d2f", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/9d2daedadeb33c7c140f4863247d20ea58e9e5a26e7947a1305e447ef40f18d3/database", + "cache_key": "9d2daedadeb33c7c140f4863247d20ea58e9e5a26e7947a1305e447ef40f18d3", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/b7688a4b944f994a4f8cdc0dc46c7126c07a3197c53b14714e52625daac53337/database", + "cache_key": "b7688a4b944f994a4f8cdc0dc46c7126c07a3197c53b14714e52625daac53337", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-3994e3622b21c396ef8a/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-3994e3622b21c396ef8a/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4d61574f8f44e58f520b35a82790a93c043aaf7b --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diff @@ -0,0 +1,80 @@ +diff --git a/PIL/EpsImagePlugin.py b/PIL/EpsImagePlugin.py +index a8706b05f..fcfae8a81 100644 +--- a/PIL/EpsImagePlugin.py ++++ b/PIL/EpsImagePlugin.py +@@ -67,7 +67,8 @@ def Ghostscript(tile, size, fp, scale=1): + + import tempfile, os, subprocess + +- file = tempfile.mktemp() ++ out_fd, file = tempfile.mkstemp() ++ os.close(out_fd) + + # Build ghostscript command + command = ["gs", +diff --git a/PIL/Image.py b/PIL/Image.py +index 87631d6f7..915f5b1df 100644 +--- a/PIL/Image.py ++++ b/PIL/Image.py +@@ -495,14 +495,17 @@ class Image: + self.readonly = 0 + + def _dump(self, file=None, format=None): +- import tempfile ++ import tempfile, os + if not file: +- file = tempfile.mktemp() ++ f, file = tempfile.mkstemp(format or '') ++ os.close(f) ++ + self.load() + if not format or format == "PPM": + self.im.save_ppm(file) + else: +- file = file + "." + format ++ if file.endswith(format): ++ file = file + "." + format + self.save(file, format) + return file + +diff --git a/PIL/IptcImagePlugin.py b/PIL/IptcImagePlugin.py +index 157b73509..104153002 100644 +--- a/PIL/IptcImagePlugin.py ++++ b/PIL/IptcImagePlugin.py +@@ -172,8 +172,8 @@ class IptcImageFile(ImageFile.ImageFile): + self.fp.seek(offset) + + # Copy image data to temporary file +- outfile = tempfile.mktemp() +- o = open(outfile, "wb") ++ o_fd, outfile = tempfile.mkstemp(text=False) ++ o = os.fdopen(o_fd) + if encoding == "raw": + # To simplify access to the extracted file, + # prepend a PPM header +diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py +index 90d3b5194..67dc5ba7d 100644 +--- a/PIL/JpegImagePlugin.py ++++ b/PIL/JpegImagePlugin.py +@@ -344,13 +344,17 @@ class JpegImageFile(ImageFile.ImageFile): + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + import tempfile, os +- file = tempfile.mktemp() +- os.system("djpeg %s >%s" % (self.filename, file)) ++ f, path = tempfile.mkstemp() ++ os.close(f) ++ if os.path.exists(self.filename): ++ os.system("djpeg '%s' >'%s'" % (self.filename, path)) ++ else: ++ raise ValueError("Invalid Filename") + + try: +- self.im = Image.core.open_ppm(file) ++ self.im = Image.core.open_ppm(path) + finally: +- try: os.unlink(file) ++ try: os.unlink(path) + except: pass + + self.mode = self.im.mode diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..330e1ac7b4982660c15fdac9b61bea7ddd1f8d3d --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.md @@ -0,0 +1,1683 @@ +# Patch-overlapping Python context after the fix + +## `PIL/EpsImagePlugin.py` — `function:Ghostscript` (lines 53-110) + +```python +def Ghostscript(tile, size, fp, scale=1): + """Render an image using Ghostscript""" + + # Unpack decoder tile + decoder, tile, offset, data = tile[0] + length, bbox = data + + #Hack to support hi-res rendering + scale = int(scale) or 1 + orig_size = size + orig_bbox = bbox + size = (size[0] * scale, size[1] * scale) + bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale] + #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox) + + import tempfile, os, subprocess + + out_fd, file = tempfile.mkstemp() + os.close(out_fd) + + # Build ghostscript command + command = ["gs", + "-q", # quite mode + "-g%dx%d" % size, # set output geometry (pixels) + "-r%d" % (72*scale), # set input DPI (dots per inch) + "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode + "-sDEVICE=ppmraw", # ppm driver + "-sOutputFile=%s" % file,# output file + ] + + if gs_windows_binary is not None: + if gs_windows_binary is False: + raise WindowsError('Unable to locate Ghostscript on paths') + command[0] = gs_windows_binary + + # push data through ghostscript + try: + gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + # adjust for image origin + if bbox[0] != 0 or bbox[1] != 0: + gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii')) + fp.seek(offset) + while length > 0: + s = fp.read(8192) + if not s: + break + length = length - len(s) + gs.stdin.write(s) + gs.stdin.close() + status = gs.wait() + if status: + raise IOError("gs failed (status %d)" % status) + im = Image.core.open_ppm(file) + finally: + try: os.unlink(file) + except: pass + + return im +``` + +## `PIL/Image.py` — `class:Image` (lines 447-1705) + +```python +class Image: + """ + This class represents an image object. To create + :py:class:`~PIL.Image.Image` objects, use the appropriate factory + functions. There's hardly ever any reason to call the Image constructor + directly. + + * :py:func:`~PIL.Image.open` + * :py:func:`~PIL.Image.new` + * :py:func:`~PIL.Image.frombytes` + """ + format = None + format_description = None + + def __init__(self): + # FIXME: take "new" parameters / other image? + # FIXME: turn mode and size into delegating properties? + self.im = None + self.mode = "" + self.size = (0, 0) + self.palette = None + self.info = {} + self.category = NORMAL + self.readonly = 0 + + def _new(self, im): + new = Image() + new.im = im + new.mode = im.mode + new.size = im.size + new.palette = self.palette + if im.mode == "P" and not new.palette: + from PIL import ImagePalette + new.palette = ImagePalette.ImagePalette() + try: + new.info = self.info.copy() + except AttributeError: + # fallback (pre-1.5.2) + new.info = {} + for k, v in self.info: + new.info[k] = v + return new + + _makeself = _new # compatibility + + def _copy(self): + self.load() + self.im = self.im.copy() + self.readonly = 0 + + def _dump(self, file=None, format=None): + import tempfile, os + if not file: + f, file = tempfile.mkstemp(format or '') + os.close(f) + + self.load() + if not format or format == "PPM": + self.im.save_ppm(file) + else: + if file.endswith(format): + file = file + "." + format + self.save(file, format) + return file + + def __repr__(self): + return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( + self.__class__.__module__, self.__class__.__name__, + self.mode, self.size[0], self.size[1], + id(self) + ) + + def __getattr__(self, name): + if name == "__array_interface__": + # numpy array interface support + new = {} + shape, typestr = _conv_type_shape(self) + new['shape'] = shape + new['typestr'] = typestr + new['data'] = self.tobytes() + return new + raise AttributeError(name) + + def tobytes(self, encoder_name="raw", *args): + """ + Return image as a bytes object + + :param encoder_name: What encoder to use. The default is to + use the standard "raw" encoder. + :param args: Extra arguments to the encoder. + :rtype: A bytes object. + """ + + # may pass tuple instead of argument list + if len(args) == 1 and isinstance(args[0], tuple): + args = args[0] + + if encoder_name == "raw" and args == (): + args = self.mode + + self.load() + + # unpack data + e = _getencoder(self.mode, encoder_name, args) + e.setimage(self.im) + + bufsize = max(65536, self.size[0] * 4) # see RawEncode.c + + data = [] + while True: + l, s, d = e.encode(bufsize) + data.append(d) + if s: + break + if s < 0: + raise RuntimeError("encoder error %d in tobytes" % s) + + return b"".join(data) + + # Declare tostring as alias to tobytes + def tostring(self, *args, **kw): + warnings.warn( + 'tostring() is deprecated. Please call tobytes() instead.', + DeprecationWarning, + stacklevel=2, + ) + return self.tobytes(*args, **kw) + + def tobitmap(self, name="image"): + """ + Returns the image converted to an X11 bitmap. + + .. note:: This method only works for mode "1" images. + + :param name: The name prefix to use for the bitmap variables. + :returns: A string containing an X11 bitmap. + :raises ValueError: If the mode is not "1" + """ + + self.load() + if self.mode != "1": + raise ValueError("not a bitmap") + data = self.tobytes("xbm") + return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'), + ("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'), + ("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"]) + + def frombytes(self, data, decoder_name="raw", *args): + """ + Loads this image with pixel data from a bytes object. + + This method is similar to the :py:func:`~PIL.Image.frombytes` function, + but loads data into this image instead of creating a new image object. + """ + + # may pass tuple instead of argument list + if len(args) == 1 and isinstance(args[0], tuple): + args = args[0] + + # default format + if decoder_name == "raw" and args == (): + args = self.mode + + # unpack data + d = _getdecoder(self.mode, decoder_name, args) + d.setimage(self.im) + s = d.decode(data) + + if s[0] >= 0: + raise ValueError("not enough image data") + if s[1] != 0: + raise ValueError("cannot decode image data") + + def fromstring(self, *args, **kw): + """Deprecated alias to frombytes. + + .. deprecated:: 2.0 + """ + warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning) + return self.frombytes(*args, **kw) + + def load(self): + """ + Allocates storage for the image and loads the pixel data. In + normal cases, you don't need to call this method, since the + Image class automatically loads an opened image when it is + accessed for the first time. + + :returns: An image access object. + """ + if self.im and self.palette and self.palette.dirty: + # realize palette + self.im.putpalette(*self.palette.getdata()) + self.palette.dirty = 0 + self.palette.mode = "RGB" + self.palette.rawmode = None + if "transparency" in self.info: + if isinstance(self.info["transparency"], int): + self.im.putpalettealpha(self.info["transparency"], 0) + else: + self.im.putpalettealphas(self.info["transparency"]) + self.palette.mode = "RGBA" + + if self.im: + return self.im.pixel_access(self.readonly) + + def verify(self): + """ + Verifies the contents of a file. For data read from a file, this + method attempts to determine if the file is broken, without + actually decoding the image data. If this method finds any + problems, it raises suitable exceptions. If you need to load + the image after using this method, you must reopen the image + file. + """ + pass + + def convert(self, mode=None, matrix=None, dither=None, + palette=WEB, colors=256): + """ + Returns a converted copy of this image. For the "P" mode, this + method translates pixels through the palette. If mode is + omitted, a mode is chosen so that all information in the image + and the palette can be represented without a palette. + + The current version supports all possible conversions between + "L", "RGB" and "CMYK." The **matrix** argument only supports "L" + and "RGB". + + When translating a color image to black and white (mode "L"), + the library uses the ITU-R 601-2 luma transform:: + + L = R * 299/1000 + G * 587/1000 + B * 114/1000 + + The default method of converting a greyscale ("L") or "RGB" + image into a bilevel (mode "1") image uses Floyd-Steinberg + dither to approximate the original image luminosity levels. If + dither is NONE, all non-zero values are set to 255 (white). To + use other thresholds, use the :py:meth:`~PIL.Image.Image.point` + method. + + :param mode: The requested mode. + :param matrix: An optional conversion matrix. If given, this + should be 4- or 16-tuple containing floating point values. + :param dither: Dithering method, used when converting from + mode "RGB" to "P" or from "RGB" or "L" to "1". + Available methods are NONE or FLOYDSTEINBERG (default). + :param palette: Palette to use when converting from mode "RGB" + to "P". Available palettes are WEB or ADAPTIVE. + :param colors: Number of colors to use for the ADAPTIVE palette. + Defaults to 256. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if not mode: + # determine default mode + if self.mode == "P": + self.load() + if self.palette: + mode = self.palette.mode + else: + mode = "RGB" + else: + return self.copy() + + self.load() + + if matrix: + # matrix conversion + if mode not in ("L", "RGB"): + raise ValueError("illegal conversion") + im = self.im.convert_matrix(mode, matrix) + return self._new(im) + + if mode == "P" and palette == ADAPTIVE: + im = self.im.quantize(colors) + return self._new(im) + + # colorspace conversion + if dither is None: + dither = FLOYDSTEINBERG + + # Use transparent conversion to promote from transparent color to an alpha channel. + if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info: + return self._new(self.im.convert_transparent(mode, self.info['transparency'])) + + try: + im = self.im.convert(mode, dither) + except ValueError: + try: + # normalize source image and try again + im = self.im.convert(getmodebase(self.mode)) + im = im.convert(mode, dither) + except KeyError: + raise ValueError("illegal conversion") + + return self._new(im) + + def quantize(self, colors=256, method=0, kmeans=0, palette=None): + + # methods: + # 0 = median cut + # 1 = maximum coverage + # 2 = fast octree + + # NOTE: this functionality will be moved to the extended + # quantizer interface in a later version of PIL. + + self.load() + + if palette: + # use palette from reference image + palette.load() + if palette.mode != "P": + raise ValueError("bad mode for palette image") + if self.mode != "RGB" and self.mode != "L": + raise ValueError( + "only RGB or L mode images can be quantized to a palette" + ) + im = self.im.convert("P", 1, palette.im) + return self._makeself(im) + + im = self.im.quantize(colors, method, kmeans) + return self._new(im) + + def copy(self): + """ + Copies this image. Use this method if you wish to paste things + into an image, but still retain the original. + + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + self.load() + im = self.im.copy() + return self._new(im) + + def crop(self, box=None): + """ + Returns a rectangular region from this image. The box is a + 4-tuple defining the left, upper, right, and lower pixel + coordinate. + + This is a lazy operation. Changes to the source image may or + may not be reflected in the cropped image. To break the + connection, call the :py:meth:`~PIL.Image.Image.load` method on + the cropped copy. + + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + if box is None: + return self.copy() + + # lazy operation + return _ImageCrop(self, box) + + def draft(self, mode, size): + """ + Configures the image file loader so it returns a version of the + image that as closely as possible matches the given mode and + size. For example, you can use this method to convert a color + JPEG to greyscale while loading it, or to extract a 128x192 + version from a PCD file. + + Note that this method modifies the :py:class:`~PIL.Image.Image` object + in place. If the image has already been loaded, this method has no + effect. + + :param mode: The requested mode. + :param size: The requested size. + """ + pass + + def _expand(self, xmargin, ymargin=None): + if ymargin is None: + ymargin = xmargin + self.load() + return self._new(self.im.expand(xmargin, ymargin, 0)) + + def filter(self, filter): + """ + Filters this image using the given filter. For a list of + available filters, see the :py:mod:`~PIL.ImageFilter` module. + + :param filter: Filter kernel. + :returns: An :py:class:`~PIL.Image.Image` object. """ + + self.load() + + if isinstance(filter, collections.Callable): + filter = filter() + if not hasattr(filter, "filter"): + raise TypeError("filter argument should be ImageFilter.Filter instance or class") + + if self.im.bands == 1: + return self._new(filter.filter(self.im)) + # fix to handle multiband images since _imaging doesn't + ims = [] + for c in range(self.im.bands): + ims.append(self._new(filter.filter(self.im.getband(c)))) + return merge(self.mode, ims) + + def getbands(self): + """ + Returns a tuple containing the name of each band in this image. + For example, **getbands** on an RGB image returns ("R", "G", "B"). + + :returns: A tuple containing band names. + :rtype: tuple + """ + return ImageMode.getmode(self.mode).bands + + def getbbox(self): + """ + Calculates the bounding box of the non-zero regions in the + image. + + :returns: The bounding box is returned as a 4-tuple defining the + left, upper, right, and lower pixel coordinate. If the image + is completely empty, this method returns None. + + """ + + self.load() + return self.im.getbbox() + + def getcolors(self, maxcolors=256): + """ + Returns a list of colors used in this image. + + :param maxcolors: Maximum number of colors. If this number is + exceeded, this method returns None. The default limit is + 256 colors. + :returns: An unsorted list of (count, pixel) values. + """ + + self.load() + if self.mode in ("1", "L", "P"): + h = self.im.histogram() + out = [] + for i in range(256): + if h[i]: + out.append((h[i], i)) + if len(out) > maxcolors: + return None + return out + return self.im.getcolors(maxcolors) + + def getdata(self, band = None): + """ + Returns the contents of this image as a sequence object + containing pixel values. The sequence object is flattened, so + that values for line one follow directly after the values of + line zero, and so on. + + Note that the sequence object returned by this method is an + internal PIL data type, which only supports certain sequence + operations. To convert it to an ordinary sequence (e.g. for + printing), use **list(im.getdata())**. + + :param band: What band to return. The default is to return + all bands. To return a single band, pass in the index + value (e.g. 0 to get the "R" band from an "RGB" image). + :returns: A sequence-like object. + """ + + self.load() + if band is not None: + return self.im.getband(band) + return self.im # could be abused + + def getextrema(self): + """ + Gets the the minimum and maximum pixel values for each band in + the image. + + :returns: For a single-band image, a 2-tuple containing the + minimum and maximum pixel value. For a multi-band image, + a tuple containing one 2-tuple for each band. + """ + + self.load() + if self.im.bands > 1: + extrema = [] + for i in range(self.im.bands): + extrema.append(self.im.getband(i).getextrema()) + return tuple(extrema) + return self.im.getextrema() + + def getim(self): + """ + Returns a capsule that points to the internal image memory. + + :returns: A capsule object. + """ + + self.load() + return self.im.ptr + + + def getpalette(self): + """ + Returns the image palette as a list. + + :returns: A list of color values [r, g, b, ...], or None if the + image has no palette. + """ + + self.load() + try: + if bytes is str: + return [i8(c) for c in self.im.getpalette()] + else: + return list(self.im.getpalette()) + except ValueError: + return None # no palette + + + def getpixel(self, xy): + """ + Returns the pixel value at a given position. + + :param xy: The coordinate, given as (x, y). + :returns: The pixel value. If the image is a multi-layer image, + this method returns a tuple. + """ + + self.load() + return self.im.getpixel(xy) + + def getprojection(self): + """ + Get projection to x and y axes + + :returns: Two sequences, indicating where there are non-zero + pixels along the X-axis and the Y-axis, respectively. + """ + + self.load() + x, y = self.im.getprojection() + return [i8(c) for c in x], [i8(c) for c in y] + + def histogram(self, mask=None, extrema=None): + """ + Returns a histogram for the image. The histogram is returned as + a list of pixel counts, one for each pixel value in the source + image. If the image has more than one band, the histograms for + all bands are concatenated (for example, the histogram for an + "RGB" image contains 768 values). + + A bilevel image (mode "1") is treated as a greyscale ("L") image + by this method. + + If a mask is provided, the method returns a histogram for those + parts of the image where the mask image is non-zero. The mask + image must have the same size as the image, and be either a + bi-level image (mode "1") or a greyscale image ("L"). + + :param mask: An optional mask. + :returns: A list containing pixel counts. + """ + self.load() + if mask: + mask.load() + return self.im.histogram((0, 0), mask.im) + if self.mode in ("I", "F"): + if extrema is None: + extrema = self.getextrema() + return self.im.histogram(extrema) + return self.im.histogram() + + def offset(self, xoffset, yoffset=None): + """ + .. deprecated:: 2.0 + + .. note:: New code should use :py:func:`PIL.ImageChops.offset`. + + Returns a copy of the image where the data has been offset by the given + distances. Data wraps around the edges. If **yoffset** is omitted, it + is assumed to be equal to **xoffset**. + + :param xoffset: The horizontal distance. + :param yoffset: The vertical distance. If omitted, both + distances are set to the same value. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + if warnings: + warnings.warn( + "'offset' is deprecated; use 'ImageChops.offset' instead", + DeprecationWarning, stacklevel=2 + ) + from PIL import ImageChops + return ImageChops.offset(self, xoffset, yoffset) + + def paste(self, im, box=None, mask=None): + """ + Pastes another image into this image. The box argument is either + a 2-tuple giving the upper left corner, a 4-tuple defining the + left, upper, right, and lower pixel coordinate, or None (same as + (0, 0)). If a 4-tuple is given, the size of the pasted image + must match the size of the region. + + If the modes don't match, the pasted image is converted to the mode of + this image (see the :py:meth:`~PIL.Image.Image.convert` method for + details). + + Instead of an image, the source can be a integer or tuple + containing pixel values. The method then fills the region + with the given color. When creating RGB images, you can + also use color strings as supported by the ImageColor module. + + If a mask is given, this method updates only the regions + indicated by the mask. You can use either "1", "L" or "RGBA" + images (in the latter case, the alpha band is used as mask). + Where the mask is 255, the given image is copied as is. Where + the mask is 0, the current value is preserved. Intermediate + values can be used for transparency effects. + + Note that if you paste an "RGBA" image, the alpha band is + ignored. You can work around this by using the same image as + both source image and mask. + + :param im: Source image or pixel value (integer or tuple). + :param box: An optional 4-tuple giving the region to paste into. + If a 2-tuple is used instead, it's treated as the upper left + corner. If omitted or None, the source is pasted into the + upper left corner. + + If an image is given as the second argument and there is no + third, the box defaults to (0, 0), and the second argument + is interpreted as a mask image. + :param mask: An optional mask image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if isImageType(box) and mask is None: + # abbreviated paste(im, mask) syntax + mask = box; box = None + + if box is None: + # cover all of self + box = (0, 0) + self.size + + if len(box) == 2: + # lower left corner given; get size from image or mask + if isImageType(im): + size = im.size + elif isImageType(mask): + size = mask.size + else: + # FIXME: use self.size here? + raise ValueError( + "cannot determine region size; use 4-item box" + ) + box = box + (box[0]+size[0], box[1]+size[1]) + + if isStringType(im): + from PIL import ImageColor + im = ImageColor.getcolor(im, self.mode) + + elif isImageType(im): + im.load() + if self.mode != im.mode: + if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): + # should use an adapter for this! + im = im.convert(self.mode) + im = im.im + + self.load() + if self.readonly: + self._copy() + + if mask: + mask.load() + self.im.paste(im, box, mask.im) + else: + self.im.paste(im, box) + + def point(self, lut, mode=None): + """ + Maps this image through a lookup table or function. + + :param lut: A lookup table, containing 256 (or 65336 if + self.mode=="I" and mode == "L") values per band in the + image. A function can be used instead, it should take a + single argument. The function is called once for each + possible pixel value, and the resulting table is applied to + all bands of the image. + :param mode: Output mode (default is same as input). In the + current version, this can only be used if the source image + has mode "L" or "P", and the output has mode "1" or the + source image mode is "I" and the output mode is "L". + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + + if isinstance(lut, ImagePointHandler): + return lut.point(self) + + if callable(lut): + # if it isn't a list, it should be a function + if self.mode in ("I", "I;16", "F"): + # check if the function can be used with point_transform + # UNDONE wiredfool -- I think this prevents us from ever doing + # a gamma function point transform on > 8bit images. + scale, offset = _getscaleoffset(lut) + return self._new(self.im.point_transform(scale, offset)) + # for other modes, convert the function to a table + lut = [lut(i) for i in range(256)] * self.im.bands + + if self.mode == "F": + # FIXME: _imaging returns a confusing error message for this case + raise ValueError("point operation not supported for this mode") + + return self._new(self.im.point(lut, mode)) + + def putalpha(self, alpha): + """ + Adds or replaces the alpha layer in this image. If the image + does not have an alpha layer, it's converted to "LA" or "RGBA". + The new layer must be either "L" or "1". + + :param alpha: The new alpha layer. This can either be an "L" or "1" + image having the same size as this image, or an integer or + other color value. + """ + + self.load() + if self.readonly: + self._copy() + + if self.mode not in ("LA", "RGBA"): + # attempt to promote self to a matching alpha mode + try: + mode = getmodebase(self.mode) + "A" + try: + self.im.setmode(mode) + except (AttributeError, ValueError): + # do things the hard way + im = self.im.convert(mode) + if im.mode not in ("LA", "RGBA"): + raise ValueError # sanity check + self.im = im + self.mode = self.im.mode + except (KeyError, ValueError): + raise ValueError("illegal image mode") + + if self.mode == "LA": + band = 1 + else: + band = 3 + + if isImageType(alpha): + # alpha layer + if alpha.mode not in ("1", "L"): + raise ValueError("illegal image mode") + alpha.load() + if alpha.mode == "1": + alpha = alpha.convert("L") + else: + # constant alpha + try: + self.im.fillband(band, alpha) + except (AttributeError, ValueError): + # do things the hard way + alpha = new("L", self.size, alpha) + else: + return + + self.im.putband(alpha.im, band) + + def putdata(self, data, scale=1.0, offset=0.0): + """ + Copies pixel data to this image. This method copies data from a + sequence object into the image, starting at the upper left + corner (0, 0), and continuing until either the image or the + sequence ends. The scale and offset values are used to adjust + the sequence values: **pixel = value*scale + offset**. + + :param data: A sequence object. + :param scale: An optional scale value. The default is 1.0. + :param offset: An optional offset value. The default is 0.0. + """ + + self.load() + if self.readonly: + self._copy() + + self.im.putdata(data, scale, offset) + + def putpalette(self, data, rawmode="RGB"): + """ + Attaches a palette to this image. The image must be a "P" or + "L" image, and the palette sequence must contain 768 integer + values, where each group of three values represent the red, + green, and blue values for the corresponding pixel + index. Instead of an integer sequence, you can use an 8-bit + string. + + :param data: A palette sequence (either a list or a string). + """ + from PIL import ImagePalette + + if self.mode not in ("L", "P"): + raise ValueError("illegal image mode") + self.load() + if isinstance(data, ImagePalette.ImagePalette): + palette = ImagePalette.raw(data.rawmode, data.palette) + else: + if not isinstance(data, bytes): + if bytes is str: + data = "".join(chr(x) for x in data) + else: + data = bytes(data) + palette = ImagePalette.raw(rawmode, data) + self.mode = "P" + self.palette = palette + self.palette.mode = "RGB" + self.load() # install new palette + + def putpixel(self, xy, value): + """ + Modifies the pixel at the given position. The color is given as + a single numerical value for single-band images, and a tuple for + multi-band images. + + Note that this method is relatively slow. For more extensive changes, + use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` + module instead. + + See: + + * :py:meth:`~PIL.Image.Image.paste` + * :py:meth:`~PIL.Image.Image.putdata` + * :py:mod:`~PIL.ImageDraw` + + :param xy: The pixel coordinate, given as (x, y). + :param value: The pixel value. + """ + + self.load() + if self.readonly: + self._copy() + + return self.im.putpixel(xy, value) + + def resize(self, size, resample=NEAREST): + """ + Returns a resized copy of this image. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param filter: An optional resampling filter. This can be + one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), + :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 + environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline + interpolation in a 4x4 environment), or + :py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter). + If omitted, or if the image has mode "1" or "P", it is + set :py:attr:`PIL.Image.NEAREST`. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS): + raise ValueError("unknown resampling filter") + + self.load() + + if self.mode in ("1", "P"): + resample = NEAREST + + if self.mode == 'RGBA': + return self.convert('RGBa').resize(size, resample).convert('RGBA') + + if resample == ANTIALIAS: + # requires stretch support (imToolkit & PIL 1.1.3) + try: + im = self.im.stretch(size, resample) + except AttributeError: + raise ValueError("unsupported resampling filter") + else: + im = self.im.resize(size, resample) + + return self._new(im) + + def rotate(self, angle, resample=NEAREST, expand=0): + """ + Returns a rotated copy of this image. This method returns a + copy of this image, rotated the given number of degrees counter + clockwise around its centre. + + :param angle: In degrees counter clockwise. + :param filter: An optional resampling filter. This can be + one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), + :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:attr:`PIL.Image.BICUBIC` + (cubic spline interpolation in a 4x4 environment). + If omitted, or if the image has mode "1" or "P", it is + set :py:attr:`PIL.Image.NEAREST`. + :param expand: Optional expansion flag. If true, expands the output + image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the + input image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if expand: + import math + angle = -angle * math.pi / 180 + matrix = [ + math.cos(angle), math.sin(angle), 0.0, + -math.sin(angle), math.cos(angle), 0.0 + ] + def transform(x, y, matrix=matrix): + (a, b, c, d, e, f) = matrix + return a*x + b*y + c, d*x + e*y + f + + # calculate output size + w, h = self.size + xx = [] + yy = [] + for x, y in ((0, 0), (w, 0), (w, h), (0, h)): + x, y = transform(x, y) + xx.append(x) + yy.append(y) + w = int(math.ceil(max(xx)) - math.floor(min(xx))) + h = int(math.ceil(max(yy)) - math.floor(min(yy))) + + # adjust center + x, y = transform(w / 2.0, h / 2.0) + matrix[2] = self.size[0] / 2.0 - x + matrix[5] = self.size[1] / 2.0 - y + + return self.transform((w, h), AFFINE, matrix, resample) + + if resample not in (NEAREST, BILINEAR, BICUBIC): + raise ValueError("unknown resampling filter") + + self.load() + + if self.mode in ("1", "P"): + resample = NEAREST + + return self._new(self.im.rotate(angle, resample)) + + def save(self, fp, format=None, **params): + """ + Saves this image under the given filename. If no format is + specified, the format to use is determined from the filename + extension, if possible. + + Keyword options can be used to provide additional instructions + to the writer. If a writer doesn't recognise an option, it is + silently ignored. The available options are described later in + this handbook. + + You can use a file object instead of a filename. In this case, + you must always specify the format. The file object must + implement the **seek**, **tell**, and **write** + methods, and be opened in binary mode. + + :param file: File name or file object. + :param format: Optional format override. If omitted, the + format to use is determined from the filename extension. + If a file object was used instead of a filename, this + parameter should always be used. + :param options: Extra parameters to the image writer. + :returns: None + :exception KeyError: If the output format could not be determined + from the file name. Use the format option to solve this. + :exception IOError: If the file could not be written. The file + may have been created, and may contain partial data. + """ + + if isPath(fp): + filename = fp + else: + if hasattr(fp, "name") and isPath(fp.name): + filename = fp.name + else: + filename = "" + + # may mutate self! + self.load() + + self.encoderinfo = params + self.encoderconfig = () + + preinit() + + ext = os.path.splitext(filename)[1].lower() + + if not format: + try: + format = EXTENSION[ext] + except KeyError: + init() + try: + format = EXTENSION[ext] + except KeyError: + raise KeyError(ext) # unknown extension + + try: + save_handler = SAVE[format.upper()] + except KeyError: + init() + save_handler = SAVE[format.upper()] # unknown format + + if isPath(fp): + fp = builtins.open(fp, "wb") + close = 1 + else: + close = 0 + + try: + save_handler(self, fp, filename) + finally: + # do what we can to clean up + if close: + fp.close() + + def seek(self, frame): + """ + Seeks to the given frame in this sequence file. If you seek + beyond the end of the sequence, the method raises an + **EOFError** exception. When a sequence file is opened, the + library automatically seeks to frame 0. + + Note that in the current version of the library, most sequence + formats only allows you to seek to the next frame. + + See :py:meth:`~PIL.Image.Image.tell`. + + :param frame: Frame number, starting at 0. + :exception EOFError: If the call attempts to seek beyond the end + of the sequence. + """ + + # overridden by file handlers + if frame != 0: + raise EOFError + + def show(self, title=None, command=None): + """ + Displays this image. This method is mainly intended for + debugging purposes. + + On Unix platforms, this method saves the image to a temporary + PPM file, and calls the **xv** utility. + + On Windows, it saves the image to a temporary BMP file, and uses + the standard BMP display utility to show it (usually Paint). + + :param title: Optional title to use for the image window, + where possible. + :param command: command used to show the image + """ + + _show(self, title=title, command=command) + + def split(self): + """ + Split this image into individual bands. This method returns a + tuple of individual image bands from an image. For example, + splitting an "RGB" image creates three new images each + containing a copy of one of the original bands (red, green, + blue). + + :returns: A tuple containing bands. + """ + + self.load() + if self.im.bands == 1: + ims = [self.copy()] + else: + ims = [] + for i in range(self.im.bands): + ims.append(self._new(self.im.getband(i))) + return tuple(ims) + + def tell(self): + """ + Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. + + :returns: Frame number, starting with 0. + """ + return 0 + + def thumbnail(self, size, resample=NEAREST): + """ + Make this image into a thumbnail. This method modifies the + image to contain a thumbnail version of itself, no larger than + the given size. This method calculates an appropriate thumbnail + size to preserve the aspect of the image, calls the + :py:meth:`~PIL.Image.Image.draft` method to configure the file reader + (where applicable), and finally resizes the image. + + Note that the bilinear and bicubic filters in the current + version of PIL are not well-suited for thumbnail generation. + You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more + important than quality. + + Also note that this function modifies the :py:class:`~PIL.Image.Image` + object in place. If you need to use the full resolution image as well, apply + this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. + + :param size: Requested size. + :param resample: Optional resampling filter. This can be one + of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`, + :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS` + (best quality). If omitted, it defaults to + :py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a + future version). + :returns: None + """ + + # FIXME: the default resampling filter will be changed + # to ANTIALIAS in future versions + + # preserve aspect ratio + x, y = self.size + if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0]) + if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1]) + size = x, y + + if size == self.size: + return + + self.draft(None, size) + + self.load() + + try: + im = self.resize(size, resample) + except ValueError: + if resample != ANTIALIAS: + raise + im = self.resize(size, NEAREST) # fallback + + self.im = im.im + self.mode = im.mode + self.size = size + + self.readonly = 0 + + # FIXME: the different tranform methods need further explanation + # instead of bloating the method docs, add a separate chapter. + def transform(self, size, method, data=None, resample=NEAREST, fill=1): + """ + Transforms this image. This method creates a new image with the + given size, and the same mode as the original, and copies data + to the new image using the given transform. + + :param size: The output size. + :param method: The transformation method. This is one of + :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion), + :py:attr:`PIL.Image.AFFINE` (affine transform), + :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform), + :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or + :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals + in one operation). + :param data: Extra data to the transformation method. + :param resample: Optional resampling filter. It can be one of + :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), + :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline + interpolation in a 4x4 environment). If omitted, or if the image + has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if self.mode == 'RGBA': + return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA') + + if isinstance(method, ImageTransformHandler): + return method.transform(size, self, resample=resample, fill=fill) + if hasattr(method, "getdata"): + # compatibility w. old-style transform objects + method, data = method.getdata() + if data is None: + raise ValueError("missing method data") + + im = new(self.mode, size, None) + if method == MESH: + # list of quads + for box, quad in data: + im.__transformer(box, self, QUAD, quad, resample, fill) + else: + im.__transformer((0, 0)+size, self, method, data, resample, fill) + + return im + + def __transformer(self, box, image, method, data, + resample=NEAREST, fill=1): + + # FIXME: this should be turned into a lazy operation (?) + + w = box[2]-box[0] + h = box[3]-box[1] + + if method == AFFINE: + # change argument order to match implementation + data = (data[2], data[0], data[1], + data[5], data[3], data[4]) + elif method == EXTENT: + # convert extent to an affine transform + x0, y0, x1, y1 = data + xs = float(x1 - x0) / w + ys = float(y1 - y0) / h + method = AFFINE + data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys) + elif method == PERSPECTIVE: + # change argument order to match implementation + data = (data[2], data[0], data[1], + data[5], data[3], data[4], + data[6], data[7]) + elif method == QUAD: + # quadrilateral warp. data specifies the four corners + # given as NW, SW, SE, and NE. + nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8] + x0, y0 = nw; As = 1.0 / w; At = 1.0 / h + data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At, + (se[0]-sw[0]-ne[0]+x0)*As*At, + y0, (ne[1]-y0)*As, (sw[1]-y0)*At, + (se[1]-sw[1]-ne[1]+y0)*As*At) + else: + raise ValueError("unknown transformation method") + + if resample not in (NEAREST, BILINEAR, BICUBIC): + raise ValueError("unknown resampling filter") + + image.load() + + self.load() + + if image.mode in ("1", "P"): + resample = NEAREST + + self.im.transform2(box, image.im, method, data, resample, fill) + + def transpose(self, method): + """ + Transpose image (flip or rotate in 90 degree steps) + + :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, + :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, + :py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`. + :returns: Returns a flipped or rotated copy of this image. + """ + + self.load() + im = self.im.transpose(method) + return self._new(im) +``` + +## `PIL/Image.py` — `function:Image._dump` (lines 497-510) + +```python + def _dump(self, file=None, format=None): + import tempfile, os + if not file: + f, file = tempfile.mkstemp(format or '') + os.close(f) + + self.load() + if not format or format == "PPM": + self.im.save_ppm(file) + else: + if file.endswith(format): + file = file + "." + format + self.save(file, format) + return file +``` + +## `PIL/IptcImagePlugin.py` — `class:IptcImageFile` (lines 53-204) + +```python +class IptcImageFile(ImageFile.ImageFile): + + format = "IPTC" + format_description = "IPTC/NAA" + + def getint(self, key): + return i(self.info[key]) + + def field(self): + # + # get a IPTC field header + s = self.fp.read(5) + if not len(s): + return None, 0 + + tag = i8(s[1]), i8(s[2]) + + # syntax + if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9: + raise SyntaxError("invalid IPTC/NAA file") + + # field size + size = i8(s[3]) + if size > 132: + raise IOError("illegal field length in IPTC/NAA file") + elif size == 128: + size = 0 + elif size > 128: + size = i(self.fp.read(size-128)) + else: + size = i16(s[3:]) + + return tag, size + + def _is_raw(self, offset, size): + # + # check if the file can be mapped + + # DISABLED: the following only slows things down... + return 0 + + self.fp.seek(offset) + t, sz = self.field() + if sz != size[0]: + return 0 + y = 1 + while True: + self.fp.seek(sz, 1) + t, s = self.field() + if t != (8, 10): + break + if s != sz: + return 0 + y = y + 1 + return y == size[1] + + def _open(self): + + # load descriptive fields + while True: + offset = self.fp.tell() + tag, size = self.field() + if not tag or tag == (8,10): + break + if size: + tagdata = self.fp.read(size) + else: + tagdata = None + if tag in list(self.info.keys()): + if isinstance(self.info[tag], list): + self.info[tag].append(tagdata) + else: + self.info[tag] = [self.info[tag], tagdata] + else: + self.info[tag] = tagdata + + # print tag, self.info[tag] + + # mode + layers = i8(self.info[(3,60)][0]) + component = i8(self.info[(3,60)][1]) + if (3,65) in self.info: + id = i8(self.info[(3,65)][0])-1 + else: + id = 0 + if layers == 1 and not component: + self.mode = "L" + elif layers == 3 and component: + self.mode = "RGB"[id] + elif layers == 4 and component: + self.mode = "CMYK"[id] + + # size + self.size = self.getint((3,20)), self.getint((3,30)) + + # compression + try: + compression = COMPRESSION[self.getint((3,120))] + except KeyError: + raise IOError("Unknown IPTC image compression") + + # tile + if tag == (8,10): + if compression == "raw" and self._is_raw(offset, self.size): + self.tile = [(compression, (offset, size + 5, -1), + (0, 0, self.size[0], self.size[1]))] + else: + self.tile = [("iptc", (compression, offset), + (0, 0, self.size[0], self.size[1]))] + + def load(self): + + if len(self.tile) != 1 or self.tile[0][0] != "iptc": + return ImageFile.ImageFile.load(self) + + type, tile, box = self.tile[0] + + encoding, offset = tile + + self.fp.seek(offset) + + # Copy image data to temporary file + o_fd, outfile = tempfile.mkstemp(text=False) + o = os.fdopen(o_fd) + if encoding == "raw": + # To simplify access to the extracted file, + # prepend a PPM header + o.write("P5\n%d %d\n255\n" % self.size) + while True: + type, size = self.field() + if type != (8, 10): + break + while size > 0: + s = self.fp.read(min(size, 8192)) + if not s: + break + o.write(s) + size = size - len(s) + o.close() + + try: + try: + # fast + self.im = Image.core.open_ppm(outfile) + except: + # slightly slower + im = Image.open(outfile) + im.load() + self.im = im.im + finally: + try: os.unlink(outfile) + except: pass +``` + +## `PIL/IptcImagePlugin.py` — `function:IptcImageFile.load` (lines 163-204) + +```python + def load(self): + + if len(self.tile) != 1 or self.tile[0][0] != "iptc": + return ImageFile.ImageFile.load(self) + + type, tile, box = self.tile[0] + + encoding, offset = tile + + self.fp.seek(offset) + + # Copy image data to temporary file + o_fd, outfile = tempfile.mkstemp(text=False) + o = os.fdopen(o_fd) + if encoding == "raw": + # To simplify access to the extracted file, + # prepend a PPM header + o.write("P5\n%d %d\n255\n" % self.size) + while True: + type, size = self.field() + if type != (8, 10): + break + while size > 0: + s = self.fp.read(min(size, 8192)) + if not s: + break + o.write(s) + size = size - len(s) + o.close() + + try: + try: + # fast + self.im = Image.core.open_ppm(outfile) + except: + # slightly slower + im = Image.open(outfile) + im.load() + self.im = im.im + finally: + try: os.unlink(outfile) + except: pass +``` + +## `PIL/JpegImagePlugin.py` — `class:JpegImageFile` (lines 267-366) + +```python +class JpegImageFile(ImageFile.ImageFile): + + format = "JPEG" + format_description = "JPEG (ISO 10918)" + + def _open(self): + + s = self.fp.read(1) + + if i8(s[0]) != 255: + raise SyntaxError("not a JPEG file") + + # Create attributes + self.bits = self.layers = 0 + + # JPEG specifics (internal) + self.layer = [] + self.huffman_dc = {} + self.huffman_ac = {} + self.quantization = {} + self.app = {} # compatibility + self.applist = [] + self.icclist = [] + + while True: + + s = s + self.fp.read(1) + + i = i16(s) + + if i in MARKER: + name, description, handler = MARKER[i] + # print hex(i), name, description + if handler is not None: + handler(self, i) + if i == 0xFFDA: # start of scan + rawmode = self.mode + if self.mode == "CMYK": + rawmode = "CMYK;I" # assume adobe conventions + self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))] + # self.__offset = self.fp.tell() + break + s = self.fp.read(1) + elif i == 0 or i == 65535: + # padded marker or junk; move on + s = "\xff" + else: + raise SyntaxError("no marker found") + + def draft(self, mode, size): + + if len(self.tile) != 1: + return + + d, e, o, a = self.tile[0] + scale = 0 + + if a[0] == "RGB" and mode in ["L", "YCbCr"]: + self.mode = mode + a = mode, "" + + if size: + scale = max(self.size[0] // size[0], self.size[1] // size[1]) + for s in [8, 4, 2, 1]: + if scale >= s: + break + e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1] + self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s) + scale = s + + self.tile = [(d, e, o, a)] + self.decoderconfig = (scale, 1) + + return self + + def load_djpeg(self): + + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + import tempfile, os + f, path = tempfile.mkstemp() + os.close(f) + if os.path.exists(self.filename): + os.system("djpeg '%s' >'%s'" % (self.filename, path)) + else: + raise ValueError("Invalid Filename") + + try: + self.im = Image.core.open_ppm(path) + finally: + try: os.unlink(path) + except: pass + + self.mode = self.im.mode + self.size = self.im.size + + self.tile = [] + + def _getexif(self): + return _getexif(self) +``` + +## `PIL/JpegImagePlugin.py` — `function:JpegImageFile.load_djpeg` (lines 342-363) + +```python + def load_djpeg(self): + + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + import tempfile, os + f, path = tempfile.mkstemp() + os.close(f) + if os.path.exists(self.filename): + os.system("djpeg '%s' >'%s'" % (self.filename, path)) + else: + raise ValueError("Invalid Filename") + + try: + self.im = Image.core.open_ppm(path) + finally: + try: os.unlink(path) + except: pass + + self.mode = self.im.mode + self.size = self.im.size + + self.tile = [] +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..75f80ba0505e6e49271f1036dd8a96bbfa6bd6a3 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.md @@ -0,0 +1,1668 @@ +# Patch-overlapping Python context before the fix + +## `PIL/EpsImagePlugin.py` — `function:Ghostscript` (lines 53-109) + +```python +def Ghostscript(tile, size, fp, scale=1): + """Render an image using Ghostscript""" + + # Unpack decoder tile + decoder, tile, offset, data = tile[0] + length, bbox = data + + #Hack to support hi-res rendering + scale = int(scale) or 1 + orig_size = size + orig_bbox = bbox + size = (size[0] * scale, size[1] * scale) + bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale] + #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox) + + import tempfile, os, subprocess + + file = tempfile.mktemp() + + # Build ghostscript command + command = ["gs", + "-q", # quite mode + "-g%dx%d" % size, # set output geometry (pixels) + "-r%d" % (72*scale), # set input DPI (dots per inch) + "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode + "-sDEVICE=ppmraw", # ppm driver + "-sOutputFile=%s" % file,# output file + ] + + if gs_windows_binary is not None: + if gs_windows_binary is False: + raise WindowsError('Unable to locate Ghostscript on paths') + command[0] = gs_windows_binary + + # push data through ghostscript + try: + gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + # adjust for image origin + if bbox[0] != 0 or bbox[1] != 0: + gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii')) + fp.seek(offset) + while length > 0: + s = fp.read(8192) + if not s: + break + length = length - len(s) + gs.stdin.write(s) + gs.stdin.close() + status = gs.wait() + if status: + raise IOError("gs failed (status %d)" % status) + im = Image.core.open_ppm(file) + finally: + try: os.unlink(file) + except: pass + + return im +``` + +## `PIL/Image.py` — `class:Image` (lines 447-1702) + +```python +class Image: + """ + This class represents an image object. To create + :py:class:`~PIL.Image.Image` objects, use the appropriate factory + functions. There's hardly ever any reason to call the Image constructor + directly. + + * :py:func:`~PIL.Image.open` + * :py:func:`~PIL.Image.new` + * :py:func:`~PIL.Image.frombytes` + """ + format = None + format_description = None + + def __init__(self): + # FIXME: take "new" parameters / other image? + # FIXME: turn mode and size into delegating properties? + self.im = None + self.mode = "" + self.size = (0, 0) + self.palette = None + self.info = {} + self.category = NORMAL + self.readonly = 0 + + def _new(self, im): + new = Image() + new.im = im + new.mode = im.mode + new.size = im.size + new.palette = self.palette + if im.mode == "P" and not new.palette: + from PIL import ImagePalette + new.palette = ImagePalette.ImagePalette() + try: + new.info = self.info.copy() + except AttributeError: + # fallback (pre-1.5.2) + new.info = {} + for k, v in self.info: + new.info[k] = v + return new + + _makeself = _new # compatibility + + def _copy(self): + self.load() + self.im = self.im.copy() + self.readonly = 0 + + def _dump(self, file=None, format=None): + import tempfile + if not file: + file = tempfile.mktemp() + self.load() + if not format or format == "PPM": + self.im.save_ppm(file) + else: + file = file + "." + format + self.save(file, format) + return file + + def __repr__(self): + return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( + self.__class__.__module__, self.__class__.__name__, + self.mode, self.size[0], self.size[1], + id(self) + ) + + def __getattr__(self, name): + if name == "__array_interface__": + # numpy array interface support + new = {} + shape, typestr = _conv_type_shape(self) + new['shape'] = shape + new['typestr'] = typestr + new['data'] = self.tobytes() + return new + raise AttributeError(name) + + def tobytes(self, encoder_name="raw", *args): + """ + Return image as a bytes object + + :param encoder_name: What encoder to use. The default is to + use the standard "raw" encoder. + :param args: Extra arguments to the encoder. + :rtype: A bytes object. + """ + + # may pass tuple instead of argument list + if len(args) == 1 and isinstance(args[0], tuple): + args = args[0] + + if encoder_name == "raw" and args == (): + args = self.mode + + self.load() + + # unpack data + e = _getencoder(self.mode, encoder_name, args) + e.setimage(self.im) + + bufsize = max(65536, self.size[0] * 4) # see RawEncode.c + + data = [] + while True: + l, s, d = e.encode(bufsize) + data.append(d) + if s: + break + if s < 0: + raise RuntimeError("encoder error %d in tobytes" % s) + + return b"".join(data) + + # Declare tostring as alias to tobytes + def tostring(self, *args, **kw): + warnings.warn( + 'tostring() is deprecated. Please call tobytes() instead.', + DeprecationWarning, + stacklevel=2, + ) + return self.tobytes(*args, **kw) + + def tobitmap(self, name="image"): + """ + Returns the image converted to an X11 bitmap. + + .. note:: This method only works for mode "1" images. + + :param name: The name prefix to use for the bitmap variables. + :returns: A string containing an X11 bitmap. + :raises ValueError: If the mode is not "1" + """ + + self.load() + if self.mode != "1": + raise ValueError("not a bitmap") + data = self.tobytes("xbm") + return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'), + ("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'), + ("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"]) + + def frombytes(self, data, decoder_name="raw", *args): + """ + Loads this image with pixel data from a bytes object. + + This method is similar to the :py:func:`~PIL.Image.frombytes` function, + but loads data into this image instead of creating a new image object. + """ + + # may pass tuple instead of argument list + if len(args) == 1 and isinstance(args[0], tuple): + args = args[0] + + # default format + if decoder_name == "raw" and args == (): + args = self.mode + + # unpack data + d = _getdecoder(self.mode, decoder_name, args) + d.setimage(self.im) + s = d.decode(data) + + if s[0] >= 0: + raise ValueError("not enough image data") + if s[1] != 0: + raise ValueError("cannot decode image data") + + def fromstring(self, *args, **kw): + """Deprecated alias to frombytes. + + .. deprecated:: 2.0 + """ + warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning) + return self.frombytes(*args, **kw) + + def load(self): + """ + Allocates storage for the image and loads the pixel data. In + normal cases, you don't need to call this method, since the + Image class automatically loads an opened image when it is + accessed for the first time. + + :returns: An image access object. + """ + if self.im and self.palette and self.palette.dirty: + # realize palette + self.im.putpalette(*self.palette.getdata()) + self.palette.dirty = 0 + self.palette.mode = "RGB" + self.palette.rawmode = None + if "transparency" in self.info: + if isinstance(self.info["transparency"], int): + self.im.putpalettealpha(self.info["transparency"], 0) + else: + self.im.putpalettealphas(self.info["transparency"]) + self.palette.mode = "RGBA" + + if self.im: + return self.im.pixel_access(self.readonly) + + def verify(self): + """ + Verifies the contents of a file. For data read from a file, this + method attempts to determine if the file is broken, without + actually decoding the image data. If this method finds any + problems, it raises suitable exceptions. If you need to load + the image after using this method, you must reopen the image + file. + """ + pass + + def convert(self, mode=None, matrix=None, dither=None, + palette=WEB, colors=256): + """ + Returns a converted copy of this image. For the "P" mode, this + method translates pixels through the palette. If mode is + omitted, a mode is chosen so that all information in the image + and the palette can be represented without a palette. + + The current version supports all possible conversions between + "L", "RGB" and "CMYK." The **matrix** argument only supports "L" + and "RGB". + + When translating a color image to black and white (mode "L"), + the library uses the ITU-R 601-2 luma transform:: + + L = R * 299/1000 + G * 587/1000 + B * 114/1000 + + The default method of converting a greyscale ("L") or "RGB" + image into a bilevel (mode "1") image uses Floyd-Steinberg + dither to approximate the original image luminosity levels. If + dither is NONE, all non-zero values are set to 255 (white). To + use other thresholds, use the :py:meth:`~PIL.Image.Image.point` + method. + + :param mode: The requested mode. + :param matrix: An optional conversion matrix. If given, this + should be 4- or 16-tuple containing floating point values. + :param dither: Dithering method, used when converting from + mode "RGB" to "P" or from "RGB" or "L" to "1". + Available methods are NONE or FLOYDSTEINBERG (default). + :param palette: Palette to use when converting from mode "RGB" + to "P". Available palettes are WEB or ADAPTIVE. + :param colors: Number of colors to use for the ADAPTIVE palette. + Defaults to 256. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if not mode: + # determine default mode + if self.mode == "P": + self.load() + if self.palette: + mode = self.palette.mode + else: + mode = "RGB" + else: + return self.copy() + + self.load() + + if matrix: + # matrix conversion + if mode not in ("L", "RGB"): + raise ValueError("illegal conversion") + im = self.im.convert_matrix(mode, matrix) + return self._new(im) + + if mode == "P" and palette == ADAPTIVE: + im = self.im.quantize(colors) + return self._new(im) + + # colorspace conversion + if dither is None: + dither = FLOYDSTEINBERG + + # Use transparent conversion to promote from transparent color to an alpha channel. + if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info: + return self._new(self.im.convert_transparent(mode, self.info['transparency'])) + + try: + im = self.im.convert(mode, dither) + except ValueError: + try: + # normalize source image and try again + im = self.im.convert(getmodebase(self.mode)) + im = im.convert(mode, dither) + except KeyError: + raise ValueError("illegal conversion") + + return self._new(im) + + def quantize(self, colors=256, method=0, kmeans=0, palette=None): + + # methods: + # 0 = median cut + # 1 = maximum coverage + # 2 = fast octree + + # NOTE: this functionality will be moved to the extended + # quantizer interface in a later version of PIL. + + self.load() + + if palette: + # use palette from reference image + palette.load() + if palette.mode != "P": + raise ValueError("bad mode for palette image") + if self.mode != "RGB" and self.mode != "L": + raise ValueError( + "only RGB or L mode images can be quantized to a palette" + ) + im = self.im.convert("P", 1, palette.im) + return self._makeself(im) + + im = self.im.quantize(colors, method, kmeans) + return self._new(im) + + def copy(self): + """ + Copies this image. Use this method if you wish to paste things + into an image, but still retain the original. + + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + self.load() + im = self.im.copy() + return self._new(im) + + def crop(self, box=None): + """ + Returns a rectangular region from this image. The box is a + 4-tuple defining the left, upper, right, and lower pixel + coordinate. + + This is a lazy operation. Changes to the source image may or + may not be reflected in the cropped image. To break the + connection, call the :py:meth:`~PIL.Image.Image.load` method on + the cropped copy. + + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + if box is None: + return self.copy() + + # lazy operation + return _ImageCrop(self, box) + + def draft(self, mode, size): + """ + Configures the image file loader so it returns a version of the + image that as closely as possible matches the given mode and + size. For example, you can use this method to convert a color + JPEG to greyscale while loading it, or to extract a 128x192 + version from a PCD file. + + Note that this method modifies the :py:class:`~PIL.Image.Image` object + in place. If the image has already been loaded, this method has no + effect. + + :param mode: The requested mode. + :param size: The requested size. + """ + pass + + def _expand(self, xmargin, ymargin=None): + if ymargin is None: + ymargin = xmargin + self.load() + return self._new(self.im.expand(xmargin, ymargin, 0)) + + def filter(self, filter): + """ + Filters this image using the given filter. For a list of + available filters, see the :py:mod:`~PIL.ImageFilter` module. + + :param filter: Filter kernel. + :returns: An :py:class:`~PIL.Image.Image` object. """ + + self.load() + + if isinstance(filter, collections.Callable): + filter = filter() + if not hasattr(filter, "filter"): + raise TypeError("filter argument should be ImageFilter.Filter instance or class") + + if self.im.bands == 1: + return self._new(filter.filter(self.im)) + # fix to handle multiband images since _imaging doesn't + ims = [] + for c in range(self.im.bands): + ims.append(self._new(filter.filter(self.im.getband(c)))) + return merge(self.mode, ims) + + def getbands(self): + """ + Returns a tuple containing the name of each band in this image. + For example, **getbands** on an RGB image returns ("R", "G", "B"). + + :returns: A tuple containing band names. + :rtype: tuple + """ + return ImageMode.getmode(self.mode).bands + + def getbbox(self): + """ + Calculates the bounding box of the non-zero regions in the + image. + + :returns: The bounding box is returned as a 4-tuple defining the + left, upper, right, and lower pixel coordinate. If the image + is completely empty, this method returns None. + + """ + + self.load() + return self.im.getbbox() + + def getcolors(self, maxcolors=256): + """ + Returns a list of colors used in this image. + + :param maxcolors: Maximum number of colors. If this number is + exceeded, this method returns None. The default limit is + 256 colors. + :returns: An unsorted list of (count, pixel) values. + """ + + self.load() + if self.mode in ("1", "L", "P"): + h = self.im.histogram() + out = [] + for i in range(256): + if h[i]: + out.append((h[i], i)) + if len(out) > maxcolors: + return None + return out + return self.im.getcolors(maxcolors) + + def getdata(self, band = None): + """ + Returns the contents of this image as a sequence object + containing pixel values. The sequence object is flattened, so + that values for line one follow directly after the values of + line zero, and so on. + + Note that the sequence object returned by this method is an + internal PIL data type, which only supports certain sequence + operations. To convert it to an ordinary sequence (e.g. for + printing), use **list(im.getdata())**. + + :param band: What band to return. The default is to return + all bands. To return a single band, pass in the index + value (e.g. 0 to get the "R" band from an "RGB" image). + :returns: A sequence-like object. + """ + + self.load() + if band is not None: + return self.im.getband(band) + return self.im # could be abused + + def getextrema(self): + """ + Gets the the minimum and maximum pixel values for each band in + the image. + + :returns: For a single-band image, a 2-tuple containing the + minimum and maximum pixel value. For a multi-band image, + a tuple containing one 2-tuple for each band. + """ + + self.load() + if self.im.bands > 1: + extrema = [] + for i in range(self.im.bands): + extrema.append(self.im.getband(i).getextrema()) + return tuple(extrema) + return self.im.getextrema() + + def getim(self): + """ + Returns a capsule that points to the internal image memory. + + :returns: A capsule object. + """ + + self.load() + return self.im.ptr + + + def getpalette(self): + """ + Returns the image palette as a list. + + :returns: A list of color values [r, g, b, ...], or None if the + image has no palette. + """ + + self.load() + try: + if bytes is str: + return [i8(c) for c in self.im.getpalette()] + else: + return list(self.im.getpalette()) + except ValueError: + return None # no palette + + + def getpixel(self, xy): + """ + Returns the pixel value at a given position. + + :param xy: The coordinate, given as (x, y). + :returns: The pixel value. If the image is a multi-layer image, + this method returns a tuple. + """ + + self.load() + return self.im.getpixel(xy) + + def getprojection(self): + """ + Get projection to x and y axes + + :returns: Two sequences, indicating where there are non-zero + pixels along the X-axis and the Y-axis, respectively. + """ + + self.load() + x, y = self.im.getprojection() + return [i8(c) for c in x], [i8(c) for c in y] + + def histogram(self, mask=None, extrema=None): + """ + Returns a histogram for the image. The histogram is returned as + a list of pixel counts, one for each pixel value in the source + image. If the image has more than one band, the histograms for + all bands are concatenated (for example, the histogram for an + "RGB" image contains 768 values). + + A bilevel image (mode "1") is treated as a greyscale ("L") image + by this method. + + If a mask is provided, the method returns a histogram for those + parts of the image where the mask image is non-zero. The mask + image must have the same size as the image, and be either a + bi-level image (mode "1") or a greyscale image ("L"). + + :param mask: An optional mask. + :returns: A list containing pixel counts. + """ + self.load() + if mask: + mask.load() + return self.im.histogram((0, 0), mask.im) + if self.mode in ("I", "F"): + if extrema is None: + extrema = self.getextrema() + return self.im.histogram(extrema) + return self.im.histogram() + + def offset(self, xoffset, yoffset=None): + """ + .. deprecated:: 2.0 + + .. note:: New code should use :py:func:`PIL.ImageChops.offset`. + + Returns a copy of the image where the data has been offset by the given + distances. Data wraps around the edges. If **yoffset** is omitted, it + is assumed to be equal to **xoffset**. + + :param xoffset: The horizontal distance. + :param yoffset: The vertical distance. If omitted, both + distances are set to the same value. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + if warnings: + warnings.warn( + "'offset' is deprecated; use 'ImageChops.offset' instead", + DeprecationWarning, stacklevel=2 + ) + from PIL import ImageChops + return ImageChops.offset(self, xoffset, yoffset) + + def paste(self, im, box=None, mask=None): + """ + Pastes another image into this image. The box argument is either + a 2-tuple giving the upper left corner, a 4-tuple defining the + left, upper, right, and lower pixel coordinate, or None (same as + (0, 0)). If a 4-tuple is given, the size of the pasted image + must match the size of the region. + + If the modes don't match, the pasted image is converted to the mode of + this image (see the :py:meth:`~PIL.Image.Image.convert` method for + details). + + Instead of an image, the source can be a integer or tuple + containing pixel values. The method then fills the region + with the given color. When creating RGB images, you can + also use color strings as supported by the ImageColor module. + + If a mask is given, this method updates only the regions + indicated by the mask. You can use either "1", "L" or "RGBA" + images (in the latter case, the alpha band is used as mask). + Where the mask is 255, the given image is copied as is. Where + the mask is 0, the current value is preserved. Intermediate + values can be used for transparency effects. + + Note that if you paste an "RGBA" image, the alpha band is + ignored. You can work around this by using the same image as + both source image and mask. + + :param im: Source image or pixel value (integer or tuple). + :param box: An optional 4-tuple giving the region to paste into. + If a 2-tuple is used instead, it's treated as the upper left + corner. If omitted or None, the source is pasted into the + upper left corner. + + If an image is given as the second argument and there is no + third, the box defaults to (0, 0), and the second argument + is interpreted as a mask image. + :param mask: An optional mask image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if isImageType(box) and mask is None: + # abbreviated paste(im, mask) syntax + mask = box; box = None + + if box is None: + # cover all of self + box = (0, 0) + self.size + + if len(box) == 2: + # lower left corner given; get size from image or mask + if isImageType(im): + size = im.size + elif isImageType(mask): + size = mask.size + else: + # FIXME: use self.size here? + raise ValueError( + "cannot determine region size; use 4-item box" + ) + box = box + (box[0]+size[0], box[1]+size[1]) + + if isStringType(im): + from PIL import ImageColor + im = ImageColor.getcolor(im, self.mode) + + elif isImageType(im): + im.load() + if self.mode != im.mode: + if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): + # should use an adapter for this! + im = im.convert(self.mode) + im = im.im + + self.load() + if self.readonly: + self._copy() + + if mask: + mask.load() + self.im.paste(im, box, mask.im) + else: + self.im.paste(im, box) + + def point(self, lut, mode=None): + """ + Maps this image through a lookup table or function. + + :param lut: A lookup table, containing 256 (or 65336 if + self.mode=="I" and mode == "L") values per band in the + image. A function can be used instead, it should take a + single argument. The function is called once for each + possible pixel value, and the resulting table is applied to + all bands of the image. + :param mode: Output mode (default is same as input). In the + current version, this can only be used if the source image + has mode "L" or "P", and the output has mode "1" or the + source image mode is "I" and the output mode is "L". + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + + if isinstance(lut, ImagePointHandler): + return lut.point(self) + + if callable(lut): + # if it isn't a list, it should be a function + if self.mode in ("I", "I;16", "F"): + # check if the function can be used with point_transform + # UNDONE wiredfool -- I think this prevents us from ever doing + # a gamma function point transform on > 8bit images. + scale, offset = _getscaleoffset(lut) + return self._new(self.im.point_transform(scale, offset)) + # for other modes, convert the function to a table + lut = [lut(i) for i in range(256)] * self.im.bands + + if self.mode == "F": + # FIXME: _imaging returns a confusing error message for this case + raise ValueError("point operation not supported for this mode") + + return self._new(self.im.point(lut, mode)) + + def putalpha(self, alpha): + """ + Adds or replaces the alpha layer in this image. If the image + does not have an alpha layer, it's converted to "LA" or "RGBA". + The new layer must be either "L" or "1". + + :param alpha: The new alpha layer. This can either be an "L" or "1" + image having the same size as this image, or an integer or + other color value. + """ + + self.load() + if self.readonly: + self._copy() + + if self.mode not in ("LA", "RGBA"): + # attempt to promote self to a matching alpha mode + try: + mode = getmodebase(self.mode) + "A" + try: + self.im.setmode(mode) + except (AttributeError, ValueError): + # do things the hard way + im = self.im.convert(mode) + if im.mode not in ("LA", "RGBA"): + raise ValueError # sanity check + self.im = im + self.mode = self.im.mode + except (KeyError, ValueError): + raise ValueError("illegal image mode") + + if self.mode == "LA": + band = 1 + else: + band = 3 + + if isImageType(alpha): + # alpha layer + if alpha.mode not in ("1", "L"): + raise ValueError("illegal image mode") + alpha.load() + if alpha.mode == "1": + alpha = alpha.convert("L") + else: + # constant alpha + try: + self.im.fillband(band, alpha) + except (AttributeError, ValueError): + # do things the hard way + alpha = new("L", self.size, alpha) + else: + return + + self.im.putband(alpha.im, band) + + def putdata(self, data, scale=1.0, offset=0.0): + """ + Copies pixel data to this image. This method copies data from a + sequence object into the image, starting at the upper left + corner (0, 0), and continuing until either the image or the + sequence ends. The scale and offset values are used to adjust + the sequence values: **pixel = value*scale + offset**. + + :param data: A sequence object. + :param scale: An optional scale value. The default is 1.0. + :param offset: An optional offset value. The default is 0.0. + """ + + self.load() + if self.readonly: + self._copy() + + self.im.putdata(data, scale, offset) + + def putpalette(self, data, rawmode="RGB"): + """ + Attaches a palette to this image. The image must be a "P" or + "L" image, and the palette sequence must contain 768 integer + values, where each group of three values represent the red, + green, and blue values for the corresponding pixel + index. Instead of an integer sequence, you can use an 8-bit + string. + + :param data: A palette sequence (either a list or a string). + """ + from PIL import ImagePalette + + if self.mode not in ("L", "P"): + raise ValueError("illegal image mode") + self.load() + if isinstance(data, ImagePalette.ImagePalette): + palette = ImagePalette.raw(data.rawmode, data.palette) + else: + if not isinstance(data, bytes): + if bytes is str: + data = "".join(chr(x) for x in data) + else: + data = bytes(data) + palette = ImagePalette.raw(rawmode, data) + self.mode = "P" + self.palette = palette + self.palette.mode = "RGB" + self.load() # install new palette + + def putpixel(self, xy, value): + """ + Modifies the pixel at the given position. The color is given as + a single numerical value for single-band images, and a tuple for + multi-band images. + + Note that this method is relatively slow. For more extensive changes, + use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` + module instead. + + See: + + * :py:meth:`~PIL.Image.Image.paste` + * :py:meth:`~PIL.Image.Image.putdata` + * :py:mod:`~PIL.ImageDraw` + + :param xy: The pixel coordinate, given as (x, y). + :param value: The pixel value. + """ + + self.load() + if self.readonly: + self._copy() + + return self.im.putpixel(xy, value) + + def resize(self, size, resample=NEAREST): + """ + Returns a resized copy of this image. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param filter: An optional resampling filter. This can be + one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), + :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 + environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline + interpolation in a 4x4 environment), or + :py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter). + If omitted, or if the image has mode "1" or "P", it is + set :py:attr:`PIL.Image.NEAREST`. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS): + raise ValueError("unknown resampling filter") + + self.load() + + if self.mode in ("1", "P"): + resample = NEAREST + + if self.mode == 'RGBA': + return self.convert('RGBa').resize(size, resample).convert('RGBA') + + if resample == ANTIALIAS: + # requires stretch support (imToolkit & PIL 1.1.3) + try: + im = self.im.stretch(size, resample) + except AttributeError: + raise ValueError("unsupported resampling filter") + else: + im = self.im.resize(size, resample) + + return self._new(im) + + def rotate(self, angle, resample=NEAREST, expand=0): + """ + Returns a rotated copy of this image. This method returns a + copy of this image, rotated the given number of degrees counter + clockwise around its centre. + + :param angle: In degrees counter clockwise. + :param filter: An optional resampling filter. This can be + one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), + :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:attr:`PIL.Image.BICUBIC` + (cubic spline interpolation in a 4x4 environment). + If omitted, or if the image has mode "1" or "P", it is + set :py:attr:`PIL.Image.NEAREST`. + :param expand: Optional expansion flag. If true, expands the output + image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the + input image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if expand: + import math + angle = -angle * math.pi / 180 + matrix = [ + math.cos(angle), math.sin(angle), 0.0, + -math.sin(angle), math.cos(angle), 0.0 + ] + def transform(x, y, matrix=matrix): + (a, b, c, d, e, f) = matrix + return a*x + b*y + c, d*x + e*y + f + + # calculate output size + w, h = self.size + xx = [] + yy = [] + for x, y in ((0, 0), (w, 0), (w, h), (0, h)): + x, y = transform(x, y) + xx.append(x) + yy.append(y) + w = int(math.ceil(max(xx)) - math.floor(min(xx))) + h = int(math.ceil(max(yy)) - math.floor(min(yy))) + + # adjust center + x, y = transform(w / 2.0, h / 2.0) + matrix[2] = self.size[0] / 2.0 - x + matrix[5] = self.size[1] / 2.0 - y + + return self.transform((w, h), AFFINE, matrix, resample) + + if resample not in (NEAREST, BILINEAR, BICUBIC): + raise ValueError("unknown resampling filter") + + self.load() + + if self.mode in ("1", "P"): + resample = NEAREST + + return self._new(self.im.rotate(angle, resample)) + + def save(self, fp, format=None, **params): + """ + Saves this image under the given filename. If no format is + specified, the format to use is determined from the filename + extension, if possible. + + Keyword options can be used to provide additional instructions + to the writer. If a writer doesn't recognise an option, it is + silently ignored. The available options are described later in + this handbook. + + You can use a file object instead of a filename. In this case, + you must always specify the format. The file object must + implement the **seek**, **tell**, and **write** + methods, and be opened in binary mode. + + :param file: File name or file object. + :param format: Optional format override. If omitted, the + format to use is determined from the filename extension. + If a file object was used instead of a filename, this + parameter should always be used. + :param options: Extra parameters to the image writer. + :returns: None + :exception KeyError: If the output format could not be determined + from the file name. Use the format option to solve this. + :exception IOError: If the file could not be written. The file + may have been created, and may contain partial data. + """ + + if isPath(fp): + filename = fp + else: + if hasattr(fp, "name") and isPath(fp.name): + filename = fp.name + else: + filename = "" + + # may mutate self! + self.load() + + self.encoderinfo = params + self.encoderconfig = () + + preinit() + + ext = os.path.splitext(filename)[1].lower() + + if not format: + try: + format = EXTENSION[ext] + except KeyError: + init() + try: + format = EXTENSION[ext] + except KeyError: + raise KeyError(ext) # unknown extension + + try: + save_handler = SAVE[format.upper()] + except KeyError: + init() + save_handler = SAVE[format.upper()] # unknown format + + if isPath(fp): + fp = builtins.open(fp, "wb") + close = 1 + else: + close = 0 + + try: + save_handler(self, fp, filename) + finally: + # do what we can to clean up + if close: + fp.close() + + def seek(self, frame): + """ + Seeks to the given frame in this sequence file. If you seek + beyond the end of the sequence, the method raises an + **EOFError** exception. When a sequence file is opened, the + library automatically seeks to frame 0. + + Note that in the current version of the library, most sequence + formats only allows you to seek to the next frame. + + See :py:meth:`~PIL.Image.Image.tell`. + + :param frame: Frame number, starting at 0. + :exception EOFError: If the call attempts to seek beyond the end + of the sequence. + """ + + # overridden by file handlers + if frame != 0: + raise EOFError + + def show(self, title=None, command=None): + """ + Displays this image. This method is mainly intended for + debugging purposes. + + On Unix platforms, this method saves the image to a temporary + PPM file, and calls the **xv** utility. + + On Windows, it saves the image to a temporary BMP file, and uses + the standard BMP display utility to show it (usually Paint). + + :param title: Optional title to use for the image window, + where possible. + :param command: command used to show the image + """ + + _show(self, title=title, command=command) + + def split(self): + """ + Split this image into individual bands. This method returns a + tuple of individual image bands from an image. For example, + splitting an "RGB" image creates three new images each + containing a copy of one of the original bands (red, green, + blue). + + :returns: A tuple containing bands. + """ + + self.load() + if self.im.bands == 1: + ims = [self.copy()] + else: + ims = [] + for i in range(self.im.bands): + ims.append(self._new(self.im.getband(i))) + return tuple(ims) + + def tell(self): + """ + Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. + + :returns: Frame number, starting with 0. + """ + return 0 + + def thumbnail(self, size, resample=NEAREST): + """ + Make this image into a thumbnail. This method modifies the + image to contain a thumbnail version of itself, no larger than + the given size. This method calculates an appropriate thumbnail + size to preserve the aspect of the image, calls the + :py:meth:`~PIL.Image.Image.draft` method to configure the file reader + (where applicable), and finally resizes the image. + + Note that the bilinear and bicubic filters in the current + version of PIL are not well-suited for thumbnail generation. + You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more + important than quality. + + Also note that this function modifies the :py:class:`~PIL.Image.Image` + object in place. If you need to use the full resolution image as well, apply + this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. + + :param size: Requested size. + :param resample: Optional resampling filter. This can be one + of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`, + :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS` + (best quality). If omitted, it defaults to + :py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a + future version). + :returns: None + """ + + # FIXME: the default resampling filter will be changed + # to ANTIALIAS in future versions + + # preserve aspect ratio + x, y = self.size + if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0]) + if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1]) + size = x, y + + if size == self.size: + return + + self.draft(None, size) + + self.load() + + try: + im = self.resize(size, resample) + except ValueError: + if resample != ANTIALIAS: + raise + im = self.resize(size, NEAREST) # fallback + + self.im = im.im + self.mode = im.mode + self.size = size + + self.readonly = 0 + + # FIXME: the different tranform methods need further explanation + # instead of bloating the method docs, add a separate chapter. + def transform(self, size, method, data=None, resample=NEAREST, fill=1): + """ + Transforms this image. This method creates a new image with the + given size, and the same mode as the original, and copies data + to the new image using the given transform. + + :param size: The output size. + :param method: The transformation method. This is one of + :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion), + :py:attr:`PIL.Image.AFFINE` (affine transform), + :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform), + :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or + :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals + in one operation). + :param data: Extra data to the transformation method. + :param resample: Optional resampling filter. It can be one of + :py:attr:`PIL.Image.NEAREST` (use nearest neighbour), + :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline + interpolation in a 4x4 environment). If omitted, or if the image + has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if self.mode == 'RGBA': + return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA') + + if isinstance(method, ImageTransformHandler): + return method.transform(size, self, resample=resample, fill=fill) + if hasattr(method, "getdata"): + # compatibility w. old-style transform objects + method, data = method.getdata() + if data is None: + raise ValueError("missing method data") + + im = new(self.mode, size, None) + if method == MESH: + # list of quads + for box, quad in data: + im.__transformer(box, self, QUAD, quad, resample, fill) + else: + im.__transformer((0, 0)+size, self, method, data, resample, fill) + + return im + + def __transformer(self, box, image, method, data, + resample=NEAREST, fill=1): + + # FIXME: this should be turned into a lazy operation (?) + + w = box[2]-box[0] + h = box[3]-box[1] + + if method == AFFINE: + # change argument order to match implementation + data = (data[2], data[0], data[1], + data[5], data[3], data[4]) + elif method == EXTENT: + # convert extent to an affine transform + x0, y0, x1, y1 = data + xs = float(x1 - x0) / w + ys = float(y1 - y0) / h + method = AFFINE + data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys) + elif method == PERSPECTIVE: + # change argument order to match implementation + data = (data[2], data[0], data[1], + data[5], data[3], data[4], + data[6], data[7]) + elif method == QUAD: + # quadrilateral warp. data specifies the four corners + # given as NW, SW, SE, and NE. + nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8] + x0, y0 = nw; As = 1.0 / w; At = 1.0 / h + data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At, + (se[0]-sw[0]-ne[0]+x0)*As*At, + y0, (ne[1]-y0)*As, (sw[1]-y0)*At, + (se[1]-sw[1]-ne[1]+y0)*As*At) + else: + raise ValueError("unknown transformation method") + + if resample not in (NEAREST, BILINEAR, BICUBIC): + raise ValueError("unknown resampling filter") + + image.load() + + self.load() + + if image.mode in ("1", "P"): + resample = NEAREST + + self.im.transform2(box, image.im, method, data, resample, fill) + + def transpose(self, method): + """ + Transpose image (flip or rotate in 90 degree steps) + + :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, + :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, + :py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`. + :returns: Returns a flipped or rotated copy of this image. + """ + + self.load() + im = self.im.transpose(method) + return self._new(im) +``` + +## `PIL/Image.py` — `function:Image._dump` (lines 497-507) + +```python + def _dump(self, file=None, format=None): + import tempfile + if not file: + file = tempfile.mktemp() + self.load() + if not format or format == "PPM": + self.im.save_ppm(file) + else: + file = file + "." + format + self.save(file, format) + return file +``` + +## `PIL/IptcImagePlugin.py` — `class:IptcImageFile` (lines 53-204) + +```python +class IptcImageFile(ImageFile.ImageFile): + + format = "IPTC" + format_description = "IPTC/NAA" + + def getint(self, key): + return i(self.info[key]) + + def field(self): + # + # get a IPTC field header + s = self.fp.read(5) + if not len(s): + return None, 0 + + tag = i8(s[1]), i8(s[2]) + + # syntax + if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9: + raise SyntaxError("invalid IPTC/NAA file") + + # field size + size = i8(s[3]) + if size > 132: + raise IOError("illegal field length in IPTC/NAA file") + elif size == 128: + size = 0 + elif size > 128: + size = i(self.fp.read(size-128)) + else: + size = i16(s[3:]) + + return tag, size + + def _is_raw(self, offset, size): + # + # check if the file can be mapped + + # DISABLED: the following only slows things down... + return 0 + + self.fp.seek(offset) + t, sz = self.field() + if sz != size[0]: + return 0 + y = 1 + while True: + self.fp.seek(sz, 1) + t, s = self.field() + if t != (8, 10): + break + if s != sz: + return 0 + y = y + 1 + return y == size[1] + + def _open(self): + + # load descriptive fields + while True: + offset = self.fp.tell() + tag, size = self.field() + if not tag or tag == (8,10): + break + if size: + tagdata = self.fp.read(size) + else: + tagdata = None + if tag in list(self.info.keys()): + if isinstance(self.info[tag], list): + self.info[tag].append(tagdata) + else: + self.info[tag] = [self.info[tag], tagdata] + else: + self.info[tag] = tagdata + + # print tag, self.info[tag] + + # mode + layers = i8(self.info[(3,60)][0]) + component = i8(self.info[(3,60)][1]) + if (3,65) in self.info: + id = i8(self.info[(3,65)][0])-1 + else: + id = 0 + if layers == 1 and not component: + self.mode = "L" + elif layers == 3 and component: + self.mode = "RGB"[id] + elif layers == 4 and component: + self.mode = "CMYK"[id] + + # size + self.size = self.getint((3,20)), self.getint((3,30)) + + # compression + try: + compression = COMPRESSION[self.getint((3,120))] + except KeyError: + raise IOError("Unknown IPTC image compression") + + # tile + if tag == (8,10): + if compression == "raw" and self._is_raw(offset, self.size): + self.tile = [(compression, (offset, size + 5, -1), + (0, 0, self.size[0], self.size[1]))] + else: + self.tile = [("iptc", (compression, offset), + (0, 0, self.size[0], self.size[1]))] + + def load(self): + + if len(self.tile) != 1 or self.tile[0][0] != "iptc": + return ImageFile.ImageFile.load(self) + + type, tile, box = self.tile[0] + + encoding, offset = tile + + self.fp.seek(offset) + + # Copy image data to temporary file + outfile = tempfile.mktemp() + o = open(outfile, "wb") + if encoding == "raw": + # To simplify access to the extracted file, + # prepend a PPM header + o.write("P5\n%d %d\n255\n" % self.size) + while True: + type, size = self.field() + if type != (8, 10): + break + while size > 0: + s = self.fp.read(min(size, 8192)) + if not s: + break + o.write(s) + size = size - len(s) + o.close() + + try: + try: + # fast + self.im = Image.core.open_ppm(outfile) + except: + # slightly slower + im = Image.open(outfile) + im.load() + self.im = im.im + finally: + try: os.unlink(outfile) + except: pass +``` + +## `PIL/IptcImagePlugin.py` — `function:IptcImageFile.load` (lines 163-204) + +```python + def load(self): + + if len(self.tile) != 1 or self.tile[0][0] != "iptc": + return ImageFile.ImageFile.load(self) + + type, tile, box = self.tile[0] + + encoding, offset = tile + + self.fp.seek(offset) + + # Copy image data to temporary file + outfile = tempfile.mktemp() + o = open(outfile, "wb") + if encoding == "raw": + # To simplify access to the extracted file, + # prepend a PPM header + o.write("P5\n%d %d\n255\n" % self.size) + while True: + type, size = self.field() + if type != (8, 10): + break + while size > 0: + s = self.fp.read(min(size, 8192)) + if not s: + break + o.write(s) + size = size - len(s) + o.close() + + try: + try: + # fast + self.im = Image.core.open_ppm(outfile) + except: + # slightly slower + im = Image.open(outfile) + im.load() + self.im = im.im + finally: + try: os.unlink(outfile) + except: pass +``` + +## `PIL/JpegImagePlugin.py` — `class:JpegImageFile` (lines 267-362) + +```python +class JpegImageFile(ImageFile.ImageFile): + + format = "JPEG" + format_description = "JPEG (ISO 10918)" + + def _open(self): + + s = self.fp.read(1) + + if i8(s[0]) != 255: + raise SyntaxError("not a JPEG file") + + # Create attributes + self.bits = self.layers = 0 + + # JPEG specifics (internal) + self.layer = [] + self.huffman_dc = {} + self.huffman_ac = {} + self.quantization = {} + self.app = {} # compatibility + self.applist = [] + self.icclist = [] + + while True: + + s = s + self.fp.read(1) + + i = i16(s) + + if i in MARKER: + name, description, handler = MARKER[i] + # print hex(i), name, description + if handler is not None: + handler(self, i) + if i == 0xFFDA: # start of scan + rawmode = self.mode + if self.mode == "CMYK": + rawmode = "CMYK;I" # assume adobe conventions + self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))] + # self.__offset = self.fp.tell() + break + s = self.fp.read(1) + elif i == 0 or i == 65535: + # padded marker or junk; move on + s = "\xff" + else: + raise SyntaxError("no marker found") + + def draft(self, mode, size): + + if len(self.tile) != 1: + return + + d, e, o, a = self.tile[0] + scale = 0 + + if a[0] == "RGB" and mode in ["L", "YCbCr"]: + self.mode = mode + a = mode, "" + + if size: + scale = max(self.size[0] // size[0], self.size[1] // size[1]) + for s in [8, 4, 2, 1]: + if scale >= s: + break + e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1] + self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s) + scale = s + + self.tile = [(d, e, o, a)] + self.decoderconfig = (scale, 1) + + return self + + def load_djpeg(self): + + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + import tempfile, os + file = tempfile.mktemp() + os.system("djpeg %s >%s" % (self.filename, file)) + + try: + self.im = Image.core.open_ppm(file) + finally: + try: os.unlink(file) + except: pass + + self.mode = self.im.mode + self.size = self.im.size + + self.tile = [] + + def _getexif(self): + return _getexif(self) +``` + +## `PIL/JpegImagePlugin.py` — `function:JpegImageFile.load_djpeg` (lines 342-359) + +```python + def load_djpeg(self): + + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + import tempfile, os + file = tempfile.mktemp() + os.system("djpeg %s >%s" % (self.filename, file)) + + try: + self.im = Image.core.open_ppm(file) + finally: + try: os.unlink(file) + except: pass + + self.mode = self.im.mode + self.size = self.im.size + + self.tile = [] +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.json new file mode 100644 index 0000000000000000000000000000000000000000..72578b22d962b732aeb21b53ec3af91592773453 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.json @@ -0,0 +1,59 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-4954e5890cce23c8b03d", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-4954e5890cce23c8b03d", + "project_id": "pyvul__python-imaging__pillow", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "PIL/EpsImagePlugin.py", + "PIL/Image.py", + "PIL/IptcImagePlugin.py", + "PIL/JpegImagePlugin.py" + ], + "patch_units": { + "before": [ + "function:Ghostscript", + "class:Image", + "function:Image._dump", + "class:IptcImageFile", + "function:IptcImageFile.load", + "class:JpegImageFile", + "function:JpegImageFile.load_djpeg" + ], + "after": [ + "function:Ghostscript", + "class:Image", + "function:Image._dump", + "class:IptcImageFile", + "function:IptcImageFile.load", + "class:JpegImageFile", + "function:JpegImageFile.load_djpeg" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/08f641daaaf70221449c3b5c4a84e91796936219a20b91e4d35203686e7f7f18/database", + "cache_key": "08f641daaaf70221449c3b5c4a84e91796936219a20b91e4d35203686e7f7f18", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/62d7667e51007d1b94a468ba2fb246305f5f01a271bec41480f941757aef828b/database", + "cache_key": "62d7667e51007d1b94a468ba2fb246305f5f01a271bec41480f941757aef828b", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/25ef67aaf353265855d3a53ef7158ae4fa13015799c0bf4d700c936c6487ed7d/database", + "cache_key": "25ef67aaf353265855d3a53ef7158ae4fa13015799c0bf4d700c936c6487ed7d", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-4954e5890cce23c8b03d/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-4954e5890cce23c8b03d/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d3e020c722e1244cac428cc6d3db0d8397ec81b6 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diff @@ -0,0 +1,184 @@ +diff --git a/nautobot_device_onboarding/jobs.py b/nautobot_device_onboarding/jobs.py +index cca9e9c..72b843d 100644 +--- a/nautobot_device_onboarding/jobs.py ++++ b/nautobot_device_onboarding/jobs.py +@@ -13,12 +13,7 @@ PLUGIN_SETTINGS = settings.PLUGINS_CONFIG["nautobot_device_onboarding"] + + + class OnboardingTask(Job): +- class Meta: +- """Meta object boilerplate for onboarding.""" +- +- name = "Perform Device Onboarding" +- description = "Login to a device and populate Nautobot device object." +- has_sensitive_variables = False ++ """Nautobot Job for onboarding a new device.""" + + location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="") + ip_address = IPAddressVar(description="", label="") +@@ -29,18 +24,32 @@ class OnboardingTask(Job): + role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="") + device_type = ObjectVar(model=DeviceType, required=False, description="") + ++ class Meta: # pylint: disable=too-few-public-methods ++ """Meta object boilerplate for onboarding.""" ++ ++ name = "Perform Device Onboarding" ++ description = "Login to a device and populate Nautobot device object." ++ has_sensitive_variables = False ++ ++ def __init__(self, *args, **kwargs): ++ """Overload init to instantiate class attributes per W0201.""" ++ self.username = None ++ self.password = None ++ self.secret = None ++ super().__init__(*args, **kwargs) ++ + def run(self, *args, **data): + """Process a single Onboarding Task instance.""" + self.logger.info("START: onboard device") +- credentials = self._parse_credentials(data["credentials"]) ++ self._parse_credentials(data["credentials"]) + platform = data["platform"] + netdev = NetdevKeeper( + hostname=data["ip_address"], + port=data["port"], + timeout=data["timeout"], +- username=credentials["username"], +- password=credentials["password"], +- secret=credentials["secret"], ++ username=self.username, ++ password=self.password, ++ secret=self.secret, + napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, + optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, + ) +@@ -72,18 +81,16 @@ class OnboardingTask(Job): + + def _parse_credentials(self, credentials): + """Parse and return dictionary of credentials.""" +- + if credentials: +- self.username = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME),) +- self.password = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD),) +- self.secret = (None,) ++ self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME) ++ self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD) + secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) + if secret.exists(): + self.secret = secret.first() + else: +- self.username = (settings.NAPALM_USERNAME,) +- self.password = (settings.NAPALM_PASSWORD,) +- self.secret = (settings.NAPALM_ARGS.get("secret", None),) ++ self.username = settings.NAPALM_USERNAME ++ self.password = settings.NAPALM_PASSWORD ++ self.secret = settings.NAPALM_ARGS.get("secret", None) + + + register_jobs(OnboardingTask) +diff --git a/nautobot_device_onboarding/tests/test_netdev_keeper.py b/nautobot_device_onboarding/tests/test_netdev_keeper.py +deleted file mode 100644 +index 91fbde6..0000000 +--- a/nautobot_device_onboarding/tests/test_netdev_keeper.py ++++ /dev/null +@@ -1,72 +0,0 @@ +-"""Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes.""" +- +-from socket import gaierror +-from unittest import mock +- +-from django.contrib.contenttypes.models import ContentType +-from django.test import TestCase +- +-from nautobot.dcim.models import Device, Location, LocationType, Platform +-from nautobot.extras.models import Role, Status +- +-from nautobot_device_onboarding.exceptions import OnboardException +-from nautobot_device_onboarding.helpers import onboarding_task_fqdn_to_ip +-# from nautobot_device_onboarding.models import OnboardingTask +- +- +-class NetdevKeeperTestCase(TestCase): +- """Test the NetdevKeeper Class.""" +- +- def setUp(self): +- """Create a superuser and token for API calls.""" +- role_content_type = ContentType.objects.get_for_model(Device) +- status = Status.objects.get(name="Active") +- location_type = LocationType.objects.create(name="site") +- self.site1 = Location.objects.create(name="USWEST", location_type=location_type, status=status) +- self.device_role1 = Role.objects.create(name="Firewall") +- self.device_role1.content_types.set([role_content_type]) +- +- self.platform1 = Platform.objects.create(name="JunOS", napalm_driver="junos") +- # self.platform2 = Platform.objects.create(name="Cisco NX-OS", slug="cisco-nx-os") +- +- # self.onboarding_task4 = OnboardingTask.objects.create( +- # ip_address="ntc123.local", location=self.site1, role=self.device_role1, platform=self.platform1 +- # ) +- +- # self.onboarding_task5 = OnboardingTask.objects.create( +- # ip_address="bad.local", location=self.site1, role=self.device_role1, platform=self.platform1 +- # ) +- +- # self.onboarding_task7 = OnboardingTask.objects.create( +- # ip_address="192.0.2.1/32", location=self.site1, role=self.device_role1, platform=self.platform1 +- # ) +- +- # @mock.patch("nautobot_device_onboarding.helpers.socket.gethostbyname") +- # def test_check_ip(self, mock_get_hostbyname): +- # """Check DNS to IP address.""" +- # # Look up response value +- # mock_get_hostbyname.return_value = "192.0.2.1" +- +- # # FQDN -> IP +- # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task4) +- +- # # Run the check to change the IP address +- # self.assertEqual(self.onboarding_task4.ip_address, "192.0.2.1") +- +- # @mock.patch("nautobot_device_onboarding.helpers.socket.gethostbyname") +- # def test_failed_check_ip(self, mock_get_hostbyname): +- # """Check DNS to IP address failing.""" +- # # Look up a failed response +- # mock_get_hostbyname.side_effect = gaierror(8) +- +- # # Check for bad.local raising an exception +- # with self.assertRaises(OnboardException) as exc_info: +- # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task5) +- # self.assertEqual(exc_info.exception.message, "ERROR failed to complete DNS lookup: bad.local") +- # self.assertEqual(exc_info.exception.reason, "fail-dns") +- +- # # Check for exception with prefix address entered +- # with self.assertRaises(OnboardException) as exc_info: +- # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task7) +- # self.assertEqual(exc_info.exception.reason, "fail-prefix") +- # self.assertEqual(exc_info.exception.message, "ERROR appears a prefix was entered: 192.0.2.1/32") +diff --git a/nautobot_device_onboarding/tests/test_onboarding.py b/nautobot_device_onboarding/tests/test_onboarding.py +index d7a938c..f427bba 100644 +--- a/nautobot_device_onboarding/tests/test_onboarding.py ++++ b/nautobot_device_onboarding/tests/test_onboarding.py +@@ -1,16 +1,15 @@ + """Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes.""" +-from unittest import mock ++# from unittest import mock + + from django.conf import settings +-from django.test import TestCase +-from django.contrib.contenttypes.models import ContentType + ++# from django.test import TestCase ++# from django.contrib.contenttypes.models import ContentType + +-from nautobot.dcim.models import Device, Location, LocationType, Platform +-from nautobot.extras.models import Status + +-# from nautobot_device_onboarding.models import OnboardingTask +-# from nautobot_device_onboarding.onboard import OnboardingManager ++# from nautobot.dcim.models import Device, Location, LocationType, Platform ++# from nautobot.extras.models import Status ++ + + PLUGIN_SETTINGS = settings.PLUGINS_CONFIG["nautobot_device_onboarding"] + diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..14f0867bc6fea0614e7aee015cc3aae2f4d97a1e --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.md @@ -0,0 +1,169 @@ +# Patch-overlapping Python context after the fix + +## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask` (lines 15-93) + +```python +class OnboardingTask(Job): + """Nautobot Job for onboarding a new device.""" + + location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="") + ip_address = IPAddressVar(description="", label="") + port = IntegerVar(description="") + timeout = IntegerVar(description="") + credentials = ObjectVar(model=SecretsGroup, query_params={"": ""}, required=False, description="") + platform = ObjectVar(model=Platform, required=False, description="") + role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="") + device_type = ObjectVar(model=DeviceType, required=False, description="") + + class Meta: # pylint: disable=too-few-public-methods + """Meta object boilerplate for onboarding.""" + + name = "Perform Device Onboarding" + description = "Login to a device and populate Nautobot device object." + has_sensitive_variables = False + + def __init__(self, *args, **kwargs): + """Overload init to instantiate class attributes per W0201.""" + self.username = None + self.password = None + self.secret = None + super().__init__(*args, **kwargs) + + def run(self, *args, **data): + """Process a single Onboarding Task instance.""" + self.logger.info("START: onboard device") + self._parse_credentials(data["credentials"]) + platform = data["platform"] + netdev = NetdevKeeper( + hostname=data["ip_address"], + port=data["port"], + timeout=data["timeout"], + username=self.username, + password=self.password, + secret=self.secret, + napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, + optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, + ) + netdev.get_onboarding_facts() + netdev_dict = netdev.get_netdev_dict() + + onboarding_kwargs = { + # Kwargs extracted from OnboardingTask: + "netdev_mgmt_ip_address": data["ip_address"], + "netdev_nb_location_name": data["location"].name, + "netdev_nb_device_type_name": data["device_type"], + "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"], + "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"], + "netdev_nb_platform_name": data["platform"].name if data["platform"] else None, + # Kwargs discovered on the Onboarded Device: + "netdev_hostname": netdev_dict["netdev_hostname"], + "netdev_vendor": netdev_dict["netdev_vendor"], + "netdev_model": netdev_dict["netdev_model"], + "netdev_serial_number": netdev_dict["netdev_serial_number"], + "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"], + "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"], + "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"], + "onboarding_class": netdev_dict["onboarding_class"], + "driver_addon_result": netdev_dict["driver_addon_result"], + } + onboarding_cls = netdev_dict["onboarding_class"]() + onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret} + onboarding_cls.run(onboarding_kwargs=onboarding_kwargs) + + def _parse_credentials(self, credentials): + """Parse and return dictionary of credentials.""" + if credentials: + self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME) + self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD) + secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) + if secret.exists(): + self.secret = secret.first() + else: + self.username = settings.NAPALM_USERNAME + self.password = settings.NAPALM_PASSWORD + self.secret = settings.NAPALM_ARGS.get("secret", None) +``` + +## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask.Meta` (lines 27-32) + +```python + class Meta: # pylint: disable=too-few-public-methods + """Meta object boilerplate for onboarding.""" + + name = "Perform Device Onboarding" + description = "Login to a device and populate Nautobot device object." + has_sensitive_variables = False +``` + +## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.__init__` (lines 34-39) + +```python + def __init__(self, *args, **kwargs): + """Overload init to instantiate class attributes per W0201.""" + self.username = None + self.password = None + self.secret = None + super().__init__(*args, **kwargs) +``` + +## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.run` (lines 41-80) + +```python + def run(self, *args, **data): + """Process a single Onboarding Task instance.""" + self.logger.info("START: onboard device") + self._parse_credentials(data["credentials"]) + platform = data["platform"] + netdev = NetdevKeeper( + hostname=data["ip_address"], + port=data["port"], + timeout=data["timeout"], + username=self.username, + password=self.password, + secret=self.secret, + napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, + optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, + ) + netdev.get_onboarding_facts() + netdev_dict = netdev.get_netdev_dict() + + onboarding_kwargs = { + # Kwargs extracted from OnboardingTask: + "netdev_mgmt_ip_address": data["ip_address"], + "netdev_nb_location_name": data["location"].name, + "netdev_nb_device_type_name": data["device_type"], + "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"], + "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"], + "netdev_nb_platform_name": data["platform"].name if data["platform"] else None, + # Kwargs discovered on the Onboarded Device: + "netdev_hostname": netdev_dict["netdev_hostname"], + "netdev_vendor": netdev_dict["netdev_vendor"], + "netdev_model": netdev_dict["netdev_model"], + "netdev_serial_number": netdev_dict["netdev_serial_number"], + "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"], + "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"], + "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"], + "onboarding_class": netdev_dict["onboarding_class"], + "driver_addon_result": netdev_dict["driver_addon_result"], + } + onboarding_cls = netdev_dict["onboarding_class"]() + onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret} + onboarding_cls.run(onboarding_kwargs=onboarding_kwargs) +``` + +## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask._parse_credentials` (lines 82-93) + +```python + def _parse_credentials(self, credentials): + """Parse and return dictionary of credentials.""" + if credentials: + self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME) + self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD) + secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) + if secret.exists(): + self.secret = secret.first() + else: + self.username = settings.NAPALM_USERNAME + self.password = settings.NAPALM_PASSWORD + self.secret = settings.NAPALM_ARGS.get("secret", None) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..79491d881d0c6d9f2464d7f5e437b58be2a86736 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/pre_context.md @@ -0,0 +1,270 @@ +# Patch-overlapping Python context before the fix + +## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask` (lines 15-86) + +```python +class OnboardingTask(Job): + class Meta: + """Meta object boilerplate for onboarding.""" + + name = "Perform Device Onboarding" + description = "Login to a device and populate Nautobot device object." + has_sensitive_variables = False + + location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="") + ip_address = IPAddressVar(description="", label="") + port = IntegerVar(description="") + timeout = IntegerVar(description="") + credentials = ObjectVar(model=SecretsGroup, query_params={"": ""}, required=False, description="") + platform = ObjectVar(model=Platform, required=False, description="") + role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="") + device_type = ObjectVar(model=DeviceType, required=False, description="") + + def run(self, *args, **data): + """Process a single Onboarding Task instance.""" + self.logger.info("START: onboard device") + credentials = self._parse_credentials(data["credentials"]) + platform = data["platform"] + netdev = NetdevKeeper( + hostname=data["ip_address"], + port=data["port"], + timeout=data["timeout"], + username=credentials["username"], + password=credentials["password"], + secret=credentials["secret"], + napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, + optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, + ) + netdev.get_onboarding_facts() + netdev_dict = netdev.get_netdev_dict() + + onboarding_kwargs = { + # Kwargs extracted from OnboardingTask: + "netdev_mgmt_ip_address": data["ip_address"], + "netdev_nb_location_name": data["location"].name, + "netdev_nb_device_type_name": data["device_type"], + "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"], + "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"], + "netdev_nb_platform_name": data["platform"].name if data["platform"] else None, + # Kwargs discovered on the Onboarded Device: + "netdev_hostname": netdev_dict["netdev_hostname"], + "netdev_vendor": netdev_dict["netdev_vendor"], + "netdev_model": netdev_dict["netdev_model"], + "netdev_serial_number": netdev_dict["netdev_serial_number"], + "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"], + "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"], + "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"], + "onboarding_class": netdev_dict["onboarding_class"], + "driver_addon_result": netdev_dict["driver_addon_result"], + } + onboarding_cls = netdev_dict["onboarding_class"]() + onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret} + onboarding_cls.run(onboarding_kwargs=onboarding_kwargs) + + def _parse_credentials(self, credentials): + """Parse and return dictionary of credentials.""" + + if credentials: + self.username = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME),) + self.password = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD),) + self.secret = (None,) + secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) + if secret.exists(): + self.secret = secret.first() + else: + self.username = (settings.NAPALM_USERNAME,) + self.password = (settings.NAPALM_PASSWORD,) + self.secret = (settings.NAPALM_ARGS.get("secret", None),) +``` + +## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask.Meta` (lines 16-21) + +```python + class Meta: + """Meta object boilerplate for onboarding.""" + + name = "Perform Device Onboarding" + description = "Login to a device and populate Nautobot device object." + has_sensitive_variables = False +``` + +## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.run` (lines 32-71) + +```python + def run(self, *args, **data): + """Process a single Onboarding Task instance.""" + self.logger.info("START: onboard device") + credentials = self._parse_credentials(data["credentials"]) + platform = data["platform"] + netdev = NetdevKeeper( + hostname=data["ip_address"], + port=data["port"], + timeout=data["timeout"], + username=credentials["username"], + password=credentials["password"], + secret=credentials["secret"], + napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None, + optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS, + ) + netdev.get_onboarding_facts() + netdev_dict = netdev.get_netdev_dict() + + onboarding_kwargs = { + # Kwargs extracted from OnboardingTask: + "netdev_mgmt_ip_address": data["ip_address"], + "netdev_nb_location_name": data["location"].name, + "netdev_nb_device_type_name": data["device_type"], + "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"], + "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"], + "netdev_nb_platform_name": data["platform"].name if data["platform"] else None, + # Kwargs discovered on the Onboarded Device: + "netdev_hostname": netdev_dict["netdev_hostname"], + "netdev_vendor": netdev_dict["netdev_vendor"], + "netdev_model": netdev_dict["netdev_model"], + "netdev_serial_number": netdev_dict["netdev_serial_number"], + "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"], + "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"], + "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"], + "onboarding_class": netdev_dict["onboarding_class"], + "driver_addon_result": netdev_dict["driver_addon_result"], + } + onboarding_cls = netdev_dict["onboarding_class"]() + onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret} + onboarding_cls.run(onboarding_kwargs=onboarding_kwargs) +``` + +## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask._parse_credentials` (lines 73-86) + +```python + def _parse_credentials(self, credentials): + """Parse and return dictionary of credentials.""" + + if credentials: + self.username = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME),) + self.password = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD),) + self.secret = (None,) + secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET) + if secret.exists(): + self.secret = secret.first() + else: + self.username = (settings.NAPALM_USERNAME,) + self.password = (settings.NAPALM_PASSWORD,) + self.secret = (settings.NAPALM_ARGS.get("secret", None),) +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `class:NetdevKeeperTestCase` (lines 17-29) + +```python +class NetdevKeeperTestCase(TestCase): + """Test the NetdevKeeper Class.""" + + def setUp(self): + """Create a superuser and token for API calls.""" + role_content_type = ContentType.objects.get_for_model(Device) + status = Status.objects.get(name="Active") + location_type = LocationType.objects.create(name="site") + self.site1 = Location.objects.create(name="USWEST", location_type=location_type, status=status) + self.device_role1 = Role.objects.create(name="Firewall") + self.device_role1.content_types.set([role_content_type]) + + self.platform1 = Platform.objects.create(name="JunOS", napalm_driver="junos") +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `function:NetdevKeeperTestCase.setUp` (lines 20-29) + +```python + def setUp(self): + """Create a superuser and token for API calls.""" + role_content_type = ContentType.objects.get_for_model(Device) + status = Status.objects.get(name="Active") + location_type = LocationType.objects.create(name="site") + self.site1 = Location.objects.create(name="USWEST", location_type=location_type, status=status) + self.device_role1 = Role.objects.create(name="Firewall") + self.device_role1.content_types.set([role_content_type]) + + self.platform1 = Platform.objects.create(name="JunOS", napalm_driver="junos") +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@1` (lines 1-1) + +```python +"""Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes.""" +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@3` (lines 3-3) + +```python +from socket import gaierror +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@4` (lines 4-4) + +```python +from unittest import mock +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@6` (lines 6-6) + +```python +from django.contrib.contenttypes.models import ContentType +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@7` (lines 7-7) + +```python +from django.test import TestCase +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@9` (lines 9-9) + +```python +from nautobot.dcim.models import Device, Location, LocationType, Platform +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@10` (lines 10-10) + +```python +from nautobot.extras.models import Role, Status +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@12` (lines 12-12) + +```python +from nautobot_device_onboarding.exceptions import OnboardException +``` + +## `nautobot_device_onboarding/tests/test_netdev_keeper.py` — `module:@13` (lines 13-13) + +```python +from nautobot_device_onboarding.helpers import onboarding_task_fqdn_to_ip +``` + +## `nautobot_device_onboarding/tests/test_onboarding.py` — `module:@2` (lines 2-2) + +```python +from unittest import mock +``` + +## `nautobot_device_onboarding/tests/test_onboarding.py` — `module:@5` (lines 5-5) + +```python +from django.test import TestCase +``` + +## `nautobot_device_onboarding/tests/test_onboarding.py` — `module:@6` (lines 6-6) + +```python +from django.contrib.contenttypes.models import ContentType +``` + +## `nautobot_device_onboarding/tests/test_onboarding.py` — `module:@9` (lines 9-9) + +```python +from nautobot.dcim.models import Device, Location, LocationType, Platform +``` + +## `nautobot_device_onboarding/tests/test_onboarding.py` — `module:@10` (lines 10-10) + +```python +from nautobot.extras.models import Status +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5d24b32fc28cc9e71ae0d9f80afb9b1736dd1d60 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/task.json @@ -0,0 +1,69 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-4ac3440b9023e6511a91", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-4ac3440b9023e6511a91", + "project_id": "pyvul__nautobot__nautobot-plugin-device-onboarding", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "nautobot_device_onboarding/jobs.py", + "nautobot_device_onboarding/tests/test_netdev_keeper.py", + "nautobot_device_onboarding/tests/test_onboarding.py" + ], + "patch_units": { + "before": [ + "class:OnboardingTask", + "class:OnboardingTask.Meta", + "function:OnboardingTask.run", + "function:OnboardingTask._parse_credentials", + "class:NetdevKeeperTestCase", + "function:NetdevKeeperTestCase.setUp", + "module:@1", + "module:@3", + "module:@4", + "module:@6", + "module:@7", + "module:@9", + "module:@10", + "module:@12", + "module:@13", + "module:@2", + "module:@5", + "module:@6", + "module:@9", + "module:@10" + ], + "after": [ + "class:OnboardingTask", + "class:OnboardingTask.Meta", + "function:OnboardingTask.__init__", + "function:OnboardingTask.run", + "function:OnboardingTask._parse_credentials" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/012046021b9fd116d3282a28f079c81707cd84efd4d2e1b24f5eb6332073dfb3/database", + "cache_key": "012046021b9fd116d3282a28f079c81707cd84efd4d2e1b24f5eb6332073dfb3", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/26efb7af79ad8b530362c838429d28bb72e8ef7f602c5193a4d437580582bf06/database", + "cache_key": "26efb7af79ad8b530362c838429d28bb72e8ef7f602c5193a4d437580582bf06", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/b6ecc163bd36c512022db3cd092be7f93d0c25dcb0e080bc5a8a27811bedcd12/database", + "cache_key": "b6ecc163bd36c512022db3cd092be7f93d0c25dcb0e080bc5a8a27811bedcd12", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-4ac3440b9023e6511a91/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-4ac3440b9023e6511a91/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ae7ffeb1f37e146dd42259203c7919e188a8e131 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/patch.diff @@ -0,0 +1,59 @@ +diff --git a/psiturk/experiment.py b/psiturk/experiment.py +index a6904f6..7ba1c1e 100644 +--- a/psiturk/experiment.py ++++ b/psiturk/experiment.py +@@ -380,9 +380,10 @@ def advertisement(): + # even have accepted the HIT. + with open('templates/ad.html', 'r') as temp_file: + ad_string = temp_file.read() +- ad_string = insert_mode(ad_string, mode) ++ ad_string = insert_mode(ad_string) + return render_template_string( + ad_string, ++ mode=mode, + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id +@@ -406,9 +407,10 @@ def give_consent(): + mode = request.args['mode'] + with open('templates/consent.html', 'r') as temp_file: + consent_string = temp_file.read() +- consent_string = insert_mode(consent_string, mode) ++ consent_string = insert_mode(consent_string) + return render_template_string( + consent_string, ++ mode=mode, + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id +@@ -731,7 +733,7 @@ def ppid(): + # to avoid breaking backwards compatibility with old templates. + + +-def insert_mode(page_html, mode): ++def insert_mode(page_html): + """ Insert mode """ + page_html = page_html + match_found = False +@@ -740,7 +742,7 @@ def insert_mode(page_html, mode): + for match in matches: + match_found = True + if match_found: +- new_html = page_html[:match.end()] + "&mode=" + mode +\ ++ new_html = page_html[:match.end()] + '&mode={{ mode }}' +\ + page_html[match.end():] + return new_html + else: +diff --git a/tests/test_psiturk.py b/tests/test_psiturk.py +index 497f0a5..5229962 100644 +--- a/tests/test_psiturk.py ++++ b/tests/test_psiturk.py +@@ -141,7 +141,7 @@ def test_insert_mode(psiturk_test_client): + ad_string = temp_file.read() + + from psiturk.experiment import insert_mode +- insert_mode(ad_string, 'debug') ++ insert_mode(ad_string) + + + class PsiTurkStandardTests(PsiturkUnitTest): diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..ece5a601228585cdebd848db152cec740faac39c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/post_context.md @@ -0,0 +1,168 @@ +# Patch-overlapping Python context after the fix + +## `psiturk/experiment.py` — `function:advertisement` (lines 284-392) + +```python +def advertisement(): + """ + This is the url we give for the ad for our 'external question'. The ad has + to display two different things: This page will be called from within + mechanical turk, with url arguments hitId, assignmentId, and workerId. + If the worker has not yet accepted the hit: + These arguments will have null values, we should just show an ad for + the experiment. + If the worker has accepted the hit: + These arguments will have appropriate values and we should enter the + person in the database and provide a link to the experiment popup. + """ + user_agent_string = request.user_agent.string + user_agent_obj = user_agents.parse(user_agent_string) + browser_ok = True + browser_exclude_rule = CONFIG.get('Task Parameters', 'browser_exclude_rule') + for rule in browser_exclude_rule.split(','): + myrule = rule.strip() + if myrule in ["mobile", "tablet", "touchcapable", "pc", "bot"]: + if (myrule == "mobile" and user_agent_obj.is_mobile) or\ + (myrule == "tablet" and user_agent_obj.is_tablet) or\ + (myrule == "touchcapable" and user_agent_obj.is_touch_capable) or\ + (myrule == "pc" and user_agent_obj.is_pc) or\ + (myrule == "bot" and user_agent_obj.is_bot): + browser_ok = False + elif myrule == "Safari" or myrule == "safari": + if "Chrome" in user_agent_string and "Safari" in user_agent_string: + pass + elif "Safari" in user_agent_string: + browser_ok = False + elif myrule in user_agent_string: + browser_ok = False + + if not browser_ok: + # Handler for IE users if IE is not supported. + raise ExperimentError('browser_type_not_allowed') + + if not ('hitId' in request.args and 'assignmentId' in request.args): + raise ExperimentError('hit_assign_worker_id_not_set_in_mturk') + hit_id = request.args['hitId'] + assignment_id = request.args['assignmentId'] + mode = request.args['mode'] + if hit_id[:5] == "debug": + debug_mode = True + else: + debug_mode = False + already_in_db = False + if 'workerId' in request.args: + worker_id = request.args['workerId'] + # First check if this workerId has completed the task before (v1). + nrecords = Participant.query.\ + filter(Participant.assignmentid != assignment_id).\ + filter(Participant.workerid == worker_id).\ + count() + + if nrecords > 0: # Already completed task + already_in_db = True + else: # If worker has not accepted the hit + worker_id = None + try: + part = Participant.query.\ + filter(Participant.hitid == hit_id).\ + filter(Participant.assignmentid == assignment_id).\ + filter(Participant.workerid == worker_id).\ + one() + status = part.status + except exc.SQLAlchemyError: + status = None + + allow_repeats = CONFIG.getboolean('Task Parameters', 'allow_repeats') + if (status == STARTED or status == QUITEARLY) and not debug_mode: + # Once participants have finished the instructions, we do not allow + # them to start the task again. + raise ExperimentError('already_started_exp_mturk') + elif status == COMPLETED or (status == SUBMITTED and not already_in_db): + # 'or status == SUBMITTED' because we suspect that sometimes the post + # to mturk fails after we've set status to SUBMITTED, so really they + # have not successfully submitted. This gives another chance for the + # submit to work. + + # They've finished the experiment but haven't successfully submitted the HIT + # yet. + return render_template( + 'thanks-mturksubmit.html', + using_sandbox=(mode == "sandbox"), + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id + ) + elif already_in_db and not (debug_mode or allow_repeats): + raise ExperimentError('already_did_exp_hit') + elif status == ALLOCATED or not status or debug_mode: + # Participant has not yet agreed to the consent. They might not + # even have accepted the HIT. + with open('templates/ad.html', 'r') as temp_file: + ad_string = temp_file.read() + ad_string = insert_mode(ad_string) + return render_template_string( + ad_string, + mode=mode, + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id + ) + else: + raise ExperimentError('status_incorrectly_set') +``` + +## `psiturk/experiment.py` — `function:give_consent` (lines 395-417) + +```python +def give_consent(): + """ + Serves up the consent in the popup window. + """ + if not ('hitId' in request.args and 'assignmentId' in request.args and + 'workerId' in request.args): + raise ExperimentError('hit_assign_worker_id_not_set_in_consent') + hit_id = request.args['hitId'] + assignment_id = request.args['assignmentId'] + worker_id = request.args['workerId'] + mode = request.args['mode'] + with open('templates/consent.html', 'r') as temp_file: + consent_string = temp_file.read() + consent_string = insert_mode(consent_string) + return render_template_string( + consent_string, + mode=mode, + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id + ) +``` + +## `psiturk/experiment.py` — `function:insert_mode` (lines 736-749) + +```python +def insert_mode(page_html): + """ Insert mode """ + page_html = page_html + match_found = False + matches = re.finditer('workerId={{ workerid }}', page_html) + match = None + for match in matches: + match_found = True + if match_found: + new_html = page_html[:match.end()] + '&mode={{ mode }}' +\ + page_html[match.end():] + return new_html + else: + raise ExperimentError("insert_mode_failed") +``` + +## `tests/test_psiturk.py` — `function:test_insert_mode` (lines 139-144) + +```python +def test_insert_mode(psiturk_test_client): + with open('templates/ad.html', 'r') as temp_file: + ad_string = temp_file.read() + + from psiturk.experiment import insert_mode + insert_mode(ad_string) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..57d70e68be601ad5e74b24c1b6b034bb00bbe811 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/pre_context.md @@ -0,0 +1,166 @@ +# Patch-overlapping Python context before the fix + +## `psiturk/experiment.py` — `function:advertisement` (lines 284-391) + +```python +def advertisement(): + """ + This is the url we give for the ad for our 'external question'. The ad has + to display two different things: This page will be called from within + mechanical turk, with url arguments hitId, assignmentId, and workerId. + If the worker has not yet accepted the hit: + These arguments will have null values, we should just show an ad for + the experiment. + If the worker has accepted the hit: + These arguments will have appropriate values and we should enter the + person in the database and provide a link to the experiment popup. + """ + user_agent_string = request.user_agent.string + user_agent_obj = user_agents.parse(user_agent_string) + browser_ok = True + browser_exclude_rule = CONFIG.get('Task Parameters', 'browser_exclude_rule') + for rule in browser_exclude_rule.split(','): + myrule = rule.strip() + if myrule in ["mobile", "tablet", "touchcapable", "pc", "bot"]: + if (myrule == "mobile" and user_agent_obj.is_mobile) or\ + (myrule == "tablet" and user_agent_obj.is_tablet) or\ + (myrule == "touchcapable" and user_agent_obj.is_touch_capable) or\ + (myrule == "pc" and user_agent_obj.is_pc) or\ + (myrule == "bot" and user_agent_obj.is_bot): + browser_ok = False + elif myrule == "Safari" or myrule == "safari": + if "Chrome" in user_agent_string and "Safari" in user_agent_string: + pass + elif "Safari" in user_agent_string: + browser_ok = False + elif myrule in user_agent_string: + browser_ok = False + + if not browser_ok: + # Handler for IE users if IE is not supported. + raise ExperimentError('browser_type_not_allowed') + + if not ('hitId' in request.args and 'assignmentId' in request.args): + raise ExperimentError('hit_assign_worker_id_not_set_in_mturk') + hit_id = request.args['hitId'] + assignment_id = request.args['assignmentId'] + mode = request.args['mode'] + if hit_id[:5] == "debug": + debug_mode = True + else: + debug_mode = False + already_in_db = False + if 'workerId' in request.args: + worker_id = request.args['workerId'] + # First check if this workerId has completed the task before (v1). + nrecords = Participant.query.\ + filter(Participant.assignmentid != assignment_id).\ + filter(Participant.workerid == worker_id).\ + count() + + if nrecords > 0: # Already completed task + already_in_db = True + else: # If worker has not accepted the hit + worker_id = None + try: + part = Participant.query.\ + filter(Participant.hitid == hit_id).\ + filter(Participant.assignmentid == assignment_id).\ + filter(Participant.workerid == worker_id).\ + one() + status = part.status + except exc.SQLAlchemyError: + status = None + + allow_repeats = CONFIG.getboolean('Task Parameters', 'allow_repeats') + if (status == STARTED or status == QUITEARLY) and not debug_mode: + # Once participants have finished the instructions, we do not allow + # them to start the task again. + raise ExperimentError('already_started_exp_mturk') + elif status == COMPLETED or (status == SUBMITTED and not already_in_db): + # 'or status == SUBMITTED' because we suspect that sometimes the post + # to mturk fails after we've set status to SUBMITTED, so really they + # have not successfully submitted. This gives another chance for the + # submit to work. + + # They've finished the experiment but haven't successfully submitted the HIT + # yet. + return render_template( + 'thanks-mturksubmit.html', + using_sandbox=(mode == "sandbox"), + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id + ) + elif already_in_db and not (debug_mode or allow_repeats): + raise ExperimentError('already_did_exp_hit') + elif status == ALLOCATED or not status or debug_mode: + # Participant has not yet agreed to the consent. They might not + # even have accepted the HIT. + with open('templates/ad.html', 'r') as temp_file: + ad_string = temp_file.read() + ad_string = insert_mode(ad_string, mode) + return render_template_string( + ad_string, + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id + ) + else: + raise ExperimentError('status_incorrectly_set') +``` + +## `psiturk/experiment.py` — `function:give_consent` (lines 394-415) + +```python +def give_consent(): + """ + Serves up the consent in the popup window. + """ + if not ('hitId' in request.args and 'assignmentId' in request.args and + 'workerId' in request.args): + raise ExperimentError('hit_assign_worker_id_not_set_in_consent') + hit_id = request.args['hitId'] + assignment_id = request.args['assignmentId'] + worker_id = request.args['workerId'] + mode = request.args['mode'] + with open('templates/consent.html', 'r') as temp_file: + consent_string = temp_file.read() + consent_string = insert_mode(consent_string, mode) + return render_template_string( + consent_string, + hitid=hit_id, + assignmentid=assignment_id, + workerid=worker_id + ) +``` + +## `psiturk/experiment.py` — `function:insert_mode` (lines 734-747) + +```python +def insert_mode(page_html, mode): + """ Insert mode """ + page_html = page_html + match_found = False + matches = re.finditer('workerId={{ workerid }}', page_html) + match = None + for match in matches: + match_found = True + if match_found: + new_html = page_html[:match.end()] + "&mode=" + mode +\ + page_html[match.end():] + return new_html + else: + raise ExperimentError("insert_mode_failed") +``` + +## `tests/test_psiturk.py` — `function:test_insert_mode` (lines 139-144) + +```python +def test_insert_mode(psiturk_test_client): + with open('templates/ad.html', 'r') as temp_file: + ad_string = temp_file.read() + + from psiturk.experiment import insert_mode + insert_mode(ad_string, 'debug') +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d820d4597455f8311b9fbf5356acb37895abc736 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-4e31b8fba29687b8d792", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-4e31b8fba29687b8d792", + "project_id": "pyvul__nyuccl__psiturk", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "psiturk/experiment.py", + "tests/test_psiturk.py" + ], + "patch_units": { + "before": [ + "function:advertisement", + "function:give_consent", + "function:insert_mode", + "function:test_insert_mode" + ], + "after": [ + "function:advertisement", + "function:give_consent", + "function:insert_mode", + "function:test_insert_mode" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/79508f84d3892ba1bfd970615da21a2e953cdd965259474c8f524774e9175e08/database", + "cache_key": "79508f84d3892ba1bfd970615da21a2e953cdd965259474c8f524774e9175e08", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/01fd9d794d01851dcf2224476d86233b43838f47082fa844196920a9b7eaff7e/database", + "cache_key": "01fd9d794d01851dcf2224476d86233b43838f47082fa844196920a9b7eaff7e", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/2f575749daec3dc4cb2bfa1da45d22079c8620e59f4fc5baa4b54ec36d5020d0/database", + "cache_key": "2f575749daec3dc4cb2bfa1da45d22079c8620e59f4fc5baa4b54ec36d5020d0", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-4e31b8fba29687b8d792/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-4e31b8fba29687b8d792/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-4e31b8fba29687b8d792/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eebc4de3c4a95579cfe951994f4b9adb141eeead --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/patch.diff @@ -0,0 +1,44 @@ +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index e0e1ca1..6905f2d 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -22,7 +22,10 @@ class StripCommentsFilter: + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. +- m = re.search(r'((\r\n|\r|\n)+) *$', token.value) ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'((\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +diff --git a/tests/test_format.py b/tests/test_format.py +index 7117d9d..70bb805 100644 +--- a/tests/test_format.py ++++ b/tests/test_format.py +@@ -84,6 +84,23 @@ class TestFormat: + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select (select 2)' + ++ def test_strip_comments_preserves_linebreak(self): ++ sql = 'select * -- a comment\r\nfrom foo' ++ res = sqlparse.format(sql, strip_comments=True) ++ assert res == 'select *\nfrom foo' ++ sql = 'select * -- a comment\nfrom foo' ++ res = sqlparse.format(sql, strip_comments=True) ++ assert res == 'select *\nfrom foo' ++ sql = 'select * -- a comment\rfrom foo' ++ res = sqlparse.format(sql, strip_comments=True) ++ assert res == 'select *\nfrom foo' ++ sql = 'select * -- a comment\r\n\r\nfrom foo' ++ res = sqlparse.format(sql, strip_comments=True) ++ assert res == 'select *\n\nfrom foo' ++ sql = 'select * -- a comment\n\nfrom foo' ++ res = sqlparse.format(sql, strip_comments=True) ++ assert res == 'select *\n\nfrom foo' ++ + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c681b4bbcfed8f7d08289c71158bcb75820c1a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/post_context.md @@ -0,0 +1,263 @@ +# Patch-overlapping Python context after the fix + +## `sqlparse/filters/others.py` — `class:StripCommentsFilter` (lines 14-56) + +```python +class StripCommentsFilter: + + @staticmethod + def _process(tlist): + def get_next_comment(): + # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment) + + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. + # Note: The actual value for a line break is replaced by \n + # in SerializerUnicode which will be executed in the + # postprocessing state. + m = re.search(r'((\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: + return sql.Token(T.Whitespace, ' ') + + tidx, token = get_next_comment() + while token: + pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) + nidx, next_ = tlist.token_next(tidx, skip_ws=False) + # Replace by whitespace if prev and next exist and if they're not + # whitespaces. This doesn't apply if prev or next is a parenthesis. + if (prev_ is None or next_ is None + or prev_.is_whitespace or prev_.match(T.Punctuation, '(') + or next_.is_whitespace or next_.match(T.Punctuation, ')')): + # Insert a whitespace to ensure the following SQL produces + # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): + tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: + tlist.tokens[tidx] = _get_insert_token(token) + + tidx, token = get_next_comment() + + def process(self, stmt): + [self.process(sgroup) for sgroup in stmt.get_sublists()] + StripCommentsFilter._process(stmt) + return stmt +``` + +## `sqlparse/filters/others.py` — `function:StripCommentsFilter._process` (lines 16-51) + +```python + def _process(tlist): + def get_next_comment(): + # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment) + + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. + # Note: The actual value for a line break is replaced by \n + # in SerializerUnicode which will be executed in the + # postprocessing state. + m = re.search(r'((\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: + return sql.Token(T.Whitespace, ' ') + + tidx, token = get_next_comment() + while token: + pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) + nidx, next_ = tlist.token_next(tidx, skip_ws=False) + # Replace by whitespace if prev and next exist and if they're not + # whitespaces. This doesn't apply if prev or next is a parenthesis. + if (prev_ is None or next_ is None + or prev_.is_whitespace or prev_.match(T.Punctuation, '(') + or next_.is_whitespace or next_.match(T.Punctuation, ')')): + # Insert a whitespace to ensure the following SQL produces + # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): + tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: + tlist.tokens[tidx] = _get_insert_token(token) + + tidx, token = get_next_comment() +``` + +## `sqlparse/filters/others.py` — `function:StripCommentsFilter._process._get_insert_token` (lines 22-32) + +```python + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. + # Note: The actual value for a line break is replaced by \n + # in SerializerUnicode which will be executed in the + # postprocessing state. + m = re.search(r'((\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: + return sql.Token(T.Whitespace, ' ') +``` + +## `tests/test_format.py` — `class:TestFormat` (lines 7-138) + +```python +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") +``` + +## `tests/test_format.py` — `function:TestFormat.test_strip_comments_preserves_linebreak` (lines 87-102) + +```python + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8bc9f238eb0e3feea61f343fbdc1751261de98c2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/pre_context.md @@ -0,0 +1,227 @@ +# Patch-overlapping Python context before the fix + +## `sqlparse/filters/others.py` — `class:StripCommentsFilter` (lines 14-53) + +```python +class StripCommentsFilter: + + @staticmethod + def _process(tlist): + def get_next_comment(): + # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment) + + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. + m = re.search(r'((\r\n|\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: + return sql.Token(T.Whitespace, ' ') + + tidx, token = get_next_comment() + while token: + pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) + nidx, next_ = tlist.token_next(tidx, skip_ws=False) + # Replace by whitespace if prev and next exist and if they're not + # whitespaces. This doesn't apply if prev or next is a parenthesis. + if (prev_ is None or next_ is None + or prev_.is_whitespace or prev_.match(T.Punctuation, '(') + or next_.is_whitespace or next_.match(T.Punctuation, ')')): + # Insert a whitespace to ensure the following SQL produces + # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): + tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: + tlist.tokens[tidx] = _get_insert_token(token) + + tidx, token = get_next_comment() + + def process(self, stmt): + [self.process(sgroup) for sgroup in stmt.get_sublists()] + StripCommentsFilter._process(stmt) + return stmt +``` + +## `sqlparse/filters/others.py` — `function:StripCommentsFilter._process` (lines 16-48) + +```python + def _process(tlist): + def get_next_comment(): + # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment) + + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. + m = re.search(r'((\r\n|\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: + return sql.Token(T.Whitespace, ' ') + + tidx, token = get_next_comment() + while token: + pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) + nidx, next_ = tlist.token_next(tidx, skip_ws=False) + # Replace by whitespace if prev and next exist and if they're not + # whitespaces. This doesn't apply if prev or next is a parenthesis. + if (prev_ is None or next_ is None + or prev_.is_whitespace or prev_.match(T.Punctuation, '(') + or next_.is_whitespace or next_.match(T.Punctuation, ')')): + # Insert a whitespace to ensure the following SQL produces + # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): + tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: + tlist.tokens[tidx] = _get_insert_token(token) + + tidx, token = get_next_comment() +``` + +## `sqlparse/filters/others.py` — `function:StripCommentsFilter._process._get_insert_token` (lines 22-29) + +```python + def _get_insert_token(token): + """Returns either a whitespace or the line breaks from token.""" + # See issue484 why line breaks should be preserved. + m = re.search(r'((\r\n|\r|\n)+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: + return sql.Token(T.Whitespace, ' ') +``` + +## `tests/test_format.py` — `class:TestFormat` (lines 7-121) + +```python +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select (select 2)' + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") +``` + +## `tests/test_format.py` — `function:TestFormat.test_strip_ws` (lines 87-92) + +```python + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6ba9ecf7d8f59a95c370e15bea9b7f8027a83e2a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/task.json @@ -0,0 +1,53 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-509b1de3e2277ac89469", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-509b1de3e2277ac89469", + "project_id": "pyvul__andialbrecht__sqlparse", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "sqlparse/filters/others.py", + "tests/test_format.py" + ], + "patch_units": { + "before": [ + "class:StripCommentsFilter", + "function:StripCommentsFilter._process", + "function:StripCommentsFilter._process._get_insert_token", + "class:TestFormat", + "function:TestFormat.test_strip_ws" + ], + "after": [ + "class:StripCommentsFilter", + "function:StripCommentsFilter._process", + "function:StripCommentsFilter._process._get_insert_token", + "class:TestFormat", + "function:TestFormat.test_strip_comments_preserves_linebreak" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/c664adfff9814bfd1e1fc4a31d39c09670f6922169a6eece08e379990a08ede3/database", + "cache_key": "c664adfff9814bfd1e1fc4a31d39c09670f6922169a6eece08e379990a08ede3", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/f905aa560d25d9df93d5ef8127624a69bef5901a2e8181ea11788f4f9a5f28e1/database", + "cache_key": "f905aa560d25d9df93d5ef8127624a69bef5901a2e8181ea11788f4f9a5f28e1", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/90ed6594ba3674fc2a0e89347b62d03c9e66f5e3b12fc0258a34188f830a6f99/database", + "cache_key": "90ed6594ba3674fc2a0e89347b62d03c9e66f5e3b12fc0258a34188f830a6f99", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-509b1de3e2277ac89469/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-509b1de3e2277ac89469/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-509b1de3e2277ac89469/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d99dca626a68d113bce6f813d6927ac09a79f8ec --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/patch.diff @@ -0,0 +1,75 @@ +diff --git a/.github/semgrep-rules/insecure-unpack-archive.yml b/.github/semgrep-rules/insecure-unpack-archive.yml +new file mode 100644 +index 0000000..d40f645 +--- /dev/null ++++ b/.github/semgrep-rules/insecure-unpack-archive.yml +@@ -0,0 +1,21 @@ ++rules: ++ - id: insecure-shutil-unpack-archive-use ++ message: The Python 'shutil' shutil.extract_archive is vulnerable to ++ arbitrary file overwrites ++ languages: ++ - python ++ severity: ERROR ++ metadata: ++ category: security ++ technology: ++ - python ++ owasp: ++ - A06:2017 - Security Misconfiguration ++ - A05:2021 - Security Misconfiguration ++ cwe: ++ - "CWE-22: Improper Limitation of a Pathname to a Restricted Directory ++ ('Path Traversal')" ++ license: Commons Clause License Condition v1.0[LGPL-2.1-only] ++ pattern-either: ++ - pattern: | ++ shutil.unpack_archive(...) +\ No newline at end of file +diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml +index e16e8ba..80320c4 100644 +--- a/.github/workflows/semgrep.yml ++++ b/.github/workflows/semgrep.yml +@@ -26,9 +26,17 @@ jobs: + - uses: actions/checkout@v3 + + - run: semgrep --config auto --sarif --output semgrep.sarif ./guarddog ++ - run: semgrep --config .github/semgrep-rules --sarif --output semgrep-custom.sarif ./guarddog + + - name: Upload SARIF file for GitHub Advanced Security Dashboard + uses: github/codeql-action/upload-sarif@v2 + with: ++ category: semgrep-builtin + sarif_file: semgrep.sarif +- if: always() ++ ++ - name: Upload SARIF file for custom Semgrep rules for GitHub Advanced Security Dashboard ++ uses: github/codeql-action/upload-sarif@v2 ++ with: ++ category: semgrep-custom ++ sarif_file: semgrep-custom.sarif ++ +diff --git a/guarddog/scanners/package_scanner.py b/guarddog/scanners/package_scanner.py +index 79f216f..0647c9a 100644 +--- a/guarddog/scanners/package_scanner.py ++++ b/guarddog/scanners/package_scanner.py +@@ -1,7 +1,6 @@ + import json + import os +-import shutil +-import tarsafe # type: ignore ++import tarsafe # type:ignore + import tempfile + import requests + +@@ -160,5 +159,8 @@ class PackageScanner(Scanner): + with open(zippath, "wb") as f: + f.write(response.raw.read()) + +- shutil.unpack_archive(zippath, unzippedpath) +- os.remove(zippath) ++ if zippath.endswith('.tar.gz'): ++ tarsafe.open(zippath).extractall(unzippedpath) ++ os.remove(zippath) ++ else: ++ raise ValueError("unsupported archive extension: " + zippath) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..622394b89d14578338d87ba7152fe3be1f4b0479 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/post_context.md @@ -0,0 +1,191 @@ +# Patch-overlapping Python context after the fix + +## `guarddog/scanners/package_scanner.py` — `class:PackageScanner` (lines 12-166) + +```python +class PackageScanner(Scanner): + """ + Scans package for attack vectors based on source code and metadata rules + + Attributes: + analyzer (Analyzer): Analyzer for source code and metadata rules + """ + + def __init__(self) -> None: + self.analyzer = Analyzer() + super(Scanner) + + def scan_local(self, path, rules=None) -> dict: + """ + Scans local package + + Args: + path (str): path to package + rules (set, optional): Set of rule names to use. Defaults to all rules. + + Raises: + Exception: Analyzer exception + + Returns: + dict: Analyzer output with rules to results mapping + """ + + if rules is not None: + rules = set(rules) + + if os.path.exists(path): + if path.endswith('.tar.gz'): + with tempfile.TemporaryDirectory() as tmpdirname: + tarsafe.open(path).extractall(tmpdirname) + return self.analyzer.analyze_sourcecode(tmpdirname, rules=rules) + elif os.path.isdir(path): + return self.analyzer.analyze_sourcecode(path, rules=rules) + else: + raise Exception(f"Path {path} is not a directory nor a tar.gz archive.") + raise Exception(f"Path {path} does not exist.") + + def _scan_remote(self, name, base_dir, version=None, rules=None, write_package_info=False): + directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), base_dir) + file_path = os.path.join(directory, name) + + self.download_package(name, directory, version) + + package_info = get_package_info(name) + + results = self.analyzer.analyze(file_path, package_info, rules) + if write_package_info: + suffix = f"{name}-{version}" if version is not None else name + with open(os.path.join(results["path"], f'package_info-{suffix}.json'), "w") as file: + file.write(json.dumps(package_info)) + + return results + + def scan_remote(self, name, version=None, rules=None, base_dir=None, write_package_info=False): + """ + Scans a remote package + + Args: + * `name` (str): name of the package on PyPI + * `version` (str, optional): version of package (ex. 0.0.1). If not specified, the latest version is + assumed. + * `rules` (set, optional): Set of rule names to use. Defaults to all rules. + * `base_dir` (str, optional): directory to use to download package to. If not specified, a temporary folder + is created and cleaned up automatically. If not specified, the provided directory is not removed after the + scan. + * `write_package_info` (bool, default False): if set to true, the result of the PyPI metadata API is written + to a json file + + Raises: + Exception: Analyzer exception + + Returns: + dict: Analyzer output with rules to results mapping + """ + if (base_dir is not None): + return self._scan_remote(name, base_dir, version, rules, write_package_info) + + with tempfile.TemporaryDirectory() as tmpdirname: + # Directory to download compressed and uncompressed package + return self._scan_remote(name, tmpdirname, version, rules, write_package_info) + + def download_package(self, package_name, directory, version=None) -> None: + """Downloads the PyPI distribution for a given package and version + + Args: + package_name (str): name of the package + directory (str): directory to download package to + version (str): version of the package + + Raises: + Exception: "Received status code: " + + " from PyPI" + Exception: "Version " + version + " for package " + package_name + " doesn't exist." + Exception: "Compressed file for package does not exist." + Exception: "Error retrieving package: " + + Returns: + None + """ + + data = get_package_info(package_name) + releases = data["releases"] + + if version is None: + version = data["info"]["version"] + + if version in releases: + files = releases[version] + + url = None + file_extension = None + + for file in files: + # Store url to compressed package and appropriate file extension + if file["filename"].endswith(".tar.gz"): + url = file["url"] + file_extension = ".tar.gz" + + if file["filename"].endswith(".egg") or file["filename"].endswith(".whl") \ + or file["filename"].endswith(".zip"): + url = file["url"] + file_extension = ".zip" + + if url and file_extension: + # Path to compressed package + zippath = os.path.join(directory, package_name + file_extension) + unzippedpath = zippath.removesuffix(file_extension) + + self.download_compressed(url, zippath, unzippedpath) + else: + raise Exception(f"Compressed file for {package_name} does not exist on PyPI.") + else: + raise Exception("Version " + version + " for package " + package_name + " doesn't exist.") + + def download_compressed(self, url, zippath, unzippedpath): + """Downloads a compressed file and extracts it + + Args: + url (str): download link + zippath (str): path to download compressed file + unzippedpath (str): path to unzip compressed file + """ + + response = requests.get(url, stream=True) + + with open(zippath, "wb") as f: + f.write(response.raw.read()) + + if zippath.endswith('.tar.gz'): + tarsafe.open(zippath).extractall(unzippedpath) + os.remove(zippath) + else: + raise ValueError("unsupported archive extension: " + zippath) +``` + +## `guarddog/scanners/package_scanner.py` — `function:PackageScanner.download_compressed` (lines 148-166) + +```python + def download_compressed(self, url, zippath, unzippedpath): + """Downloads a compressed file and extracts it + + Args: + url (str): download link + zippath (str): path to download compressed file + unzippedpath (str): path to unzip compressed file + """ + + response = requests.get(url, stream=True) + + with open(zippath, "wb") as f: + f.write(response.raw.read()) + + if zippath.endswith('.tar.gz'): + tarsafe.open(zippath).extractall(unzippedpath) + os.remove(zippath) + else: + raise ValueError("unsupported archive extension: " + zippath) +``` + +## `guarddog/scanners/package_scanner.py` — `module:@3` (lines 3-3) + +```python +import tarsafe # type:ignore +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..b0011832b86f13b2dca80e7569c99e49d95b14cc --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/pre_context.md @@ -0,0 +1,197 @@ +# Patch-overlapping Python context before the fix + +## `guarddog/scanners/package_scanner.py` — `class:PackageScanner` (lines 13-164) + +```python +class PackageScanner(Scanner): + """ + Scans package for attack vectors based on source code and metadata rules + + Attributes: + analyzer (Analyzer): Analyzer for source code and metadata rules + """ + + def __init__(self) -> None: + self.analyzer = Analyzer() + super(Scanner) + + def scan_local(self, path, rules=None) -> dict: + """ + Scans local package + + Args: + path (str): path to package + rules (set, optional): Set of rule names to use. Defaults to all rules. + + Raises: + Exception: Analyzer exception + + Returns: + dict: Analyzer output with rules to results mapping + """ + + if rules is not None: + rules = set(rules) + + if os.path.exists(path): + if path.endswith('.tar.gz'): + with tempfile.TemporaryDirectory() as tmpdirname: + tarsafe.open(path).extractall(tmpdirname) + return self.analyzer.analyze_sourcecode(tmpdirname, rules=rules) + elif os.path.isdir(path): + return self.analyzer.analyze_sourcecode(path, rules=rules) + else: + raise Exception(f"Path {path} is not a directory nor a tar.gz archive.") + raise Exception(f"Path {path} does not exist.") + + def _scan_remote(self, name, base_dir, version=None, rules=None, write_package_info=False): + directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), base_dir) + file_path = os.path.join(directory, name) + + self.download_package(name, directory, version) + + package_info = get_package_info(name) + + results = self.analyzer.analyze(file_path, package_info, rules) + if write_package_info: + suffix = f"{name}-{version}" if version is not None else name + with open(os.path.join(results["path"], f'package_info-{suffix}.json'), "w") as file: + file.write(json.dumps(package_info)) + + return results + + def scan_remote(self, name, version=None, rules=None, base_dir=None, write_package_info=False): + """ + Scans a remote package + + Args: + * `name` (str): name of the package on PyPI + * `version` (str, optional): version of package (ex. 0.0.1). If not specified, the latest version is + assumed. + * `rules` (set, optional): Set of rule names to use. Defaults to all rules. + * `base_dir` (str, optional): directory to use to download package to. If not specified, a temporary folder + is created and cleaned up automatically. If not specified, the provided directory is not removed after the + scan. + * `write_package_info` (bool, default False): if set to true, the result of the PyPI metadata API is written + to a json file + + Raises: + Exception: Analyzer exception + + Returns: + dict: Analyzer output with rules to results mapping + """ + if (base_dir is not None): + return self._scan_remote(name, base_dir, version, rules, write_package_info) + + with tempfile.TemporaryDirectory() as tmpdirname: + # Directory to download compressed and uncompressed package + return self._scan_remote(name, tmpdirname, version, rules, write_package_info) + + def download_package(self, package_name, directory, version=None) -> None: + """Downloads the PyPI distribution for a given package and version + + Args: + package_name (str): name of the package + directory (str): directory to download package to + version (str): version of the package + + Raises: + Exception: "Received status code: " + + " from PyPI" + Exception: "Version " + version + " for package " + package_name + " doesn't exist." + Exception: "Compressed file for package does not exist." + Exception: "Error retrieving package: " + + Returns: + None + """ + + data = get_package_info(package_name) + releases = data["releases"] + + if version is None: + version = data["info"]["version"] + + if version in releases: + files = releases[version] + + url = None + file_extension = None + + for file in files: + # Store url to compressed package and appropriate file extension + if file["filename"].endswith(".tar.gz"): + url = file["url"] + file_extension = ".tar.gz" + + if file["filename"].endswith(".egg") or file["filename"].endswith(".whl") \ + or file["filename"].endswith(".zip"): + url = file["url"] + file_extension = ".zip" + + if url and file_extension: + # Path to compressed package + zippath = os.path.join(directory, package_name + file_extension) + unzippedpath = zippath.removesuffix(file_extension) + + self.download_compressed(url, zippath, unzippedpath) + else: + raise Exception(f"Compressed file for {package_name} does not exist on PyPI.") + else: + raise Exception("Version " + version + " for package " + package_name + " doesn't exist.") + + def download_compressed(self, url, zippath, unzippedpath): + """Downloads a compressed file and extracts it + + Args: + url (str): download link + zippath (str): path to download compressed file + unzippedpath (str): path to unzip compressed file + """ + + response = requests.get(url, stream=True) + + with open(zippath, "wb") as f: + f.write(response.raw.read()) + + shutil.unpack_archive(zippath, unzippedpath) + os.remove(zippath) +``` + +## `guarddog/scanners/package_scanner.py` — `function:PackageScanner.download_compressed` (lines 149-164) + +```python + def download_compressed(self, url, zippath, unzippedpath): + """Downloads a compressed file and extracts it + + Args: + url (str): download link + zippath (str): path to download compressed file + unzippedpath (str): path to unzip compressed file + """ + + response = requests.get(url, stream=True) + + with open(zippath, "wb") as f: + f.write(response.raw.read()) + + shutil.unpack_archive(zippath, unzippedpath) + os.remove(zippath) +``` + +## `guarddog/scanners/package_scanner.py` — `module:@3` (lines 3-3) + +```python +import shutil +``` + +## `guarddog/scanners/package_scanner.py` — `module:@4` (lines 4-4) + +```python +import tarsafe # type: ignore +``` + +## `guarddog/scanners/package_scanner.py` — `module:@5` (lines 5-5) + +```python +import tempfile +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3e56ff1e2b0e45ddae01ef581e56db8fc016c193 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-533cc1a8c090c7529184", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-533cc1a8c090c7529184", + "project_id": "pyvul__datadog__guarddog", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "guarddog/scanners/package_scanner.py" + ], + "patch_units": { + "before": [ + "class:PackageScanner", + "function:PackageScanner.download_compressed", + "module:@3", + "module:@4", + "module:@5" + ], + "after": [ + "class:PackageScanner", + "function:PackageScanner.download_compressed", + "module:@3" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/d89953758521586d96435a7da704e98ffc4107ed7c562192fe9596b789f1bb48/database", + "cache_key": "d89953758521586d96435a7da704e98ffc4107ed7c562192fe9596b789f1bb48", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/9a92ea79a245266699e4035c30c6294ac6259fa64585450ef258b71876772a02/database", + "cache_key": "9a92ea79a245266699e4035c30c6294ac6259fa64585450ef258b71876772a02", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/02a4e564cd723474324a76fa5fad904ce96ebfe6f7ca35d689363fc5eb694865/database", + "cache_key": "02a4e564cd723474324a76fa5fad904ce96ebfe6f7ca35d689363fc5eb694865", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-533cc1a8c090c7529184/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-533cc1a8c090c7529184/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-533cc1a8c090c7529184/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..911cbcf1d0ab96fd420da6ce615ddee98be3530a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/patch.diff @@ -0,0 +1,74 @@ +diff --git a/langchain/tools/jira/prompt.py b/langchain/tools/jira/prompt.py +index a50c373c9a..08f0602304 100644 +--- a/langchain/tools/jira/prompt.py ++++ b/langchain/tools/jira/prompt.py +@@ -25,11 +25,12 @@ JIRA_CATCH_ALL_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira API. + There are other dedicated tools for fetching all projects, and creating and searching for issues, + use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API. +- The input to this tool is line of python code that calls a function from atlassian-python-api's Jira API +- For example, to update the summary field of an issue, you would pass in the following string: +- self.jira.update_issue_field(key, {{"summary": "New summary"}}) ++ The input to this tool is a dictionary specifying a function from atlassian-python-api's Jira API, ++ as well as a list of arguments and dictionary of keyword arguments to pass into the function. ++ For example, to get all the users in a group, while increasing the max number of results to 100, you would ++ pass in the following dictionary: {{"function": "get_all_users_from_group", "args": ["group"], "kwargs": {{"limit":100}} }} + or to find out how many projects are in the Jira instance, you would pass in the following string: +- self.jira.projects() ++ {{"function": "projects"}} + For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html + """ + +diff --git a/langchain/utilities/jira.py b/langchain/utilities/jira.py +index 3f3719437e..f3fe4dfe3e 100644 +--- a/langchain/utilities/jira.py ++++ b/langchain/utilities/jira.py +@@ -188,10 +188,15 @@ class JiraAPIWrapper(BaseModel): + return self.confluence.create_page(**dict(params)) + + def other(self, query: str) -> str: +- context = {"self": self} +- exec(f"result = {query}", context) +- result = context["result"] +- return str(result) ++ try: ++ import json ++ except ImportError: ++ raise ImportError( ++ "json is not installed. Please install it with `pip install json`" ++ ) ++ params = json.loads(query) ++ jira_function = getattr(self.jira, params["function"]) ++ return jira_function(*params.get("args", []), **params.get("kwargs", {})) + + def run(self, mode: str, query: str) -> str: + if mode == "jql": +diff --git a/tests/integration_tests/utilities/test_jira_api.py b/tests/integration_tests/utilities/test_jira_api.py +index fa44a6014d..3a74e9e943 100644 +--- a/tests/integration_tests/utilities/test_jira_api.py ++++ b/tests/integration_tests/utilities/test_jira_api.py +@@ -41,3 +41,24 @@ def test_create_confluence_page() -> None: + output = jira.run("create_page", create_page_dict) + assert "type" in output + assert "page" in output ++ ++ ++def test_other() -> None: ++ """Non-exhaustive test for accessing other JIRA API methods""" ++ jira = JiraAPIWrapper() ++ issue_create_dict = """ ++ { ++ "function":"issue_create", ++ "kwargs": { ++ "fields": { ++ "summary": "Test Summary", ++ "description": "Test Description", ++ "issuetype": {"name": "Bug"}, ++ "project": {"key": "TP"} ++ } ++ } ++ } ++ """ ++ output = jira.run("other", issue_create_dict) ++ assert "id" in output ++ assert "key" in output diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..93834f7d7763dce75927d4b443de4c5eb9d773ed --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/post_context.md @@ -0,0 +1,259 @@ +# Patch-overlapping Python context after the fix + +## `langchain/tools/jira/prompt.py` — `module:@24` (lines 24-35) + +```python +JIRA_CATCH_ALL_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira API. + There are other dedicated tools for fetching all projects, and creating and searching for issues, + use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API. + The input to this tool is a dictionary specifying a function from atlassian-python-api's Jira API, + as well as a list of arguments and dictionary of keyword arguments to pass into the function. + For example, to get all the users in a group, while increasing the max number of results to 100, you would + pass in the following dictionary: {{"function": "get_all_users_from_group", "args": ["group"], "kwargs": {{"limit":100}} }} + or to find out how many projects are in the Jira instance, you would pass in the following string: + {{"function": "projects"}} + For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html + """ +``` + +## `langchain/utilities/jira.py` — `class:JiraAPIWrapper` (lines 17-213) + +```python +class JiraAPIWrapper(BaseModel): + """Wrapper for Jira API.""" + + jira: Any #: :meta private: + confluence: Any + jira_username: Optional[str] = None + jira_api_token: Optional[str] = None + jira_instance_url: Optional[str] = None + + operations: List[Dict] = [ + { + "mode": "jql", + "name": "JQL Query", + "description": JIRA_JQL_PROMPT, + }, + { + "mode": "get_projects", + "name": "Get Projects", + "description": JIRA_GET_ALL_PROJECTS_PROMPT, + }, + { + "mode": "create_issue", + "name": "Create Issue", + "description": JIRA_ISSUE_CREATE_PROMPT, + }, + { + "mode": "other", + "name": "Catch all Jira API call", + "description": JIRA_CATCH_ALL_PROMPT, + }, + { + "mode": "create_page", + "name": "Create confluence page", + "description": JIRA_CONFLUENCE_PAGE_CREATE_PROMPT, + }, + ] + + class Config: + """Configuration for this pydantic object.""" + + extra = Extra.forbid + + def list(self) -> List[Dict]: + return self.operations + + @root_validator() + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + jira_username = get_from_dict_or_env(values, "jira_username", "JIRA_USERNAME") + values["jira_username"] = jira_username + + jira_api_token = get_from_dict_or_env( + values, "jira_api_token", "JIRA_API_TOKEN" + ) + values["jira_api_token"] = jira_api_token + + jira_instance_url = get_from_dict_or_env( + values, "jira_instance_url", "JIRA_INSTANCE_URL" + ) + values["jira_instance_url"] = jira_instance_url + + try: + from atlassian import Confluence, Jira + except ImportError: + raise ImportError( + "atlassian-python-api is not installed. " + "Please install it with `pip install atlassian-python-api`" + ) + + jira = Jira( + url=jira_instance_url, + username=jira_username, + password=jira_api_token, + cloud=True, + ) + + confluence = Confluence( + url=jira_instance_url, + username=jira_username, + password=jira_api_token, + cloud=True, + ) + + values["jira"] = jira + values["confluence"] = confluence + + return values + + def parse_issues(self, issues: Dict) -> List[dict]: + parsed = [] + for issue in issues["issues"]: + key = issue["key"] + summary = issue["fields"]["summary"] + created = issue["fields"]["created"][0:10] + priority = issue["fields"]["priority"]["name"] + status = issue["fields"]["status"]["name"] + try: + assignee = issue["fields"]["assignee"]["displayName"] + except Exception: + assignee = "None" + rel_issues = {} + for related_issue in issue["fields"]["issuelinks"]: + if "inwardIssue" in related_issue.keys(): + rel_type = related_issue["type"]["inward"] + rel_key = related_issue["inwardIssue"]["key"] + rel_summary = related_issue["inwardIssue"]["fields"]["summary"] + if "outwardIssue" in related_issue.keys(): + rel_type = related_issue["type"]["outward"] + rel_key = related_issue["outwardIssue"]["key"] + rel_summary = related_issue["outwardIssue"]["fields"]["summary"] + rel_issues = {"type": rel_type, "key": rel_key, "summary": rel_summary} + parsed.append( + { + "key": key, + "summary": summary, + "created": created, + "assignee": assignee, + "priority": priority, + "status": status, + "related_issues": rel_issues, + } + ) + return parsed + + def parse_projects(self, projects: List[dict]) -> List[dict]: + parsed = [] + for project in projects: + id = project["id"] + key = project["key"] + name = project["name"] + type = project["projectTypeKey"] + style = project["style"] + parsed.append( + {"id": id, "key": key, "name": name, "type": type, "style": style} + ) + return parsed + + def search(self, query: str) -> str: + issues = self.jira.jql(query) + parsed_issues = self.parse_issues(issues) + parsed_issues_str = ( + "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) + ) + return parsed_issues_str + + def project(self) -> str: + projects = self.jira.projects() + parsed_projects = self.parse_projects(projects) + parsed_projects_str = ( + "Found " + str(len(parsed_projects)) + " projects:\n" + str(parsed_projects) + ) + return parsed_projects_str + + def issue_create(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + return self.jira.issue_create(fields=dict(params)) + + def page_create(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + return self.confluence.create_page(**dict(params)) + + def other(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + jira_function = getattr(self.jira, params["function"]) + return jira_function(*params.get("args", []), **params.get("kwargs", {})) + + def run(self, mode: str, query: str) -> str: + if mode == "jql": + return self.search(query) + elif mode == "get_projects": + return self.project() + elif mode == "create_issue": + return self.issue_create(query) + elif mode == "other": + return self.other(query) + elif mode == "create_page": + return self.page_create(query) + else: + raise ValueError(f"Got unexpected mode {mode}") +``` + +## `langchain/utilities/jira.py` — `function:JiraAPIWrapper.other` (lines 190-199) + +```python + def other(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + jira_function = getattr(self.jira, params["function"]) + return jira_function(*params.get("args", []), **params.get("kwargs", {})) +``` + +## `tests/integration_tests/utilities/test_jira_api.py` — `function:test_other` (lines 46-64) + +```python +def test_other() -> None: + """Non-exhaustive test for accessing other JIRA API methods""" + jira = JiraAPIWrapper() + issue_create_dict = """ + { + "function":"issue_create", + "kwargs": { + "fields": { + "summary": "Test Summary", + "description": "Test Description", + "issuetype": {"name": "Bug"}, + "project": {"key": "TP"} + } + } + } + """ + output = jira.run("other", issue_create_dict) + assert "id" in output + assert "key" in output +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..2af2a884043923444d32ba89cad5f7dddc49639e --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/pre_context.md @@ -0,0 +1,224 @@ +# Patch-overlapping Python context before the fix + +## `langchain/tools/jira/prompt.py` — `module:@24` (lines 24-34) + +```python +JIRA_CATCH_ALL_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira API. + There are other dedicated tools for fetching all projects, and creating and searching for issues, + use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API. + The input to this tool is line of python code that calls a function from atlassian-python-api's Jira API + For example, to update the summary field of an issue, you would pass in the following string: + self.jira.update_issue_field(key, {{"summary": "New summary"}}) + or to find out how many projects are in the Jira instance, you would pass in the following string: + self.jira.projects() + For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html + """ +``` + +## `langchain/utilities/jira.py` — `class:JiraAPIWrapper` (lines 17-208) + +```python +class JiraAPIWrapper(BaseModel): + """Wrapper for Jira API.""" + + jira: Any #: :meta private: + confluence: Any + jira_username: Optional[str] = None + jira_api_token: Optional[str] = None + jira_instance_url: Optional[str] = None + + operations: List[Dict] = [ + { + "mode": "jql", + "name": "JQL Query", + "description": JIRA_JQL_PROMPT, + }, + { + "mode": "get_projects", + "name": "Get Projects", + "description": JIRA_GET_ALL_PROJECTS_PROMPT, + }, + { + "mode": "create_issue", + "name": "Create Issue", + "description": JIRA_ISSUE_CREATE_PROMPT, + }, + { + "mode": "other", + "name": "Catch all Jira API call", + "description": JIRA_CATCH_ALL_PROMPT, + }, + { + "mode": "create_page", + "name": "Create confluence page", + "description": JIRA_CONFLUENCE_PAGE_CREATE_PROMPT, + }, + ] + + class Config: + """Configuration for this pydantic object.""" + + extra = Extra.forbid + + def list(self) -> List[Dict]: + return self.operations + + @root_validator() + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + jira_username = get_from_dict_or_env(values, "jira_username", "JIRA_USERNAME") + values["jira_username"] = jira_username + + jira_api_token = get_from_dict_or_env( + values, "jira_api_token", "JIRA_API_TOKEN" + ) + values["jira_api_token"] = jira_api_token + + jira_instance_url = get_from_dict_or_env( + values, "jira_instance_url", "JIRA_INSTANCE_URL" + ) + values["jira_instance_url"] = jira_instance_url + + try: + from atlassian import Confluence, Jira + except ImportError: + raise ImportError( + "atlassian-python-api is not installed. " + "Please install it with `pip install atlassian-python-api`" + ) + + jira = Jira( + url=jira_instance_url, + username=jira_username, + password=jira_api_token, + cloud=True, + ) + + confluence = Confluence( + url=jira_instance_url, + username=jira_username, + password=jira_api_token, + cloud=True, + ) + + values["jira"] = jira + values["confluence"] = confluence + + return values + + def parse_issues(self, issues: Dict) -> List[dict]: + parsed = [] + for issue in issues["issues"]: + key = issue["key"] + summary = issue["fields"]["summary"] + created = issue["fields"]["created"][0:10] + priority = issue["fields"]["priority"]["name"] + status = issue["fields"]["status"]["name"] + try: + assignee = issue["fields"]["assignee"]["displayName"] + except Exception: + assignee = "None" + rel_issues = {} + for related_issue in issue["fields"]["issuelinks"]: + if "inwardIssue" in related_issue.keys(): + rel_type = related_issue["type"]["inward"] + rel_key = related_issue["inwardIssue"]["key"] + rel_summary = related_issue["inwardIssue"]["fields"]["summary"] + if "outwardIssue" in related_issue.keys(): + rel_type = related_issue["type"]["outward"] + rel_key = related_issue["outwardIssue"]["key"] + rel_summary = related_issue["outwardIssue"]["fields"]["summary"] + rel_issues = {"type": rel_type, "key": rel_key, "summary": rel_summary} + parsed.append( + { + "key": key, + "summary": summary, + "created": created, + "assignee": assignee, + "priority": priority, + "status": status, + "related_issues": rel_issues, + } + ) + return parsed + + def parse_projects(self, projects: List[dict]) -> List[dict]: + parsed = [] + for project in projects: + id = project["id"] + key = project["key"] + name = project["name"] + type = project["projectTypeKey"] + style = project["style"] + parsed.append( + {"id": id, "key": key, "name": name, "type": type, "style": style} + ) + return parsed + + def search(self, query: str) -> str: + issues = self.jira.jql(query) + parsed_issues = self.parse_issues(issues) + parsed_issues_str = ( + "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) + ) + return parsed_issues_str + + def project(self) -> str: + projects = self.jira.projects() + parsed_projects = self.parse_projects(projects) + parsed_projects_str = ( + "Found " + str(len(parsed_projects)) + " projects:\n" + str(parsed_projects) + ) + return parsed_projects_str + + def issue_create(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + return self.jira.issue_create(fields=dict(params)) + + def page_create(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + return self.confluence.create_page(**dict(params)) + + def other(self, query: str) -> str: + context = {"self": self} + exec(f"result = {query}", context) + result = context["result"] + return str(result) + + def run(self, mode: str, query: str) -> str: + if mode == "jql": + return self.search(query) + elif mode == "get_projects": + return self.project() + elif mode == "create_issue": + return self.issue_create(query) + elif mode == "other": + return self.other(query) + elif mode == "create_page": + return self.page_create(query) + else: + raise ValueError(f"Got unexpected mode {mode}") +``` + +## `langchain/utilities/jira.py` — `function:JiraAPIWrapper.other` (lines 190-194) + +```python + def other(self, query: str) -> str: + context = {"self": self} + exec(f"result = {query}", context) + result = context["result"] + return str(result) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f184630149b3fbc6a2f50bc09057bc9383cc7840 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-5cffd45f7550a060e2cf", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-5cffd45f7550a060e2cf", + "project_id": "pyvul__langchain-ai__langchain", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "langchain/tools/jira/prompt.py", + "langchain/utilities/jira.py", + "tests/integration_tests/utilities/test_jira_api.py" + ], + "patch_units": { + "before": [ + "module:@24", + "class:JiraAPIWrapper", + "function:JiraAPIWrapper.other" + ], + "after": [ + "module:@24", + "class:JiraAPIWrapper", + "function:JiraAPIWrapper.other", + "function:test_other" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/3ab8cf98f4a2899679e1ccfc6d8b6769f285e59934eff877d428595b1cf09283/database", + "cache_key": "3ab8cf98f4a2899679e1ccfc6d8b6769f285e59934eff877d428595b1cf09283", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/570592d3967d4c75356a31e69fc7187b0a0a35a42386694dabb9294afa0bd076/database", + "cache_key": "570592d3967d4c75356a31e69fc7187b0a0a35a42386694dabb9294afa0bd076", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/58f505d588f122e64038f644c96726c3ad80ad431e4de1fab548891ace4a6573/database", + "cache_key": "58f505d588f122e64038f644c96726c3ad80ad431e4de1fab548891ace4a6573", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-5cffd45f7550a060e2cf/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-5cffd45f7550a060e2cf/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-5cffd45f7550a060e2cf/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6ccb63253a8f23c1d6ca736df58b822346e6153b --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/patch.diff @@ -0,0 +1,54 @@ +diff --git a/horovod/runner/js_run.py b/horovod/runner/js_run.py +index d25f5dd3..5be68011 100644 +--- a/horovod/runner/js_run.py ++++ b/horovod/runner/js_run.py +@@ -126,7 +126,12 @@ def generate_jsrun_rankfile(settings, path=None): + slots=settings.num_proc)) + + # Generate rankfile +- path = tempfile.mktemp() if path is None else path ++ # using mkstemp here instead of insecure mktemp. ++ # note that the caller is responsible for cleaning up this file ++ if path is None: ++ fd, path = tempfile.mkstemp() ++ fd.close() ++ + with open(path, 'w') as tmp: + tmp.write('overlapping_rs: allow\n') + tmp.write('cpu_index_using: logical\n') +diff --git a/test/single/test_run.py b/test/single/test_run.py +index f7a82cd0..5f506f9f 100644 +--- a/test/single/test_run.py ++++ b/test/single/test_run.py +@@ -640,7 +640,7 @@ class RunTests(unittest.TestCase): + test(("HYDRA build details:\n" + " Version: 3.3a2\n" + " Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL) +- ++ + test("Intel(R) MPI", _IMPI_IMPL) + + test("Unknown MPI v1.00", _UNKNOWN_IMPL) +diff --git a/test/utils/common.py b/test/utils/common.py +index 038ed1ea..77871c45 100644 +--- a/test/utils/common.py ++++ b/test/utils/common.py +@@ -112,15 +112,12 @@ def tempdir(): + + @contextlib.contextmanager + def temppath(): +- path = tempfile.mktemp() ++ dir_path = tempfile.TemporaryDirectory() ++ path = os.path.join(dir_path.name,'temp_test_file') + try: + yield path + finally: +- if os.path.exists(path): +- if os.path.isfile(path): +- os.remove(path) +- else: +- shutil.rmtree(path) ++ dir_path.cleanup() + + + @contextlib.contextmanager diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..14e7cb1a6b6a729d553b5a72d253432524e3f23b --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/post_context.md @@ -0,0 +1,1227 @@ +# Patch-overlapping Python context after the fix + +## `horovod/runner/js_run.py` — `function:generate_jsrun_rankfile` (lines 96-151) + +```python +def generate_jsrun_rankfile(settings, path=None): + """ + Generates rankfile to use with jsrun. + It splits the cores among the processes, which leads to best performance according to experiments. + + Args: + settings: Settings for running jsrun. + Note: settings.num_proc and settings.hosts must not be None. + path: Optional path of the rankfile. + Note: this file will be overwritten. + """ + cpu_per_gpu = (lsf.LSFUtils.get_num_cores() * lsf.LSFUtils.get_num_threads()) // lsf.LSFUtils.get_num_gpus() + host_list = (x.split(':') for x in settings.hosts.split(',')) + + # Verify and truncate host list if necessary + validated_list = [] + remaining_slots = settings.num_proc + for host, slots in host_list: + slots = int(slots) + if slots > lsf.LSFUtils.get_num_gpus(): + raise ValueError('Invalid host input, slot count for host \'{host}:{slots}\' is greater ' + 'than number of GPUs per host \'{gpus}\'.'.format( + host=host, slots=slots, gpus=lsf.LSFUtils.get_num_gpus())) + needed_slots = min(slots, remaining_slots) + validated_list.append((host, needed_slots)) + remaining_slots -= needed_slots + if remaining_slots == 0: + break + if remaining_slots != 0: + raise ValueError('Not enough slots on the hosts to fulfill the {slots} requested.'.format( + slots=settings.num_proc)) + + # Generate rankfile + # using mkstemp here instead of insecure mktemp. + # note that the caller is responsible for cleaning up this file + if path is None: + fd, path = tempfile.mkstemp() + fd.close() + + with open(path, 'w') as tmp: + tmp.write('overlapping_rs: allow\n') + tmp.write('cpu_index_using: logical\n') + rank = 0 + for host, slots in validated_list: + cpu_val = 0 + tmp.write('\n') + for s in range(slots): + tmp.write('rank: {rank}: {{ hostname: {host}; cpu: {{{scpu}-{ecpu}}} ; gpu: * ; mem: * }}\n'.format( + rank=rank, + host=host, + scpu=cpu_val, + ecpu=cpu_val + cpu_per_gpu - 1 + )) + rank += 1 + cpu_val += cpu_per_gpu + return path +``` + +## `test/single/test_run.py` — `class:RunTests` (lines 53-1168) + +```python +class RunTests(unittest.TestCase): + """ + Tests for horovod.runner. + """ + + def __init__(self, *args, **kwargs): + super(RunTests, self).__init__(*args, **kwargs) + warnings.simplefilter('module') + + def test_params_args(self): + with override_args('horovodrun', '-np', '2', + '--fusion-threshold-mb', '10', + '--cycle-time-ms', '20', + '--cache-capacity', '512', + '--hierarchical-allreduce', + '--hierarchical-allgather'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_FUSION_THRESHOLD), str(10 * 1024 * 1024)) + self.assertEqual(env.get(config_parser.HOROVOD_CYCLE_TIME), '20.0') + self.assertEqual(env.get(config_parser.HOROVOD_CACHE_CAPACITY), '512') + self.assertEqual(env.get(config_parser.HOROVOD_HIERARCHICAL_ALLREDUCE), '1') + self.assertEqual(env.get(config_parser.HOROVOD_HIERARCHICAL_ALLGATHER), '1') + + def test_autotune_args(self): + with override_args('horovodrun', '-np', '2', + '--autotune', + '--autotune-log-file', '/tmp/autotune.txt', + '--autotune-warmup-samples', '1', + '--autotune-steps-per-sample', '5', + '--autotune-bayes-opt-max-samples', '10', + '--autotune-gaussian-process-noise', '0.2'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE), '1') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_LOG), '/tmp/autotune.txt') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_WARMUP_SAMPLES), '1') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_STEPS_PER_SAMPLE), '5') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_BAYES_OPT_MAX_SAMPLES), '10') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_GAUSSIAN_PROCESS_NOISE), '0.2') + + def test_autotuning_with_fixed_param(self): + with override_args('horovodrun', '-np', '2', + '--autotune', + '--cache-capacity', '1024', + '--no-hierarchical-allgather'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertNotIn(config_parser.HOROVOD_FUSION_THRESHOLD, env) + self.assertNotIn(config_parser.HOROVOD_CYCLE_TIME, env) + self.assertEqual(env.get(config_parser.HOROVOD_CACHE_CAPACITY), '1024') + self.assertNotIn(config_parser.HOROVOD_HIERARCHICAL_ALLREDUCE, env) + self.assertEqual(env.get(config_parser.HOROVOD_HIERARCHICAL_ALLGATHER), '0') + + def test_timeline_args(self): + with override_args('horovodrun', '-np', '2', + '--timeline-filename', '/tmp/timeline.json', + '--timeline-mark-cycles'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_TIMELINE), '/tmp/timeline.json') + self.assertEqual(env.get(config_parser.HOROVOD_TIMELINE_MARK_CYCLES), '1') + + def test_stall_check_args(self): + with override_args('horovodrun', '-np', '2', + '--no-stall-check'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_STALL_CHECK_DISABLE), '1') + + with override_args('horovodrun', '-np', '2', + '--stall-check-warning-time-seconds', '10', + '--stall-check-shutdown-time-seconds', '20'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertNotIn(config_parser.HOROVOD_STALL_CHECK_DISABLE, env) + self.assertEqual(env.get(config_parser.HOROVOD_STALL_CHECK_TIME_SECONDS), '10') + self.assertEqual(env.get(config_parser.HOROVOD_STALL_SHUTDOWN_TIME_SECONDS), '20') + + def test_library_args(self): + with override_args('horovodrun', '-np', '2', + '--mpi-threads-disable', + '--num-nccl-streams', '2', + '--thread-affinity', '1', + '--gloo-timeout-seconds', '60'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_MPI_THREADS_DISABLE), '1') + self.assertEqual(env.get(config_parser.HOROVOD_NUM_NCCL_STREAMS), '2') + self.assertEqual(env.get(config_parser.HOROVOD_THREAD_AFFINITY), '1') + self.assertEqual(env.get(config_parser.HOROVOD_GLOO_TIMEOUT_SECONDS), '60') + + def test_library_env_override(self): + """Tests that environment variables override arg defaults.""" + with override_args('horovodrun', '-np', '2'): + args = parse_args() + env = { + 'HOROVOD_GLOO_TIMEOUT_SECONDS': '1800', + } + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_GLOO_TIMEOUT_SECONDS), '1800') + + def test_logging_args(self): + with override_args('horovodrun', '-np', '2', + '--log-level', 'INFO', + '--log-hide-timestamp'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_LOG_LEVEL), 'INFO') + self.assertEqual(env.get(config_parser.HOROVOD_LOG_HIDE_TIME), '1') + + def test_config_file(self): + config_filename = os.path.join(os.path.dirname(__file__), 'data/config.test.yaml') + with override_args('horovodrun', '-np', '2', + '--config-file', config_filename): + args = parse_args() + + self.assertTrue(args.use_gloo) + + # Params + self.assertEqual(args.fusion_threshold_mb, 32) + self.assertEqual(args.cycle_time_ms, 10) + self.assertEqual(args.cache_capacity, 2048) + self.assertTrue(args.hierarchical_allreduce) + self.assertTrue(args.hierarchical_allgather) + + # Autotune + self.assertTrue(args.autotune) + self.assertEqual(args.autotune_log_file, 'horovod_autotune_log.txt') + self.assertEqual(args.autotune_warmup_samples, 5) + self.assertEqual(args.autotune_steps_per_sample, 20) + self.assertEqual(args.autotune_bayes_opt_max_samples, 50) + self.assertEqual(args.autotune_gaussian_process_noise, 0.9) + + # Timeline + self.assertEqual(args.timeline_filename, 'horovod_timeline.json') + self.assertTrue(args.timeline_mark_cycles) + + # Stall Check + self.assertFalse(args.no_stall_check) + self.assertEqual(args.stall_check_warning_time_seconds, 120) + self.assertEqual(args.stall_check_shutdown_time_seconds, 240) + + # Library Options + self.assertTrue(args.mpi_threads_disable) + self.assertEqual(args.num_nccl_streams, 2) + self.assertEqual(args.thread_affinity, 1) + self.assertEqual(args.gloo_timeout_seconds, 60) + + # Logging + self.assertEqual(args.log_level, 'INFO') + self.assertFalse(args.log_with_timestamp) + + def test_config_file_override_args(self): + config_filename = os.path.join(os.path.dirname(__file__), 'data/config.test.yaml') + with override_args('horovodrun', '-np', '2', + '--fusion-threshold-mb', '256', + '--config-file', config_filename, + '--cycle-time-ms', '20',): + args = parse_args() + self.assertEqual(args.fusion_threshold_mb, 256) + self.assertEqual(args.cycle_time_ms, 20) + + def test_validate_config_args(self): + with override_args('horovodrun', '-np', '2', + '--fusion-threshold-mb', '-1'): + with pytest.raises(ValueError): + parse_args() + + # test_on_event tests in_thread as well, but it does not test args + def test_in_thread_args(self): + fn = mock.Mock() + thread = in_thread(fn, args=(1,)) + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once_with(1) + + fn = mock.Mock() + thread = in_thread(fn, args=(1, 2)) + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once_with(1, 2) + + fn = mock.Mock() + thread = in_thread(fn, args=(1, 2), silent=True) + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once_with(1, 2) + + fn = mock.Mock() + with pytest.raises(ValueError, match="^args must be a tuple, not <(class|type) 'int'>, " + "for a single argument use \\(arg,\\)$"): + in_thread(fn, args=1) + fn.assert_not_called() + + def test_on_event(self): + # a happy run without args and stop event + event = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + + # a happy run with args but without stop event + event = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn, ('a', 1)) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + fn.assert_called_once_with('a', 1) + + # a happy run with stop event but unused + event = threading.Event() + stop = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn, stop=stop, check_stop_interval_s=0.01) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + stop.set() + time.sleep(0.1) + fn.assert_called_once() + + # stop the thread before we set the event + event = threading.Event() + stop = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn, stop=stop, check_stop_interval_s=0.01) + fn.assert_not_called() + stop.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_not_called() + event.set() + time.sleep(0.1) + fn.assert_not_called() + + # test with exception + def exception(): + raise Exception("Test Exception") + + event = threading.Event() + fn = mock.Mock(side_effect=exception) + thread = on_event(event, fn) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + + # test with exception but silent + event = threading.Event() + fn = mock.Mock(side_effect=exception) + thread = on_event(event, fn) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + + # test None event + event = None + fn = mock.Mock() + with pytest.raises(ValueError, match="^Event must not be None$"): + on_event(event, fn) + fn.assert_not_called() + + # test non-tuple args + event = threading.Event() + fn = mock.Mock() + with pytest.raises(ValueError, match="^args must be a tuple, not <(class|type) 'int'>, " + "for a single argument use \\(arg,\\)$"): + on_event(event, fn, args=1) + fn.assert_not_called() + + # test None stop and non-daemon + event = threading.Event() + fn = mock.Mock() + with pytest.raises(ValueError, match="^Stop event must be given for non-daemon event thread$"): + on_event(event, fn, stop=None, daemon=False) + fn.assert_not_called() + + def test_prefix_connection(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:first line\n' + '[123]:second line\n' + '[123]:more lines\n') + + def test_prefix_connection_with_unicode(self): + string = '∀∁∂∃∄∅∆∇∈∉∊∋∌∍∎∏∐∑\n⌚⌛⛄✅…\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:∀∁∂∃∄∅∆∇∈∉∊∋∌∍∎∏∐∑\n' + '[123]:⌚⌛⛄✅…\n') + + def test_prefix_connection_with_multibyte_unicode(self): + block = '█▓▒░▒▓'*1000 + string = block + '\n' + block + '\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:' + block + '\n' + + '[123]:' + block + '\n') + + def test_prefix_connection_with_timestamp(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection_with_timestamp( + string, prefix='prefix', index=123, + expected='Mon Jan 20 12:00:01 2020[123]:first line\n' + 'Mon Jan 20 12:00:02 2020[123]:second line\n' + 'Mon Jan 20 12:00:03 2020[123]:more lines\n' + ) + + def test_prefix_connection_with_timestamp_without_index(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection_with_timestamp(string, prefix=None, index=None, + expected=string) + + def test_prefix_connection_without_trailing_newline(self): + string = 'first line\nsecond line\nmore lines' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:first line\n' + '[123]:second line\n' + '[123]:more lines') + + def test_prefix_connection_without_index(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection(string, prefix='prefix', index=None, expected=string) + + def test_prefix_connection_without_prefix(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection(string, prefix=None, index=123, expected=string) + + def test_prefix_connection_with_carriage_return(self): + string = 'first line\rfirst line again\nsecond line\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:first line\r' + '[123]:first line again\n' + '[123]:second line\n') + + def test_prefix_connection_with_carriage_return_without_index(self): + string = 'first line\rfirst line again\nsecond line\n' + self.do_test_prefix_connection(string, prefix='prefix', index=None, expected=string) + + def test_prefix_connection_with_carriage_return_without_prefix(self): + string = 'first line\rfirst line again\nsecond line\n' + self.do_test_prefix_connection(string, prefix=None, index=123, expected=string) + + def do_test_prefix_connection(self, string, prefix, index, expected, timestamp=False): + # create a Pipe Connection and populate it with string + (connection, w) = multiprocessing.get_context('spawn').Pipe(duplex=False) + with os.fdopen(w.fileno(), 'wt', encoding='utf8', newline='', closefd=False) as stream: + stream.write(string) + w.close() + + dst = io.StringIO() + safe_shell_exec.prefix_connection(connection, dst, prefix=prefix, index=index, + prefix_output_with_timestamp=timestamp) + self.assertEqual(expected, dst.getvalue()) + + def do_test_prefix_connection_with_timestamp(self, string_or_connection, prefix, index, expected): + # control the time used to prepend the timestamp + class MockTime: + def __init__(self): + # start at 2020-01-20 12:00:00 + self._time = 1579521600 + + def time(self, seconds): + from time import gmtime + self._time = self._time + 1 + return gmtime(self._time) + + with mock.patch('horovod.runner.common.util.safe_shell_exec.time.localtime', + side_effect=MockTime().time): + self.do_test_prefix_connection(string_or_connection, prefix, index, expected, timestamp=True) + + def test_prefix_connection_does_stream(self): + index = 123 + prefix = 'prefix' + expected = '[123]:first line\r' \ + '[123]:first line again\n' \ + '[123]:second line\n' \ + '[123]:more lines' + + timeout = 0.2 + barrier = multiprocessing.Barrier(2, timeout=timeout) + + def writer(write_connection): + def write(stream, text): + stream.write(text) + logging.info('wrote: {}'.format(text)) + stream.flush() + + # are we expecting the reader to read something + logging.info('waiting for reader') + if '\r' in text or '\n' in text: + # yes, barrier should not timeout + try: + barrier.wait() + except threading.BrokenBarrierError: + self.fail('reader side should have read something from the stream') + else: + # no, barrier should timeout + try: + barrier.wait() + self.fail('reader side should not have read anything from the stream') + except threading.BrokenBarrierError: + logging.info('reader did not read') + barrier.reset() + pass + logging.info('continuing writing') + + try: + with os.fdopen(write_connection.fileno(), 'wt', encoding='utf8', newline='', closefd=False) as stream: + for text in ['first line\r', + 'first ', 'line ', 'again\n', + 'second line\nmore ', 'lines']: + write(stream, text) + finally: + write_connection.close() + + actual = [] + do_read = True + + def reader(read_connection): + try: + while do_read: + text = os.read(read_connection.fileno(), 1000) + if not text: + break + text = text.decode('utf8') + actual.append(text) + logging.info('read: {}'.format(text)) + logging.info('waiting for writer') + try: + barrier.wait() + except threading.BrokenBarrierError as e: + if do_read: + raise e + break + logging.info('continuing reading') + finally: + read_connection.close() + + # one thread writes into the w side of this pipe + # prefix_connection reads on the other end of this pipe + (connection, w) = multiprocessing.get_context('spawn').Pipe(duplex=False) + writer_thread = in_thread(writer, (w,)) + + # prefix_connection writes to the write side of this Pipe (opened as a text stream) + # another thread reads from the r side of this pipe + (r, dst_con) = multiprocessing.get_context('spawn').Pipe(duplex=False) + reader_thread = in_thread(reader, (r,)) + + with os.fdopen(dst_con.fileno(), 'wt', encoding='utf8', newline='', closefd=False) as dst: + safe_shell_exec.prefix_connection(connection, dst, prefix=prefix, index=index, + prefix_output_with_timestamp=False) + + writer_thread.join(2*timeout) + do_read = False + reader_thread.join(2*timeout) + + self.assertEqual(expected, ''.join(actual)) + + def test_safe_shell_exec_captures_stdout(self): + self.do_test_safe_shell_exec('echo hello', 0, 'hello\n', '') + + def test_safe_shell_exec_captures_stderr(self): + self.do_test_safe_shell_exec('echo hello >&2', 0, '', 'hello\n') + + def test_safe_shell_exec_captures_last_line_wo_eol(self): + cmd = 'bash -c "echo -e -n \\"hello\nstdout\\"; echo -e -n \\"hello\nstderr\\" >&2"' + self.do_test_safe_shell_exec(cmd, 0, 'hello\nstdout', 'hello\nstderr') + + def test_safe_shell_exec_returns_exit_code(self): + self.do_test_safe_shell_exec('false', 1, '', '') + + @pytest.mark.skip(reason='https://github.com/horovod/horovod/issues/1993') + def test_safe_shell_exec_interrupts_on_event(self): + # interrupt execute in one second + interrupt = threading.Event() + interrupt_delay = 1.0 + delay(lambda: interrupt.set(), interrupt_delay) + + sleep = interrupt_delay + safe_shell_exec.GRACEFUL_TERMINATION_TIME_S + 2.0 + start = time.time() + self.do_test_safe_shell_exec('sleep {}'.format(sleep), 143, '', None, interrupt) + duration = time.time() - start + + self.assertGreaterEqual(duration, interrupt_delay) + self.assertLess(duration, sleep - 1.0, 'sleep should not finish') + + def test_safe_shell_exec_interrupts_on_parent_shutdown(self): + sleep = 20 + parent_script = os.path.join(os.path.dirname(__file__), 'data/run_safe_shell_exec.py') + child_script = os.path.join(os.path.dirname(__file__), 'data/sleep.py') + + def get_pid(logfile): + # Wait until the script has written its PID to the logfile + wait(lambda: os.path.exists(logfile), timeout=5) + with open(logfile, 'r') as f: + return int(f.read()) + + with temppath() as parent_logfile, temppath() as child_logfile: + # It's important that this executes in an entirely different interpreter with as little shared + # state as possible, to avoid issues with the semaphore tracker. + cmd = ' '.join([sys.executable, parent_script, parent_logfile, child_script, str(sleep), child_logfile]) + p = subprocess.Popen(cmd, shell=True) + + parent = psutil.Process(get_pid(parent_logfile)) + child = psutil.Process(get_pid(child_logfile)) + + self.assertTrue(parent.is_running()) + self.assertTrue(child.is_running()) + + # Hard kill the parent process + parent.kill() + parent.wait(timeout=safe_shell_exec.GRACEFUL_TERMINATION_TIME_S) + p.wait() + + # Child process will exit when pipe breaks + child.wait(timeout=2 * safe_shell_exec.GRACEFUL_TERMINATION_TIME_S + 1) + + self.assertFalse(parent.is_running()) + self.assertFalse(child.is_running()) + + def do_test_safe_shell_exec(self, cmd, expected_exit_code, expected_stdout, expected_stderr, event=None): + stdout = io.StringIO() + stderr = io.StringIO() + res = safe_shell_exec.execute(cmd, stdout=stdout, stderr=stderr, events=[event] if event else None) + self.assertEqual(expected_exit_code, res) + if expected_stdout is not None: + self.assertEqual(expected_stdout, stdout.getvalue()) + if expected_stderr is not None: + self.assertEqual(expected_stderr, stderr.getvalue()) + + def test_hash(self): + hash = _hash("test string") + self.assertEqual(hash, '6f8db599de986fab7a21625b7916589c') + + def test_host_hash(self): + hash = host_hash() + salted = host_hash('salt') + empty_salted = host_hash('') + + self.assertNotEqual(salted, hash) + self.assertEqual(empty_salted, hash) + + def test_get_mpi_implementation(self): + def test(output, expected, exit_code=0): + ret = (output, exit_code) if output is not None else None + env = {'VAR': 'val'} + with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m: + implementation = _get_mpi_implementation(env) + self.assertEqual(expected, implementation) + m.assert_called_once_with('mpirun --version', env) + + test(("mpirun (Open MPI) 2.1.1\n" + "Report bugs to http://www.open-mpi.org/community/help/\n"), _OMPI_IMPL) + + test("OpenRTE", _OMPI_IMPL) + + test("IBM Spectrum MPI", _SMPI_IMPL) + + test(("HYDRA build details:\n" + " Version: 3.3a2\n" + " Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL) + + test("Intel(R) MPI", _IMPI_IMPL) + + test("Unknown MPI v1.00", _UNKNOWN_IMPL) + + test("output", exit_code=1, expected=_MISSING_IMPL) + + test(None, _MISSING_IMPL) + + def test_run_controller(self): + def test(use_gloo, use_mpi, use_js, + gloo_is_built, mpi_is_built, + lsf_exists, jsrun_installed, + expected, exception): + gloo_run = MagicMock() + mpi_run = MagicMock() + js_run = MagicMock() + + with is_built(gloo_is_built, mpi_is_built): + with lsf_and_jsrun(lsf_exists, jsrun_installed): + if exception is not None: + with pytest.raises(ValueError, match=exception) as e: + run_controller(use_gloo, gloo_run, use_mpi, mpi_run, use_js, js_run, verbosity=2) + return + run_controller(use_gloo, gloo_run, use_mpi, mpi_run, use_js, js_run, verbosity=2) + + if expected == "gloo": + gloo_run.assert_called_once() + mpi_run.assert_not_called() + js_run.assert_not_called() + elif expected == "mpi": + gloo_run.assert_not_called() + mpi_run.assert_called_once() + js_run.assert_not_called() + elif expected == "js": + gloo_run.assert_not_called() + mpi_run.assert_not_called() + js_run.assert_called_once() + else: + raise ValueError("unsupported framework: {}".format(expected)) + + bool_values = [False, True] + bool_values_and_none = [None, False, True] + + for use_gloo, use_mpi, use_js, \ + gloo_is_built, mpi_is_built, \ + lsf_exists, jsrun_installed in \ + itertools.product(bool_values_and_none, bool_values_and_none, bool_values_and_none, + bool_values, bool_values, + bool_values, bool_values): + + expected = exception = None + if use_gloo: + if gloo_is_built: + expected = 'gloo' + else: + exception = r'^Gloo support has not been built\. If this is not expected, ensure CMake is installed ' \ + r'and reinstall Horovod with HOROVOD_WITH_GLOO=1 to debug the build error\.$' + elif use_mpi: + if mpi_is_built: + expected = 'mpi' + else: + exception = r'^MPI support has not been built\. If this is not expected, ensure MPI is installed ' \ + r'and reinstall Horovod with HOROVOD_WITH_MPI=1 to debug the build error\.$' + elif use_js: + if mpi_is_built: + if lsf_exists: + expected = 'js' + else: + exception = 'Horovod did not detect an LSF job. The jsrun launcher can only be used in that environment. ' \ + 'Please, pick a different launcher for other environments.' + else: + exception = r'^MPI support has not been built\. If this is not expected, ensure MPI is installed ' \ + r'and reinstall Horovod with HOROVOD_WITH_MPI=1 to debug the build error\.$' + elif mpi_is_built: + if lsf_exists and jsrun_installed: + expected = 'js' + else: + expected = 'mpi' + elif gloo_is_built: + expected = 'gloo' + else: + exception = r'Neither MPI nor Gloo support has been built\. Try reinstalling Horovod ensuring that ' \ + r'either MPI is installed \(MPI\) or CMake is installed \(Gloo\)\.' + + test(use_gloo, use_mpi, use_js, + gloo_is_built, mpi_is_built, + lsf_exists, jsrun_installed, + expected, exception) + + """ + Minimal mpi_run settings for tests. + """ + minimal_settings = hvd_settings.Settings( + verbose=0, + num_proc=2, + hosts='localhost:2', + run_func_mode=True + ) + + """ + Tests mpi_run with minimal settings. + """ + def test_mpi_run_minimal(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute: + mpi_run(settings, None, {}, cmd) + + # call the mocked _get_mpi_implementation_flags method + mpi_flags, binding_args, mpi = horovod.runner.mpi_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + if _IMPI_IMPL == mpi: + expected_cmd = ('mpirun ' + '-l -n 2 -hosts localhost ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(binding_args=' '.join(binding_args), mpi_flags=' '.join(mpi_flags)) + else: + expected_cmd = ('mpirun ' + '--allow-run-as-root --tag-output ' + '-np 2 -H localhost:2 ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(binding_args=' '.join(binding_args), mpi_flags=' '.join(mpi_flags)) + + # remove PYTHONPATH from execute's env + # we cannot know the exact value of that env variable + # we test right handling of PYTHONPATH in test_mpi_run_*pythonpath* below + self.assertIn('env', execute.call_args.kwargs) + if 'PYTHONPATH' in execute.call_args.kwargs['env']: + execute.call_args.kwargs['env'].pop('PYTHONPATH') + + expected_env = {'PATH': os.environ.get('PATH')} + execute.assert_called_once_with(expected_cmd, env=expected_env, stdout=None, stderr=None) + + """ + Tests mpi_run on a large cluster. + """ + def test_mpi_run_on_large_cluster(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = copy.copy(self.minimal_settings) + settings.hosts = ','.join(['localhost:1'] * large_cluster_threshold) + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute: + mpi_run(settings, None, {}, cmd) + + # call the mocked _get_mpi_implementation_flags method + mpi_flags, binding_args, mpi = horovod.runner.mpi_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + if _IMPI_IMPL == mpi: + expected_cmd = ('mpirun ' + '-l -n 2 -ppn 1 -hosts {hosts} ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(hosts=settings.hosts, binding_args=' '.join(binding_args), + mpi_flags=' '.join(mpi_flags)) + else: + mpi_flags.append('-mca plm_rsh_no_tree_spawn true') + mpi_flags.append('-mca plm_rsh_num_concurrent {}'.format(large_cluster_threshold)) + expected_cmd = ('mpirun ' + '--allow-run-as-root --tag-output ' + '-np 2 -H {hosts} ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(hosts=settings.hosts, binding_args=' '.join(binding_args), + mpi_flags=' '.join(mpi_flags)) + + # remove PYTHONPATH from execute's env + # we cannot know the exact value of that env variable + # we test right handling of PYTHONPATH in test_mpi_run_*pythonpath* below + self.assertIn('env', execute.call_args.kwargs) + if 'PYTHONPATH' in execute.call_args.kwargs['env']: + execute.call_args.kwargs['env'].pop('PYTHONPATH') + + expected_env = {'PATH': os.environ.get('PATH')} + execute.assert_called_once_with(expected_cmd, env=expected_env, stdout=None, stderr=None) + + """ + Tests mpi_run with full settings. + """ + def test_mpi_run_full(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd', 'arg1', 'arg2'] + nics = ['eth0', 'eth1'] + env = {'env1': 'val1', 'env2': 'val2'} + stdout = '' + stderr = '' + tmout = timeout.Timeout(5, message='Timed out waiting for something.') + settings = hvd_settings.Settings( + verbose=0, + ssh_port=1022, + extra_mpi_args='>mpi-extra args go here<', + binding_args='>binding args go here<', + key=secret.make_secret_key(), + start_timeout=tmout, + num_proc=1, + hosts='localhost:1', + output_filename='>output filename goes here<', + run_func_mode=True + ) + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], [], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags) as impl: + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute: + mpi_run(settings, nics, env, cmd, stdout=stdout, stderr=stderr) + + # assert call on _get_mpi_implementation_flags + impl.assert_called_once_with(None, env=env) + + # call the mocked _get_mpi_implementation_flags method ourselves + mpi_flags, _, mpi = horovod.runner.mpi_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + if _IMPI_IMPL == mpi: + expected_command = ('mpirun ' + '-l -n 1 -hosts {hosts} ' + '>binding args go here< ' + '{mpi_flags} ' + '-bootstrap-exec-args "-p 1022" ' + '-genv NCCL_SOCKET_IFNAME=eth0,eth1 ' + '-outfile-pattern >output pattern goes here< ' + '-genvlist env1,env2 ' + '>mpi-extra args go here< ' + 'cmd arg1 arg2').format(hosts=settings.hosts, + mpi_flags=' '.join(mpi_flags)) + else: + expected_command = ('mpirun ' + '--allow-run-as-root --tag-output ' + '-np 1 -H {hosts} ' + '>binding args go here< ' + '{mpi_flags} ' + '-mca plm_rsh_args "-p 1022" ' + '-mca btl_tcp_if_include eth0,eth1 -x NCCL_SOCKET_IFNAME=eth0,eth1 ' + '--output-filename >output filename goes here< ' + '-x env1 -x env2 ' + '>mpi-extra args go here< ' + 'cmd arg1 arg2').format(hosts=settings.hosts, + mpi_flags=' '.join(mpi_flags)) + + # remove PYTHONPATH from execute's env + # we cannot know the exact value of that env variable + # we test right handling of PYTHONPATH in test_mpi_run_*pythonpath* below + self.assertIn('env', execute.call_args.kwargs) + if 'PYTHONPATH' in execute.call_args.kwargs['env']: + execute.call_args.kwargs['env'].pop('PYTHONPATH') + + expected_env = {'env1': 'val1', 'env2': 'val2', 'PATH': os.environ.get('PATH')} + execute.assert_called_once_with(expected_command, env=expected_env, stdout=stdout, stderr=stderr) + + """ + Tests mpi_run without PYTHONPATH set. + """ + def test_mpi_run_without_pythonpath(self): + self.do_test_mpi_run_env_override({}, {}, 'PYTHONPATH', None) + + """ + Tests mpi_run with PYTHONPATH set in sys. + """ + def test_mpi_run_with_sys_pythonpath(self): + self.do_test_mpi_run_env_override({'PYTHONPATH': 'ppath'}, {}, 'PYTHONPATH', 'ppath') + + """ + Tests mpi_run with PYTHONPATH set in env. + """ + def test_mpi_run_with_env_pythonpath(self): + self.do_test_mpi_run_env_override({}, {'PYTHONPATH': 'ppath'}, 'PYTHONPATH', 'ppath') + + """ + Tests mpi_run with both PYTHONPATH set. + """ + def test_mpi_run_with_both_pythonpaths(self): + self.do_test_mpi_run_env_override({'PYTHONPATH': 'sys-ppath'}, {'PYTHONPATH': 'env-ppath'}, 'PYTHONPATH', 'env-ppath') + + """ + Tests mpi_run without PATH set. + """ + def test_mpi_run_without_path(self): + self.do_test_mpi_run_env_override({}, {}, 'PATH', None) + + """ + Tests mpi_run with PATH set in sys. + """ + def test_mpi_run_with_sys_path(self): + self.do_test_mpi_run_env_override({'PATH': 'ppath'}, {}, 'PATH', 'ppath') + + """ + Tests mpi_run with PATH set in env. + """ + def test_mpi_run_with_env_path(self): + self.do_test_mpi_run_env_override({}, {'PATH': 'ppath'}, 'PATH', 'ppath') + + """ + Tests mpi_run with both PATH set. + """ + def test_mpi_run_with_both_paths(self): + self.do_test_mpi_run_env_override({'PATH': 'sys-path'}, {'PATH': 'env-path'}, 'PATH', 'env-path') + + """ + Actually tests mpi_run overrides arg env with sys env. + """ + def do_test_mpi_run_env_override(self, sysenv, argenv, env_var, expected): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags),\ + mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute,\ + override_env(sysenv): + mpi_run(settings, None, argenv, cmd) + + # assert the env variable in the execute's env + self.assertIn('env', execute.call_args.kwargs) + self.assertEqual(execute.call_args.kwargs['env'].get(env_var), expected) + + def test_mpi_run_with_non_zero_exit(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return [], [], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=1): + with pytest.raises(RuntimeError, match="^mpirun failed with exit code 1$"): + mpi_run(settings, None, {}, cmd) + + """ + Tests mpi_run with os.environ. + """ + def test_mpi_run_with_os_environ(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"] + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0): + with pytest.raises(Exception, match="^env argument must be a dict, not : "): + mpi_run(settings, None, os.environ, cmd) + + """ + Tests gloo_run with minimal settings. + """ + def test_gloo_run_minimal(self): + if not gloo_built: + self.skipTest("Gloo is not available") + + cmd = ['whoami'] + settings = self.minimal_settings + gloo_run(settings, ['lo'], {}, '127.0.0.1', cmd) + + """ + Tests gloo_run with os.environ. + """ + def test_gloo_run_with_os_environ(self): + if not gloo_built: + self.skipTest("Gloo is not available") + + cmd = ['whoami'] + settings = self.minimal_settings + gloo_run(settings, ['lo'], os.environ, '127.0.0.1', cmd) + + def test_horovodrun_hostfile(self): + with temppath() as host_filename: + with open(host_filename, 'w+') as fp: + fp.write('172.31.32.7 slots=8\n') + fp.write('172.31.33.9 slots=8\n') + + hostnames = hosts.parse_host_files(host_filename) + self.assertEqual(hostnames, '172.31.32.7:8,172.31.33.9:8') + + """ + Tests js_run. + """ + @mock.patch('horovod.runner.js_run.is_jsrun_installed', MagicMock(return_value=True)) + @mock.patch('horovod.runner.js_run.generate_jsrun_rankfile', MagicMock(return_value='/tmp/rankfile')) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_gpus', MagicMock(return_value=2)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_cores', MagicMock(return_value=2)) + def test_js_run(self): + if _get_mpi_implementation_flags(False)[0] is None: + self.skipTest("MPI is not available") + + cmd = ['cmd', 'arg1', 'arg2'] + env = {'env1': 'val1', 'env2': 'val2'} + stdout = '' + stderr = '' + settings = hvd_settings.Settings( + verbose=0, + extra_mpi_args='>mpi-extra args go here<', + num_proc=4, + hosts='localhost:2,127.0.0.1:2', + output_filename='>output filename goes here<', + run_func_mode=True + ) + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], [] + + with mock.patch("horovod.runner.js_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.js_run.safe_shell_exec.execute", return_value=0) as execute: + js_run(settings, None, env, cmd, stdout=stdout, stderr=stderr) + + # call the mocked _get_mpi_implementation_flags method + mpi_flags, _ = horovod.runner.js_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + expected_command = ('jsrun ' + '--erf_input /tmp/rankfile ' + '--stdio_stderr >output filename goes here< ' + '--stdio_stdout >output filename goes here< ' + '--smpiargs \'{mpi_args} >mpi-extra args go here<\' ' + 'cmd arg1 arg2').format(mpi_args=' '.join(mpi_flags)) + expected_env = {'env1': 'val1', 'env2': 'val2'} + execute.assert_called_once_with(expected_command, env=expected_env, stdout=stdout, stderr=stderr) + + """ + Tests generate_jsrun_rankfile. + """ + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_gpus', MagicMock(return_value=4)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_cores', MagicMock(return_value=4)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_threads', MagicMock(return_value=4)) + def test_generate_jsrun_rankfile(self): + settings = hvd_settings.Settings( + num_proc=5, + hosts='host1:4,host2:4,host3:4', + ) + + with temppath() as rankfile_path: + rankfile_path = generate_jsrun_rankfile(settings, rankfile_path) + + with open(rankfile_path, 'r') as file: + gen_rankfile = file.read() + + expected_rankfile = ( +"""overlapping_rs: allow +cpu_index_using: logical + +rank: 0: { hostname: host1; cpu: {0-3} ; gpu: * ; mem: * } +rank: 1: { hostname: host1; cpu: {4-7} ; gpu: * ; mem: * } +rank: 2: { hostname: host1; cpu: {8-11} ; gpu: * ; mem: * } +rank: 3: { hostname: host1; cpu: {12-15} ; gpu: * ; mem: * } + +rank: 4: { hostname: host2; cpu: {0-3} ; gpu: * ; mem: * } +""") + + self.assertMultiLineEqual(gen_rankfile, expected_rankfile) + + """ + Tests horovod.runner.launch._run with jsrun + """ + @mock.patch('horovod.runner.util.lsf.LSFUtils.using_lsf', MagicMock(return_value=True)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_compute_hosts', MagicMock(return_value=['host1', 'host2'])) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_gpus', MagicMock(return_value=2)) + @mock.patch('horovod.runner.util.network.filter_local_addresses', MagicMock(return_value=['host1', 'host2'])) + @mock.patch('horovod.runner.launch._check_all_hosts_ssh_successful', MagicMock()) + @mock.patch('horovod.runner.launch.run_controller') + def test_run_with_jsrun(self, mocked_run_controller): + hargs = _HorovodArgs() + _run(hargs) + mocked_run_controller.assert_called_once() + + def test_get_host_assignments(self): + hosts = parse_hosts('worker-0:2,worker-1:2') + np = 4 + assignments = get_host_assignments(hosts, np) + + sizes = dict(size=4, local_size=2, cross_size=2) + expected = [SlotInfo(hostname='worker-0', rank=0, local_rank=0, cross_rank=0, **sizes), + SlotInfo(hostname='worker-0', rank=1, local_rank=1, cross_rank=0, **sizes), + SlotInfo(hostname='worker-1', rank=2, local_rank=0, cross_rank=1, **sizes), + SlotInfo(hostname='worker-1', rank=3, local_rank=1, cross_rank=1, **sizes)] + self.assertListEqual(assignments, expected) + + def test_get_host_assignments_elastic(self): + hosts = parse_hosts('worker-0:2,worker-1:2') + min_np = 1 + max_np = 2 + assignments = get_host_assignments(hosts, min_np=min_np, max_np=max_np) + + sizes = dict(size=2, local_size=2, cross_size=1) + expected = [SlotInfo(hostname='worker-0', rank=0, local_rank=0, cross_rank=0, **sizes), + SlotInfo(hostname='worker-0', rank=1, local_rank=1, cross_rank=0, **sizes)] + self.assertListEqual(assignments, expected) + + def test_get_host_assignments_heterogeneous(self): + hosts = parse_hosts('worker-0:1,worker-1:2') + np = 3 + assignments = get_host_assignments(hosts, np) + + expected = [SlotInfo(hostname='worker-0', rank=0, local_rank=0, cross_rank=0, + size=3, local_size=1, cross_size=2), + SlotInfo(hostname='worker-1', rank=1, local_rank=0, cross_rank=1, + size=3, local_size=2, cross_size=2), + SlotInfo(hostname='worker-1', rank=2, local_rank=1, cross_rank=0, + size=3, local_size=2, cross_size=1)] + self.assertListEqual(assignments, expected) +``` + +## `test/single/test_run.py` — `function:RunTests.test_get_mpi_implementation` (lines 624-650) + +```python + def test_get_mpi_implementation(self): + def test(output, expected, exit_code=0): + ret = (output, exit_code) if output is not None else None + env = {'VAR': 'val'} + with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m: + implementation = _get_mpi_implementation(env) + self.assertEqual(expected, implementation) + m.assert_called_once_with('mpirun --version', env) + + test(("mpirun (Open MPI) 2.1.1\n" + "Report bugs to http://www.open-mpi.org/community/help/\n"), _OMPI_IMPL) + + test("OpenRTE", _OMPI_IMPL) + + test("IBM Spectrum MPI", _SMPI_IMPL) + + test(("HYDRA build details:\n" + " Version: 3.3a2\n" + " Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL) + + test("Intel(R) MPI", _IMPI_IMPL) + + test("Unknown MPI v1.00", _UNKNOWN_IMPL) + + test("output", exit_code=1, expected=_MISSING_IMPL) + + test(None, _MISSING_IMPL) +``` + +## `test/utils/common.py` — `function:temppath` (lines 113-120) + +```python +def temppath(): + dir_path = tempfile.TemporaryDirectory() + path = os.path.join(dir_path.name,'temp_test_file') + try: + yield path + finally: + dir_path.cleanup() +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..223b1b19886f787b8812b5d7740950e582c3245c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/pre_context.md @@ -0,0 +1,1225 @@ +# Patch-overlapping Python context before the fix + +## `horovod/runner/js_run.py` — `function:generate_jsrun_rankfile` (lines 96-146) + +```python +def generate_jsrun_rankfile(settings, path=None): + """ + Generates rankfile to use with jsrun. + It splits the cores among the processes, which leads to best performance according to experiments. + + Args: + settings: Settings for running jsrun. + Note: settings.num_proc and settings.hosts must not be None. + path: Optional path of the rankfile. + Note: this file will be overwritten. + """ + cpu_per_gpu = (lsf.LSFUtils.get_num_cores() * lsf.LSFUtils.get_num_threads()) // lsf.LSFUtils.get_num_gpus() + host_list = (x.split(':') for x in settings.hosts.split(',')) + + # Verify and truncate host list if necessary + validated_list = [] + remaining_slots = settings.num_proc + for host, slots in host_list: + slots = int(slots) + if slots > lsf.LSFUtils.get_num_gpus(): + raise ValueError('Invalid host input, slot count for host \'{host}:{slots}\' is greater ' + 'than number of GPUs per host \'{gpus}\'.'.format( + host=host, slots=slots, gpus=lsf.LSFUtils.get_num_gpus())) + needed_slots = min(slots, remaining_slots) + validated_list.append((host, needed_slots)) + remaining_slots -= needed_slots + if remaining_slots == 0: + break + if remaining_slots != 0: + raise ValueError('Not enough slots on the hosts to fulfill the {slots} requested.'.format( + slots=settings.num_proc)) + + # Generate rankfile + path = tempfile.mktemp() if path is None else path + with open(path, 'w') as tmp: + tmp.write('overlapping_rs: allow\n') + tmp.write('cpu_index_using: logical\n') + rank = 0 + for host, slots in validated_list: + cpu_val = 0 + tmp.write('\n') + for s in range(slots): + tmp.write('rank: {rank}: {{ hostname: {host}; cpu: {{{scpu}-{ecpu}}} ; gpu: * ; mem: * }}\n'.format( + rank=rank, + host=host, + scpu=cpu_val, + ecpu=cpu_val + cpu_per_gpu - 1 + )) + rank += 1 + cpu_val += cpu_per_gpu + return path +``` + +## `test/single/test_run.py` — `class:RunTests` (lines 53-1168) + +```python +class RunTests(unittest.TestCase): + """ + Tests for horovod.runner. + """ + + def __init__(self, *args, **kwargs): + super(RunTests, self).__init__(*args, **kwargs) + warnings.simplefilter('module') + + def test_params_args(self): + with override_args('horovodrun', '-np', '2', + '--fusion-threshold-mb', '10', + '--cycle-time-ms', '20', + '--cache-capacity', '512', + '--hierarchical-allreduce', + '--hierarchical-allgather'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_FUSION_THRESHOLD), str(10 * 1024 * 1024)) + self.assertEqual(env.get(config_parser.HOROVOD_CYCLE_TIME), '20.0') + self.assertEqual(env.get(config_parser.HOROVOD_CACHE_CAPACITY), '512') + self.assertEqual(env.get(config_parser.HOROVOD_HIERARCHICAL_ALLREDUCE), '1') + self.assertEqual(env.get(config_parser.HOROVOD_HIERARCHICAL_ALLGATHER), '1') + + def test_autotune_args(self): + with override_args('horovodrun', '-np', '2', + '--autotune', + '--autotune-log-file', '/tmp/autotune.txt', + '--autotune-warmup-samples', '1', + '--autotune-steps-per-sample', '5', + '--autotune-bayes-opt-max-samples', '10', + '--autotune-gaussian-process-noise', '0.2'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE), '1') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_LOG), '/tmp/autotune.txt') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_WARMUP_SAMPLES), '1') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_STEPS_PER_SAMPLE), '5') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_BAYES_OPT_MAX_SAMPLES), '10') + self.assertEqual(env.get(config_parser.HOROVOD_AUTOTUNE_GAUSSIAN_PROCESS_NOISE), '0.2') + + def test_autotuning_with_fixed_param(self): + with override_args('horovodrun', '-np', '2', + '--autotune', + '--cache-capacity', '1024', + '--no-hierarchical-allgather'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertNotIn(config_parser.HOROVOD_FUSION_THRESHOLD, env) + self.assertNotIn(config_parser.HOROVOD_CYCLE_TIME, env) + self.assertEqual(env.get(config_parser.HOROVOD_CACHE_CAPACITY), '1024') + self.assertNotIn(config_parser.HOROVOD_HIERARCHICAL_ALLREDUCE, env) + self.assertEqual(env.get(config_parser.HOROVOD_HIERARCHICAL_ALLGATHER), '0') + + def test_timeline_args(self): + with override_args('horovodrun', '-np', '2', + '--timeline-filename', '/tmp/timeline.json', + '--timeline-mark-cycles'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_TIMELINE), '/tmp/timeline.json') + self.assertEqual(env.get(config_parser.HOROVOD_TIMELINE_MARK_CYCLES), '1') + + def test_stall_check_args(self): + with override_args('horovodrun', '-np', '2', + '--no-stall-check'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_STALL_CHECK_DISABLE), '1') + + with override_args('horovodrun', '-np', '2', + '--stall-check-warning-time-seconds', '10', + '--stall-check-shutdown-time-seconds', '20'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertNotIn(config_parser.HOROVOD_STALL_CHECK_DISABLE, env) + self.assertEqual(env.get(config_parser.HOROVOD_STALL_CHECK_TIME_SECONDS), '10') + self.assertEqual(env.get(config_parser.HOROVOD_STALL_SHUTDOWN_TIME_SECONDS), '20') + + def test_library_args(self): + with override_args('horovodrun', '-np', '2', + '--mpi-threads-disable', + '--num-nccl-streams', '2', + '--thread-affinity', '1', + '--gloo-timeout-seconds', '60'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_MPI_THREADS_DISABLE), '1') + self.assertEqual(env.get(config_parser.HOROVOD_NUM_NCCL_STREAMS), '2') + self.assertEqual(env.get(config_parser.HOROVOD_THREAD_AFFINITY), '1') + self.assertEqual(env.get(config_parser.HOROVOD_GLOO_TIMEOUT_SECONDS), '60') + + def test_library_env_override(self): + """Tests that environment variables override arg defaults.""" + with override_args('horovodrun', '-np', '2'): + args = parse_args() + env = { + 'HOROVOD_GLOO_TIMEOUT_SECONDS': '1800', + } + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_GLOO_TIMEOUT_SECONDS), '1800') + + def test_logging_args(self): + with override_args('horovodrun', '-np', '2', + '--log-level', 'INFO', + '--log-hide-timestamp'): + args = parse_args() + env = {} + config_parser.set_env_from_args(env, args) + + self.assertEqual(env.get(config_parser.HOROVOD_LOG_LEVEL), 'INFO') + self.assertEqual(env.get(config_parser.HOROVOD_LOG_HIDE_TIME), '1') + + def test_config_file(self): + config_filename = os.path.join(os.path.dirname(__file__), 'data/config.test.yaml') + with override_args('horovodrun', '-np', '2', + '--config-file', config_filename): + args = parse_args() + + self.assertTrue(args.use_gloo) + + # Params + self.assertEqual(args.fusion_threshold_mb, 32) + self.assertEqual(args.cycle_time_ms, 10) + self.assertEqual(args.cache_capacity, 2048) + self.assertTrue(args.hierarchical_allreduce) + self.assertTrue(args.hierarchical_allgather) + + # Autotune + self.assertTrue(args.autotune) + self.assertEqual(args.autotune_log_file, 'horovod_autotune_log.txt') + self.assertEqual(args.autotune_warmup_samples, 5) + self.assertEqual(args.autotune_steps_per_sample, 20) + self.assertEqual(args.autotune_bayes_opt_max_samples, 50) + self.assertEqual(args.autotune_gaussian_process_noise, 0.9) + + # Timeline + self.assertEqual(args.timeline_filename, 'horovod_timeline.json') + self.assertTrue(args.timeline_mark_cycles) + + # Stall Check + self.assertFalse(args.no_stall_check) + self.assertEqual(args.stall_check_warning_time_seconds, 120) + self.assertEqual(args.stall_check_shutdown_time_seconds, 240) + + # Library Options + self.assertTrue(args.mpi_threads_disable) + self.assertEqual(args.num_nccl_streams, 2) + self.assertEqual(args.thread_affinity, 1) + self.assertEqual(args.gloo_timeout_seconds, 60) + + # Logging + self.assertEqual(args.log_level, 'INFO') + self.assertFalse(args.log_with_timestamp) + + def test_config_file_override_args(self): + config_filename = os.path.join(os.path.dirname(__file__), 'data/config.test.yaml') + with override_args('horovodrun', '-np', '2', + '--fusion-threshold-mb', '256', + '--config-file', config_filename, + '--cycle-time-ms', '20',): + args = parse_args() + self.assertEqual(args.fusion_threshold_mb, 256) + self.assertEqual(args.cycle_time_ms, 20) + + def test_validate_config_args(self): + with override_args('horovodrun', '-np', '2', + '--fusion-threshold-mb', '-1'): + with pytest.raises(ValueError): + parse_args() + + # test_on_event tests in_thread as well, but it does not test args + def test_in_thread_args(self): + fn = mock.Mock() + thread = in_thread(fn, args=(1,)) + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once_with(1) + + fn = mock.Mock() + thread = in_thread(fn, args=(1, 2)) + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once_with(1, 2) + + fn = mock.Mock() + thread = in_thread(fn, args=(1, 2), silent=True) + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once_with(1, 2) + + fn = mock.Mock() + with pytest.raises(ValueError, match="^args must be a tuple, not <(class|type) 'int'>, " + "for a single argument use \\(arg,\\)$"): + in_thread(fn, args=1) + fn.assert_not_called() + + def test_on_event(self): + # a happy run without args and stop event + event = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + + # a happy run with args but without stop event + event = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn, ('a', 1)) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + fn.assert_called_once_with('a', 1) + + # a happy run with stop event but unused + event = threading.Event() + stop = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn, stop=stop, check_stop_interval_s=0.01) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + stop.set() + time.sleep(0.1) + fn.assert_called_once() + + # stop the thread before we set the event + event = threading.Event() + stop = threading.Event() + fn = mock.Mock() + thread = on_event(event, fn, stop=stop, check_stop_interval_s=0.01) + fn.assert_not_called() + stop.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_not_called() + event.set() + time.sleep(0.1) + fn.assert_not_called() + + # test with exception + def exception(): + raise Exception("Test Exception") + + event = threading.Event() + fn = mock.Mock(side_effect=exception) + thread = on_event(event, fn) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + + # test with exception but silent + event = threading.Event() + fn = mock.Mock(side_effect=exception) + thread = on_event(event, fn) + fn.assert_not_called() + event.set() + thread.join(1.0) + self.assertFalse(thread.is_alive()) + fn.assert_called_once() + + # test None event + event = None + fn = mock.Mock() + with pytest.raises(ValueError, match="^Event must not be None$"): + on_event(event, fn) + fn.assert_not_called() + + # test non-tuple args + event = threading.Event() + fn = mock.Mock() + with pytest.raises(ValueError, match="^args must be a tuple, not <(class|type) 'int'>, " + "for a single argument use \\(arg,\\)$"): + on_event(event, fn, args=1) + fn.assert_not_called() + + # test None stop and non-daemon + event = threading.Event() + fn = mock.Mock() + with pytest.raises(ValueError, match="^Stop event must be given for non-daemon event thread$"): + on_event(event, fn, stop=None, daemon=False) + fn.assert_not_called() + + def test_prefix_connection(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:first line\n' + '[123]:second line\n' + '[123]:more lines\n') + + def test_prefix_connection_with_unicode(self): + string = '∀∁∂∃∄∅∆∇∈∉∊∋∌∍∎∏∐∑\n⌚⌛⛄✅…\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:∀∁∂∃∄∅∆∇∈∉∊∋∌∍∎∏∐∑\n' + '[123]:⌚⌛⛄✅…\n') + + def test_prefix_connection_with_multibyte_unicode(self): + block = '█▓▒░▒▓'*1000 + string = block + '\n' + block + '\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:' + block + '\n' + + '[123]:' + block + '\n') + + def test_prefix_connection_with_timestamp(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection_with_timestamp( + string, prefix='prefix', index=123, + expected='Mon Jan 20 12:00:01 2020[123]:first line\n' + 'Mon Jan 20 12:00:02 2020[123]:second line\n' + 'Mon Jan 20 12:00:03 2020[123]:more lines\n' + ) + + def test_prefix_connection_with_timestamp_without_index(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection_with_timestamp(string, prefix=None, index=None, + expected=string) + + def test_prefix_connection_without_trailing_newline(self): + string = 'first line\nsecond line\nmore lines' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:first line\n' + '[123]:second line\n' + '[123]:more lines') + + def test_prefix_connection_without_index(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection(string, prefix='prefix', index=None, expected=string) + + def test_prefix_connection_without_prefix(self): + string = 'first line\nsecond line\nmore lines\n' + self.do_test_prefix_connection(string, prefix=None, index=123, expected=string) + + def test_prefix_connection_with_carriage_return(self): + string = 'first line\rfirst line again\nsecond line\n' + self.do_test_prefix_connection(string, prefix='prefix', index=123, + expected='[123]:first line\r' + '[123]:first line again\n' + '[123]:second line\n') + + def test_prefix_connection_with_carriage_return_without_index(self): + string = 'first line\rfirst line again\nsecond line\n' + self.do_test_prefix_connection(string, prefix='prefix', index=None, expected=string) + + def test_prefix_connection_with_carriage_return_without_prefix(self): + string = 'first line\rfirst line again\nsecond line\n' + self.do_test_prefix_connection(string, prefix=None, index=123, expected=string) + + def do_test_prefix_connection(self, string, prefix, index, expected, timestamp=False): + # create a Pipe Connection and populate it with string + (connection, w) = multiprocessing.get_context('spawn').Pipe(duplex=False) + with os.fdopen(w.fileno(), 'wt', encoding='utf8', newline='', closefd=False) as stream: + stream.write(string) + w.close() + + dst = io.StringIO() + safe_shell_exec.prefix_connection(connection, dst, prefix=prefix, index=index, + prefix_output_with_timestamp=timestamp) + self.assertEqual(expected, dst.getvalue()) + + def do_test_prefix_connection_with_timestamp(self, string_or_connection, prefix, index, expected): + # control the time used to prepend the timestamp + class MockTime: + def __init__(self): + # start at 2020-01-20 12:00:00 + self._time = 1579521600 + + def time(self, seconds): + from time import gmtime + self._time = self._time + 1 + return gmtime(self._time) + + with mock.patch('horovod.runner.common.util.safe_shell_exec.time.localtime', + side_effect=MockTime().time): + self.do_test_prefix_connection(string_or_connection, prefix, index, expected, timestamp=True) + + def test_prefix_connection_does_stream(self): + index = 123 + prefix = 'prefix' + expected = '[123]:first line\r' \ + '[123]:first line again\n' \ + '[123]:second line\n' \ + '[123]:more lines' + + timeout = 0.2 + barrier = multiprocessing.Barrier(2, timeout=timeout) + + def writer(write_connection): + def write(stream, text): + stream.write(text) + logging.info('wrote: {}'.format(text)) + stream.flush() + + # are we expecting the reader to read something + logging.info('waiting for reader') + if '\r' in text or '\n' in text: + # yes, barrier should not timeout + try: + barrier.wait() + except threading.BrokenBarrierError: + self.fail('reader side should have read something from the stream') + else: + # no, barrier should timeout + try: + barrier.wait() + self.fail('reader side should not have read anything from the stream') + except threading.BrokenBarrierError: + logging.info('reader did not read') + barrier.reset() + pass + logging.info('continuing writing') + + try: + with os.fdopen(write_connection.fileno(), 'wt', encoding='utf8', newline='', closefd=False) as stream: + for text in ['first line\r', + 'first ', 'line ', 'again\n', + 'second line\nmore ', 'lines']: + write(stream, text) + finally: + write_connection.close() + + actual = [] + do_read = True + + def reader(read_connection): + try: + while do_read: + text = os.read(read_connection.fileno(), 1000) + if not text: + break + text = text.decode('utf8') + actual.append(text) + logging.info('read: {}'.format(text)) + logging.info('waiting for writer') + try: + barrier.wait() + except threading.BrokenBarrierError as e: + if do_read: + raise e + break + logging.info('continuing reading') + finally: + read_connection.close() + + # one thread writes into the w side of this pipe + # prefix_connection reads on the other end of this pipe + (connection, w) = multiprocessing.get_context('spawn').Pipe(duplex=False) + writer_thread = in_thread(writer, (w,)) + + # prefix_connection writes to the write side of this Pipe (opened as a text stream) + # another thread reads from the r side of this pipe + (r, dst_con) = multiprocessing.get_context('spawn').Pipe(duplex=False) + reader_thread = in_thread(reader, (r,)) + + with os.fdopen(dst_con.fileno(), 'wt', encoding='utf8', newline='', closefd=False) as dst: + safe_shell_exec.prefix_connection(connection, dst, prefix=prefix, index=index, + prefix_output_with_timestamp=False) + + writer_thread.join(2*timeout) + do_read = False + reader_thread.join(2*timeout) + + self.assertEqual(expected, ''.join(actual)) + + def test_safe_shell_exec_captures_stdout(self): + self.do_test_safe_shell_exec('echo hello', 0, 'hello\n', '') + + def test_safe_shell_exec_captures_stderr(self): + self.do_test_safe_shell_exec('echo hello >&2', 0, '', 'hello\n') + + def test_safe_shell_exec_captures_last_line_wo_eol(self): + cmd = 'bash -c "echo -e -n \\"hello\nstdout\\"; echo -e -n \\"hello\nstderr\\" >&2"' + self.do_test_safe_shell_exec(cmd, 0, 'hello\nstdout', 'hello\nstderr') + + def test_safe_shell_exec_returns_exit_code(self): + self.do_test_safe_shell_exec('false', 1, '', '') + + @pytest.mark.skip(reason='https://github.com/horovod/horovod/issues/1993') + def test_safe_shell_exec_interrupts_on_event(self): + # interrupt execute in one second + interrupt = threading.Event() + interrupt_delay = 1.0 + delay(lambda: interrupt.set(), interrupt_delay) + + sleep = interrupt_delay + safe_shell_exec.GRACEFUL_TERMINATION_TIME_S + 2.0 + start = time.time() + self.do_test_safe_shell_exec('sleep {}'.format(sleep), 143, '', None, interrupt) + duration = time.time() - start + + self.assertGreaterEqual(duration, interrupt_delay) + self.assertLess(duration, sleep - 1.0, 'sleep should not finish') + + def test_safe_shell_exec_interrupts_on_parent_shutdown(self): + sleep = 20 + parent_script = os.path.join(os.path.dirname(__file__), 'data/run_safe_shell_exec.py') + child_script = os.path.join(os.path.dirname(__file__), 'data/sleep.py') + + def get_pid(logfile): + # Wait until the script has written its PID to the logfile + wait(lambda: os.path.exists(logfile), timeout=5) + with open(logfile, 'r') as f: + return int(f.read()) + + with temppath() as parent_logfile, temppath() as child_logfile: + # It's important that this executes in an entirely different interpreter with as little shared + # state as possible, to avoid issues with the semaphore tracker. + cmd = ' '.join([sys.executable, parent_script, parent_logfile, child_script, str(sleep), child_logfile]) + p = subprocess.Popen(cmd, shell=True) + + parent = psutil.Process(get_pid(parent_logfile)) + child = psutil.Process(get_pid(child_logfile)) + + self.assertTrue(parent.is_running()) + self.assertTrue(child.is_running()) + + # Hard kill the parent process + parent.kill() + parent.wait(timeout=safe_shell_exec.GRACEFUL_TERMINATION_TIME_S) + p.wait() + + # Child process will exit when pipe breaks + child.wait(timeout=2 * safe_shell_exec.GRACEFUL_TERMINATION_TIME_S + 1) + + self.assertFalse(parent.is_running()) + self.assertFalse(child.is_running()) + + def do_test_safe_shell_exec(self, cmd, expected_exit_code, expected_stdout, expected_stderr, event=None): + stdout = io.StringIO() + stderr = io.StringIO() + res = safe_shell_exec.execute(cmd, stdout=stdout, stderr=stderr, events=[event] if event else None) + self.assertEqual(expected_exit_code, res) + if expected_stdout is not None: + self.assertEqual(expected_stdout, stdout.getvalue()) + if expected_stderr is not None: + self.assertEqual(expected_stderr, stderr.getvalue()) + + def test_hash(self): + hash = _hash("test string") + self.assertEqual(hash, '6f8db599de986fab7a21625b7916589c') + + def test_host_hash(self): + hash = host_hash() + salted = host_hash('salt') + empty_salted = host_hash('') + + self.assertNotEqual(salted, hash) + self.assertEqual(empty_salted, hash) + + def test_get_mpi_implementation(self): + def test(output, expected, exit_code=0): + ret = (output, exit_code) if output is not None else None + env = {'VAR': 'val'} + with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m: + implementation = _get_mpi_implementation(env) + self.assertEqual(expected, implementation) + m.assert_called_once_with('mpirun --version', env) + + test(("mpirun (Open MPI) 2.1.1\n" + "Report bugs to http://www.open-mpi.org/community/help/\n"), _OMPI_IMPL) + + test("OpenRTE", _OMPI_IMPL) + + test("IBM Spectrum MPI", _SMPI_IMPL) + + test(("HYDRA build details:\n" + " Version: 3.3a2\n" + " Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL) + + test("Intel(R) MPI", _IMPI_IMPL) + + test("Unknown MPI v1.00", _UNKNOWN_IMPL) + + test("output", exit_code=1, expected=_MISSING_IMPL) + + test(None, _MISSING_IMPL) + + def test_run_controller(self): + def test(use_gloo, use_mpi, use_js, + gloo_is_built, mpi_is_built, + lsf_exists, jsrun_installed, + expected, exception): + gloo_run = MagicMock() + mpi_run = MagicMock() + js_run = MagicMock() + + with is_built(gloo_is_built, mpi_is_built): + with lsf_and_jsrun(lsf_exists, jsrun_installed): + if exception is not None: + with pytest.raises(ValueError, match=exception) as e: + run_controller(use_gloo, gloo_run, use_mpi, mpi_run, use_js, js_run, verbosity=2) + return + run_controller(use_gloo, gloo_run, use_mpi, mpi_run, use_js, js_run, verbosity=2) + + if expected == "gloo": + gloo_run.assert_called_once() + mpi_run.assert_not_called() + js_run.assert_not_called() + elif expected == "mpi": + gloo_run.assert_not_called() + mpi_run.assert_called_once() + js_run.assert_not_called() + elif expected == "js": + gloo_run.assert_not_called() + mpi_run.assert_not_called() + js_run.assert_called_once() + else: + raise ValueError("unsupported framework: {}".format(expected)) + + bool_values = [False, True] + bool_values_and_none = [None, False, True] + + for use_gloo, use_mpi, use_js, \ + gloo_is_built, mpi_is_built, \ + lsf_exists, jsrun_installed in \ + itertools.product(bool_values_and_none, bool_values_and_none, bool_values_and_none, + bool_values, bool_values, + bool_values, bool_values): + + expected = exception = None + if use_gloo: + if gloo_is_built: + expected = 'gloo' + else: + exception = r'^Gloo support has not been built\. If this is not expected, ensure CMake is installed ' \ + r'and reinstall Horovod with HOROVOD_WITH_GLOO=1 to debug the build error\.$' + elif use_mpi: + if mpi_is_built: + expected = 'mpi' + else: + exception = r'^MPI support has not been built\. If this is not expected, ensure MPI is installed ' \ + r'and reinstall Horovod with HOROVOD_WITH_MPI=1 to debug the build error\.$' + elif use_js: + if mpi_is_built: + if lsf_exists: + expected = 'js' + else: + exception = 'Horovod did not detect an LSF job. The jsrun launcher can only be used in that environment. ' \ + 'Please, pick a different launcher for other environments.' + else: + exception = r'^MPI support has not been built\. If this is not expected, ensure MPI is installed ' \ + r'and reinstall Horovod with HOROVOD_WITH_MPI=1 to debug the build error\.$' + elif mpi_is_built: + if lsf_exists and jsrun_installed: + expected = 'js' + else: + expected = 'mpi' + elif gloo_is_built: + expected = 'gloo' + else: + exception = r'Neither MPI nor Gloo support has been built\. Try reinstalling Horovod ensuring that ' \ + r'either MPI is installed \(MPI\) or CMake is installed \(Gloo\)\.' + + test(use_gloo, use_mpi, use_js, + gloo_is_built, mpi_is_built, + lsf_exists, jsrun_installed, + expected, exception) + + """ + Minimal mpi_run settings for tests. + """ + minimal_settings = hvd_settings.Settings( + verbose=0, + num_proc=2, + hosts='localhost:2', + run_func_mode=True + ) + + """ + Tests mpi_run with minimal settings. + """ + def test_mpi_run_minimal(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute: + mpi_run(settings, None, {}, cmd) + + # call the mocked _get_mpi_implementation_flags method + mpi_flags, binding_args, mpi = horovod.runner.mpi_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + if _IMPI_IMPL == mpi: + expected_cmd = ('mpirun ' + '-l -n 2 -hosts localhost ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(binding_args=' '.join(binding_args), mpi_flags=' '.join(mpi_flags)) + else: + expected_cmd = ('mpirun ' + '--allow-run-as-root --tag-output ' + '-np 2 -H localhost:2 ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(binding_args=' '.join(binding_args), mpi_flags=' '.join(mpi_flags)) + + # remove PYTHONPATH from execute's env + # we cannot know the exact value of that env variable + # we test right handling of PYTHONPATH in test_mpi_run_*pythonpath* below + self.assertIn('env', execute.call_args.kwargs) + if 'PYTHONPATH' in execute.call_args.kwargs['env']: + execute.call_args.kwargs['env'].pop('PYTHONPATH') + + expected_env = {'PATH': os.environ.get('PATH')} + execute.assert_called_once_with(expected_cmd, env=expected_env, stdout=None, stderr=None) + + """ + Tests mpi_run on a large cluster. + """ + def test_mpi_run_on_large_cluster(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = copy.copy(self.minimal_settings) + settings.hosts = ','.join(['localhost:1'] * large_cluster_threshold) + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute: + mpi_run(settings, None, {}, cmd) + + # call the mocked _get_mpi_implementation_flags method + mpi_flags, binding_args, mpi = horovod.runner.mpi_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + if _IMPI_IMPL == mpi: + expected_cmd = ('mpirun ' + '-l -n 2 -ppn 1 -hosts {hosts} ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(hosts=settings.hosts, binding_args=' '.join(binding_args), + mpi_flags=' '.join(mpi_flags)) + else: + mpi_flags.append('-mca plm_rsh_no_tree_spawn true') + mpi_flags.append('-mca plm_rsh_num_concurrent {}'.format(large_cluster_threshold)) + expected_cmd = ('mpirun ' + '--allow-run-as-root --tag-output ' + '-np 2 -H {hosts} ' + '{binding_args} ' + '{mpi_flags} ' + 'cmd').format(hosts=settings.hosts, binding_args=' '.join(binding_args), + mpi_flags=' '.join(mpi_flags)) + + # remove PYTHONPATH from execute's env + # we cannot know the exact value of that env variable + # we test right handling of PYTHONPATH in test_mpi_run_*pythonpath* below + self.assertIn('env', execute.call_args.kwargs) + if 'PYTHONPATH' in execute.call_args.kwargs['env']: + execute.call_args.kwargs['env'].pop('PYTHONPATH') + + expected_env = {'PATH': os.environ.get('PATH')} + execute.assert_called_once_with(expected_cmd, env=expected_env, stdout=None, stderr=None) + + """ + Tests mpi_run with full settings. + """ + def test_mpi_run_full(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd', 'arg1', 'arg2'] + nics = ['eth0', 'eth1'] + env = {'env1': 'val1', 'env2': 'val2'} + stdout = '' + stderr = '' + tmout = timeout.Timeout(5, message='Timed out waiting for something.') + settings = hvd_settings.Settings( + verbose=0, + ssh_port=1022, + extra_mpi_args='>mpi-extra args go here<', + binding_args='>binding args go here<', + key=secret.make_secret_key(), + start_timeout=tmout, + num_proc=1, + hosts='localhost:1', + output_filename='>output filename goes here<', + run_func_mode=True + ) + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], [], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags) as impl: + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute: + mpi_run(settings, nics, env, cmd, stdout=stdout, stderr=stderr) + + # assert call on _get_mpi_implementation_flags + impl.assert_called_once_with(None, env=env) + + # call the mocked _get_mpi_implementation_flags method ourselves + mpi_flags, _, mpi = horovod.runner.mpi_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + if _IMPI_IMPL == mpi: + expected_command = ('mpirun ' + '-l -n 1 -hosts {hosts} ' + '>binding args go here< ' + '{mpi_flags} ' + '-bootstrap-exec-args "-p 1022" ' + '-genv NCCL_SOCKET_IFNAME=eth0,eth1 ' + '-outfile-pattern >output pattern goes here< ' + '-genvlist env1,env2 ' + '>mpi-extra args go here< ' + 'cmd arg1 arg2').format(hosts=settings.hosts, + mpi_flags=' '.join(mpi_flags)) + else: + expected_command = ('mpirun ' + '--allow-run-as-root --tag-output ' + '-np 1 -H {hosts} ' + '>binding args go here< ' + '{mpi_flags} ' + '-mca plm_rsh_args "-p 1022" ' + '-mca btl_tcp_if_include eth0,eth1 -x NCCL_SOCKET_IFNAME=eth0,eth1 ' + '--output-filename >output filename goes here< ' + '-x env1 -x env2 ' + '>mpi-extra args go here< ' + 'cmd arg1 arg2').format(hosts=settings.hosts, + mpi_flags=' '.join(mpi_flags)) + + # remove PYTHONPATH from execute's env + # we cannot know the exact value of that env variable + # we test right handling of PYTHONPATH in test_mpi_run_*pythonpath* below + self.assertIn('env', execute.call_args.kwargs) + if 'PYTHONPATH' in execute.call_args.kwargs['env']: + execute.call_args.kwargs['env'].pop('PYTHONPATH') + + expected_env = {'env1': 'val1', 'env2': 'val2', 'PATH': os.environ.get('PATH')} + execute.assert_called_once_with(expected_command, env=expected_env, stdout=stdout, stderr=stderr) + + """ + Tests mpi_run without PYTHONPATH set. + """ + def test_mpi_run_without_pythonpath(self): + self.do_test_mpi_run_env_override({}, {}, 'PYTHONPATH', None) + + """ + Tests mpi_run with PYTHONPATH set in sys. + """ + def test_mpi_run_with_sys_pythonpath(self): + self.do_test_mpi_run_env_override({'PYTHONPATH': 'ppath'}, {}, 'PYTHONPATH', 'ppath') + + """ + Tests mpi_run with PYTHONPATH set in env. + """ + def test_mpi_run_with_env_pythonpath(self): + self.do_test_mpi_run_env_override({}, {'PYTHONPATH': 'ppath'}, 'PYTHONPATH', 'ppath') + + """ + Tests mpi_run with both PYTHONPATH set. + """ + def test_mpi_run_with_both_pythonpaths(self): + self.do_test_mpi_run_env_override({'PYTHONPATH': 'sys-ppath'}, {'PYTHONPATH': 'env-ppath'}, 'PYTHONPATH', 'env-ppath') + + """ + Tests mpi_run without PATH set. + """ + def test_mpi_run_without_path(self): + self.do_test_mpi_run_env_override({}, {}, 'PATH', None) + + """ + Tests mpi_run with PATH set in sys. + """ + def test_mpi_run_with_sys_path(self): + self.do_test_mpi_run_env_override({'PATH': 'ppath'}, {}, 'PATH', 'ppath') + + """ + Tests mpi_run with PATH set in env. + """ + def test_mpi_run_with_env_path(self): + self.do_test_mpi_run_env_override({}, {'PATH': 'ppath'}, 'PATH', 'ppath') + + """ + Tests mpi_run with both PATH set. + """ + def test_mpi_run_with_both_paths(self): + self.do_test_mpi_run_env_override({'PATH': 'sys-path'}, {'PATH': 'env-path'}, 'PATH', 'env-path') + + """ + Actually tests mpi_run overrides arg env with sys env. + """ + def do_test_mpi_run_env_override(self, sysenv, argenv, env_var, expected): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags),\ + mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0) as execute,\ + override_env(sysenv): + mpi_run(settings, None, argenv, cmd) + + # assert the env variable in the execute's env + self.assertIn('env', execute.call_args.kwargs) + self.assertEqual(execute.call_args.kwargs['env'].get(env_var), expected) + + def test_mpi_run_with_non_zero_exit(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return [], [], None + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=1): + with pytest.raises(RuntimeError, match="^mpirun failed with exit code 1$"): + mpi_run(settings, None, {}, cmd) + + """ + Tests mpi_run with os.environ. + """ + def test_mpi_run_with_os_environ(self): + if not mpi_available(): + self.skipTest("MPI is not available") + + cmd = ['cmd'] + settings = self.minimal_settings + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], ["--mock-mpi-binding-args"] + + with mock.patch("horovod.runner.mpi_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.mpi_run.safe_shell_exec.execute", return_value=0): + with pytest.raises(Exception, match="^env argument must be a dict, not : "): + mpi_run(settings, None, os.environ, cmd) + + """ + Tests gloo_run with minimal settings. + """ + def test_gloo_run_minimal(self): + if not gloo_built: + self.skipTest("Gloo is not available") + + cmd = ['whoami'] + settings = self.minimal_settings + gloo_run(settings, ['lo'], {}, '127.0.0.1', cmd) + + """ + Tests gloo_run with os.environ. + """ + def test_gloo_run_with_os_environ(self): + if not gloo_built: + self.skipTest("Gloo is not available") + + cmd = ['whoami'] + settings = self.minimal_settings + gloo_run(settings, ['lo'], os.environ, '127.0.0.1', cmd) + + def test_horovodrun_hostfile(self): + with temppath() as host_filename: + with open(host_filename, 'w+') as fp: + fp.write('172.31.32.7 slots=8\n') + fp.write('172.31.33.9 slots=8\n') + + hostnames = hosts.parse_host_files(host_filename) + self.assertEqual(hostnames, '172.31.32.7:8,172.31.33.9:8') + + """ + Tests js_run. + """ + @mock.patch('horovod.runner.js_run.is_jsrun_installed', MagicMock(return_value=True)) + @mock.patch('horovod.runner.js_run.generate_jsrun_rankfile', MagicMock(return_value='/tmp/rankfile')) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_gpus', MagicMock(return_value=2)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_cores', MagicMock(return_value=2)) + def test_js_run(self): + if _get_mpi_implementation_flags(False)[0] is None: + self.skipTest("MPI is not available") + + cmd = ['cmd', 'arg1', 'arg2'] + env = {'env1': 'val1', 'env2': 'val2'} + stdout = '' + stderr = '' + settings = hvd_settings.Settings( + verbose=0, + extra_mpi_args='>mpi-extra args go here<', + num_proc=4, + hosts='localhost:2,127.0.0.1:2', + output_filename='>output filename goes here<', + run_func_mode=True + ) + + def mpi_impl_flags(tcp, env=None): + return ["--mock-mpi-impl-flags"], [] + + with mock.patch("horovod.runner.js_run._get_mpi_implementation_flags", side_effect=mpi_impl_flags): + with mock.patch("horovod.runner.js_run.safe_shell_exec.execute", return_value=0) as execute: + js_run(settings, None, env, cmd, stdout=stdout, stderr=stderr) + + # call the mocked _get_mpi_implementation_flags method + mpi_flags, _ = horovod.runner.js_run._get_mpi_implementation_flags(False) + self.assertIsNotNone(mpi_flags) + expected_command = ('jsrun ' + '--erf_input /tmp/rankfile ' + '--stdio_stderr >output filename goes here< ' + '--stdio_stdout >output filename goes here< ' + '--smpiargs \'{mpi_args} >mpi-extra args go here<\' ' + 'cmd arg1 arg2').format(mpi_args=' '.join(mpi_flags)) + expected_env = {'env1': 'val1', 'env2': 'val2'} + execute.assert_called_once_with(expected_command, env=expected_env, stdout=stdout, stderr=stderr) + + """ + Tests generate_jsrun_rankfile. + """ + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_gpus', MagicMock(return_value=4)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_cores', MagicMock(return_value=4)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_threads', MagicMock(return_value=4)) + def test_generate_jsrun_rankfile(self): + settings = hvd_settings.Settings( + num_proc=5, + hosts='host1:4,host2:4,host3:4', + ) + + with temppath() as rankfile_path: + rankfile_path = generate_jsrun_rankfile(settings, rankfile_path) + + with open(rankfile_path, 'r') as file: + gen_rankfile = file.read() + + expected_rankfile = ( +"""overlapping_rs: allow +cpu_index_using: logical + +rank: 0: { hostname: host1; cpu: {0-3} ; gpu: * ; mem: * } +rank: 1: { hostname: host1; cpu: {4-7} ; gpu: * ; mem: * } +rank: 2: { hostname: host1; cpu: {8-11} ; gpu: * ; mem: * } +rank: 3: { hostname: host1; cpu: {12-15} ; gpu: * ; mem: * } + +rank: 4: { hostname: host2; cpu: {0-3} ; gpu: * ; mem: * } +""") + + self.assertMultiLineEqual(gen_rankfile, expected_rankfile) + + """ + Tests horovod.runner.launch._run with jsrun + """ + @mock.patch('horovod.runner.util.lsf.LSFUtils.using_lsf', MagicMock(return_value=True)) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_compute_hosts', MagicMock(return_value=['host1', 'host2'])) + @mock.patch('horovod.runner.util.lsf.LSFUtils.get_num_gpus', MagicMock(return_value=2)) + @mock.patch('horovod.runner.util.network.filter_local_addresses', MagicMock(return_value=['host1', 'host2'])) + @mock.patch('horovod.runner.launch._check_all_hosts_ssh_successful', MagicMock()) + @mock.patch('horovod.runner.launch.run_controller') + def test_run_with_jsrun(self, mocked_run_controller): + hargs = _HorovodArgs() + _run(hargs) + mocked_run_controller.assert_called_once() + + def test_get_host_assignments(self): + hosts = parse_hosts('worker-0:2,worker-1:2') + np = 4 + assignments = get_host_assignments(hosts, np) + + sizes = dict(size=4, local_size=2, cross_size=2) + expected = [SlotInfo(hostname='worker-0', rank=0, local_rank=0, cross_rank=0, **sizes), + SlotInfo(hostname='worker-0', rank=1, local_rank=1, cross_rank=0, **sizes), + SlotInfo(hostname='worker-1', rank=2, local_rank=0, cross_rank=1, **sizes), + SlotInfo(hostname='worker-1', rank=3, local_rank=1, cross_rank=1, **sizes)] + self.assertListEqual(assignments, expected) + + def test_get_host_assignments_elastic(self): + hosts = parse_hosts('worker-0:2,worker-1:2') + min_np = 1 + max_np = 2 + assignments = get_host_assignments(hosts, min_np=min_np, max_np=max_np) + + sizes = dict(size=2, local_size=2, cross_size=1) + expected = [SlotInfo(hostname='worker-0', rank=0, local_rank=0, cross_rank=0, **sizes), + SlotInfo(hostname='worker-0', rank=1, local_rank=1, cross_rank=0, **sizes)] + self.assertListEqual(assignments, expected) + + def test_get_host_assignments_heterogeneous(self): + hosts = parse_hosts('worker-0:1,worker-1:2') + np = 3 + assignments = get_host_assignments(hosts, np) + + expected = [SlotInfo(hostname='worker-0', rank=0, local_rank=0, cross_rank=0, + size=3, local_size=1, cross_size=2), + SlotInfo(hostname='worker-1', rank=1, local_rank=0, cross_rank=1, + size=3, local_size=2, cross_size=2), + SlotInfo(hostname='worker-1', rank=2, local_rank=1, cross_rank=0, + size=3, local_size=2, cross_size=1)] + self.assertListEqual(assignments, expected) +``` + +## `test/single/test_run.py` — `function:RunTests.test_get_mpi_implementation` (lines 624-650) + +```python + def test_get_mpi_implementation(self): + def test(output, expected, exit_code=0): + ret = (output, exit_code) if output is not None else None + env = {'VAR': 'val'} + with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m: + implementation = _get_mpi_implementation(env) + self.assertEqual(expected, implementation) + m.assert_called_once_with('mpirun --version', env) + + test(("mpirun (Open MPI) 2.1.1\n" + "Report bugs to http://www.open-mpi.org/community/help/\n"), _OMPI_IMPL) + + test("OpenRTE", _OMPI_IMPL) + + test("IBM Spectrum MPI", _SMPI_IMPL) + + test(("HYDRA build details:\n" + " Version: 3.3a2\n" + " Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL) + + test("Intel(R) MPI", _IMPI_IMPL) + + test("Unknown MPI v1.00", _UNKNOWN_IMPL) + + test("output", exit_code=1, expected=_MISSING_IMPL) + + test(None, _MISSING_IMPL) +``` + +## `test/utils/common.py` — `function:temppath` (lines 113-123) + +```python +def temppath(): + path = tempfile.mktemp() + try: + yield path + finally: + if os.path.exists(path): + if os.path.isfile(path): + os.remove(path) + else: + shutil.rmtree(path) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8698284d403caea3bdc7c22c2a4d6f3e33bcfca7 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/task.json @@ -0,0 +1,52 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-6b5cf1b92b87b04c09cd", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-6b5cf1b92b87b04c09cd", + "project_id": "pyvul__horovod__horovod", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "horovod/runner/js_run.py", + "test/single/test_run.py", + "test/utils/common.py" + ], + "patch_units": { + "before": [ + "function:generate_jsrun_rankfile", + "class:RunTests", + "function:RunTests.test_get_mpi_implementation", + "function:temppath" + ], + "after": [ + "function:generate_jsrun_rankfile", + "class:RunTests", + "function:RunTests.test_get_mpi_implementation", + "function:temppath" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/9a59aba7ebec2d3b4a550d78f09d5950eaae4f6a5115b34a469ec12086d2f9ce/database", + "cache_key": "9a59aba7ebec2d3b4a550d78f09d5950eaae4f6a5115b34a469ec12086d2f9ce", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/1081e42c208320d79afaf0b9bf106151ddacef199590082f3bafbfb34b269c89/database", + "cache_key": "1081e42c208320d79afaf0b9bf106151ddacef199590082f3bafbfb34b269c89", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/63bef52c6fe3fa050ee0776e872386890966412fe8f2e3a182b0a160d99238c8/database", + "cache_key": "63bef52c6fe3fa050ee0776e872386890966412fe8f2e3a182b0a160d99238c8", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-6b5cf1b92b87b04c09cd/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-6b5cf1b92b87b04c09cd/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-6b5cf1b92b87b04c09cd/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8cd6e28070cbeb32db532c99750a05467ca7f18d --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/patch.diff @@ -0,0 +1,70 @@ +diff --git a/flask_unchained/bundles/controller/utils.py b/flask_unchained/bundles/controller/utils.py +index ae9a2db..c9946d9 100644 +--- a/flask_unchained/bundles/controller/utils.py ++++ b/flask_unchained/bundles/controller/utils.py +@@ -6,7 +6,7 @@ from flask_unchained.string_utils import kebab_case, right_replace, snake_case + from flask_unchained._compat import is_local_proxy + from py_meta_utils import _missing + from typing import * +-from urllib.parse import urlsplit ++from urllib.parse import urlsplit, quote as urlquote + from werkzeug.routing import BuildError, UnicodeConverter + + from .attr_constants import CONTROLLER_ROUTES_ATTR, REMOVE_SUFFIXES_ATTR +@@ -183,6 +183,11 @@ def method_name_to_url(method_name) -> str: + return '/' + kebab_case(method_name).strip('-') + + ++def encode_non_url_reserved_characters(url): ++ # safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 ++ return urlquote(url, safe=":/?#[]@!$&'()*+,;=") ++ ++ + # modified from flask_security.utils.get_post_action_redirect + def redirect(where: Optional[str] = None, + default: Optional[str] = None, +@@ -235,7 +240,7 @@ def redirect(where: Optional[str] = None, + + for url in urls: + if _validate_redirect_url(url, _external_host): +- return flask_redirect(url) ++ return flask_redirect(encode_non_url_reserved_characters(url)) + return flask_redirect('/') + + +@@ -289,15 +294,29 @@ def _url_for(endpoint: str, **values) -> Union[str, None]: + + # modified from flask_security.utils.validate_redirect_url + def _validate_redirect_url(url, _external_host=None): +- if url is None or url.strip() == '': ++ url = (url or '').strip().replace('\\', '/') ++ ++ # reject empty urls and urls starting with 3+ slashes or a control character ++ if not url or url.startswith('///') or ord(url[0]) <= 32: + return False ++ + url_next = urlsplit(url) + url_base = urlsplit(request.host_url) +- external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME', '') +- if ((url_next.netloc or url_next.scheme) +- and url_next.netloc != url_base.netloc +- and url_next.netloc not in external_host): +- return False ++ if url_next.netloc or url_next.scheme: ++ # require both netloc and scheme ++ if not url_next.netloc or not url_next.scheme: ++ return False ++ ++ # if external host, require same netloc and scheme ++ external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME', '') ++ if external_host: ++ url_external = urlsplit(external_host) ++ if url_next.netloc == url_external.netloc and url_next.scheme == url_external.scheme: ++ return True ++ ++ # require same netloc and scheme ++ if url_next.netloc != url_base.netloc or url_next.scheme != url_base.scheme: ++ return False + return True + + diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..5a890f56fb2816ce7a9ed251d1ccd859d7131471 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/post_context.md @@ -0,0 +1,103 @@ +# Patch-overlapping Python context after the fix + +## `flask_unchained/bundles/controller/utils.py` — `function:encode_non_url_reserved_characters` (lines 186-188) + +```python +def encode_non_url_reserved_characters(url): + # safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 + return urlquote(url, safe=":/?#[]@!$&'()*+,;=") +``` + +## `flask_unchained/bundles/controller/utils.py` — `function:redirect` (lines 192-244) + +```python +def redirect(where: Optional[str] = None, + default: Optional[str] = None, + override: Optional[str] = None, + _anchor: Optional[str] = None, + _cls: Optional[Union[object, type]] = None, + _external: Optional[bool] = False, + _external_host: Optional[str] = None, + _method: Optional[str] = None, + _scheme: Optional[str] = None, + **values, + ) -> Response: + """ + An improved version of flask's redirect function + + :param where: A URL, endpoint, or config key name to redirect to + :param default: A URL, endpoint, or config key name to redirect to if + ``where`` is invalid + :param override: explicitly redirect to a URL, endpoint, or config key name + (takes precedence over the ``next`` value in query strings or forms) + :param values: the variable arguments of the URL rule + :param _anchor: if provided this is added as anchor to the URL. + :param _cls: if specified, allows a method name to be passed to where, + default, and/or override + :param _external: if set to ``True``, an absolute URL is generated. Server + address can be changed via ``SERVER_NAME`` configuration variable which + defaults to `localhost`. + :param _external_host: if specified, the host of an external server to + generate urls for (eg https://example.com or localhost:8888) + :param _method: if provided this explicitly specifies an HTTP method. + :param _scheme: a string specifying the desired URL scheme. The `_external` + parameter must be set to ``True`` or a :exc:`ValueError` is raised. The + default behavior uses the same scheme as the current request, or + ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no + request context is available. As of Werkzeug 0.10, this also can be set + to an empty string to build protocol-relative URLs. + """ + flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, + _external_host=_external_host, _method=_method, + _scheme=_scheme, **values) + + urls = [url_for(request.args.get('next'), **flask_url_for_kwargs), + url_for(request.form.get('next'), **flask_url_for_kwargs)] + if where: + urls.append(url_for(where, _cls=_cls, **flask_url_for_kwargs)) + if default: + urls.append(url_for(default, _cls=_cls, **flask_url_for_kwargs)) + if override: + urls.insert(0, url_for(override, _cls=_cls, **flask_url_for_kwargs)) + + for url in urls: + if _validate_redirect_url(url, _external_host): + return flask_redirect(encode_non_url_reserved_characters(url)) + return flask_redirect('/') +``` + +## `flask_unchained/bundles/controller/utils.py` — `function:_validate_redirect_url` (lines 296-320) + +```python +def _validate_redirect_url(url, _external_host=None): + url = (url or '').strip().replace('\\', '/') + + # reject empty urls and urls starting with 3+ slashes or a control character + if not url or url.startswith('///') or ord(url[0]) <= 32: + return False + + url_next = urlsplit(url) + url_base = urlsplit(request.host_url) + if url_next.netloc or url_next.scheme: + # require both netloc and scheme + if not url_next.netloc or not url_next.scheme: + return False + + # if external host, require same netloc and scheme + external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME', '') + if external_host: + url_external = urlsplit(external_host) + if url_next.netloc == url_external.netloc and url_next.scheme == url_external.scheme: + return True + + # require same netloc and scheme + if url_next.netloc != url_base.netloc or url_next.scheme != url_base.scheme: + return False + return True +``` + +## `flask_unchained/bundles/controller/utils.py` — `module:@9` (lines 9-9) + +```python +from urllib.parse import urlsplit, quote as urlquote +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..41e732eedb9c4445093ea5e5ece0629d538a7389 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/pre_context.md @@ -0,0 +1,87 @@ +# Patch-overlapping Python context before the fix + +## `flask_unchained/bundles/controller/utils.py` — `function:redirect` (lines 187-239) + +```python +def redirect(where: Optional[str] = None, + default: Optional[str] = None, + override: Optional[str] = None, + _anchor: Optional[str] = None, + _cls: Optional[Union[object, type]] = None, + _external: Optional[bool] = False, + _external_host: Optional[str] = None, + _method: Optional[str] = None, + _scheme: Optional[str] = None, + **values, + ) -> Response: + """ + An improved version of flask's redirect function + + :param where: A URL, endpoint, or config key name to redirect to + :param default: A URL, endpoint, or config key name to redirect to if + ``where`` is invalid + :param override: explicitly redirect to a URL, endpoint, or config key name + (takes precedence over the ``next`` value in query strings or forms) + :param values: the variable arguments of the URL rule + :param _anchor: if provided this is added as anchor to the URL. + :param _cls: if specified, allows a method name to be passed to where, + default, and/or override + :param _external: if set to ``True``, an absolute URL is generated. Server + address can be changed via ``SERVER_NAME`` configuration variable which + defaults to `localhost`. + :param _external_host: if specified, the host of an external server to + generate urls for (eg https://example.com or localhost:8888) + :param _method: if provided this explicitly specifies an HTTP method. + :param _scheme: a string specifying the desired URL scheme. The `_external` + parameter must be set to ``True`` or a :exc:`ValueError` is raised. The + default behavior uses the same scheme as the current request, or + ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no + request context is available. As of Werkzeug 0.10, this also can be set + to an empty string to build protocol-relative URLs. + """ + flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, + _external_host=_external_host, _method=_method, + _scheme=_scheme, **values) + + urls = [url_for(request.args.get('next'), **flask_url_for_kwargs), + url_for(request.form.get('next'), **flask_url_for_kwargs)] + if where: + urls.append(url_for(where, _cls=_cls, **flask_url_for_kwargs)) + if default: + urls.append(url_for(default, _cls=_cls, **flask_url_for_kwargs)) + if override: + urls.insert(0, url_for(override, _cls=_cls, **flask_url_for_kwargs)) + + for url in urls: + if _validate_redirect_url(url, _external_host): + return flask_redirect(url) + return flask_redirect('/') +``` + +## `flask_unchained/bundles/controller/utils.py` — `function:_validate_redirect_url` (lines 291-301) + +```python +def _validate_redirect_url(url, _external_host=None): + if url is None or url.strip() == '': + return False + url_next = urlsplit(url) + url_base = urlsplit(request.host_url) + external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME', '') + if ((url_next.netloc or url_next.scheme) + and url_next.netloc != url_base.netloc + and url_next.netloc not in external_host): + return False + return True +``` + +## `flask_unchained/bundles/controller/utils.py` — `module:@9` (lines 9-9) + +```python +from urllib.parse import urlsplit +``` + +## `flask_unchained/bundles/controller/utils.py` — `module:@10` (lines 10-10) + +```python +from werkzeug.routing import BuildError, UnicodeConverter +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7a5392dc528391e77f82bdb5d9738e3271e312ea --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-796a152aa965ce44a6db", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-796a152aa965ce44a6db", + "project_id": "pyvul__briancappello__flask-unchained", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "flask_unchained/bundles/controller/utils.py" + ], + "patch_units": { + "before": [ + "function:redirect", + "function:_validate_redirect_url", + "module:@9", + "module:@10" + ], + "after": [ + "function:encode_non_url_reserved_characters", + "function:redirect", + "function:_validate_redirect_url", + "module:@9" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/e5fd82bd60056af5aaffb57019a904ba682f11f2d3661ecf6d18301cd87df6af/database", + "cache_key": "e5fd82bd60056af5aaffb57019a904ba682f11f2d3661ecf6d18301cd87df6af", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/7088558c3df474c6d44a72f76f6439b246f196e1d3ef64c90ae22c464de77a19/database", + "cache_key": "7088558c3df474c6d44a72f76f6439b246f196e1d3ef64c90ae22c464de77a19", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/557ece170ef451e56128b15092377dd17ef0a82705cb7e5e3baeb37fda3a5ae0/database", + "cache_key": "557ece170ef451e56128b15092377dd17ef0a82705cb7e5e3baeb37fda3a5ae0", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-796a152aa965ce44a6db/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-796a152aa965ce44a6db/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-796a152aa965ce44a6db/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e97983c2fa039dead5fa725fc87c760aecab5407 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/patch.diff @@ -0,0 +1,245 @@ +diff --git a/changelog.d/8950.misc b/changelog.d/8950.misc +new file mode 100644 +index 000000000..42e0335af +--- /dev/null ++++ b/changelog.d/8950.misc +@@ -0,0 +1 @@ ++Add a maximum size of 50 kilobytes to .well-known lookups. +diff --git a/synapse/http/client.py b/synapse/http/client.py +index df7730078..29f40ddf5 100644 +--- a/synapse/http/client.py ++++ b/synapse/http/client.py +@@ -720,11 +720,14 @@ class SimpleHttpClient: + + try: + length = await make_deferred_yieldable( +- readBodyToFile(response, output_stream, max_size) ++ read_body_with_max_size(response, output_stream, max_size) ++ ) ++ except BodyExceededMaxSize: ++ SynapseError( ++ 502, ++ "Requested file is too large > %r bytes" % (max_size,), ++ Codes.TOO_LARGE, + ) +- except SynapseError: +- # This can happen e.g. because the body is too large. +- raise + except Exception as e: + raise SynapseError(502, ("Failed to download remote body: %s" % e)) from e + +@@ -748,7 +751,11 @@ def _timeout_to_request_timed_out_error(f: Failure): + return f + + +-class _ReadBodyToFileProtocol(protocol.Protocol): ++class BodyExceededMaxSize(Exception): ++ """The maximum allowed size of the HTTP body was exceeded.""" ++ ++ ++class _ReadBodyWithMaxSizeProtocol(protocol.Protocol): + def __init__( + self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] + ): +@@ -761,13 +768,7 @@ class _ReadBodyToFileProtocol(protocol.Protocol): + self.stream.write(data) + self.length += len(data) + if self.max_size is not None and self.length >= self.max_size: +- self.deferred.errback( +- SynapseError( +- 502, +- "Requested file is too large > %r bytes" % (self.max_size,), +- Codes.TOO_LARGE, +- ) +- ) ++ self.deferred.errback(BodyExceededMaxSize()) + self.deferred = defer.Deferred() + self.transport.loseConnection() + +@@ -782,12 +783,15 @@ class _ReadBodyToFileProtocol(protocol.Protocol): + self.deferred.errback(reason) + + +-def readBodyToFile( ++def read_body_with_max_size( + response: IResponse, stream: BinaryIO, max_size: Optional[int] + ) -> defer.Deferred: + """ + Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. + ++ If the maximum file size is reached, the returned Deferred will resolve to a ++ Failure with a BodyExceededMaxSize exception. ++ + Args: + response: The HTTP response to read from. + stream: The file-object to write to. +@@ -798,7 +802,7 @@ def readBodyToFile( + """ + + d = defer.Deferred() +- response.deliverBody(_ReadBodyToFileProtocol(stream, d, max_size)) ++ response.deliverBody(_ReadBodyWithMaxSizeProtocol(stream, d, max_size)) + return d + + +diff --git a/synapse/http/federation/well_known_resolver.py b/synapse/http/federation/well_known_resolver.py +index 5e08ef166..b3b6dbcab 100644 +--- a/synapse/http/federation/well_known_resolver.py ++++ b/synapse/http/federation/well_known_resolver.py +@@ -15,17 +15,19 @@ + import logging + import random + import time ++from io import BytesIO + from typing import Callable, Dict, Optional, Tuple + + import attr + + from twisted.internet import defer + from twisted.internet.interfaces import IReactorTime +-from twisted.web.client import RedirectAgent, readBody ++from twisted.web.client import RedirectAgent + from twisted.web.http import stringToDatetime + from twisted.web.http_headers import Headers + from twisted.web.iweb import IAgent, IResponse + ++from synapse.http.client import BodyExceededMaxSize, read_body_with_max_size + from synapse.logging.context import make_deferred_yieldable + from synapse.util import Clock, json_decoder + from synapse.util.caches.ttlcache import TTLCache +@@ -53,6 +55,9 @@ WELL_KNOWN_MAX_CACHE_PERIOD = 48 * 3600 + # lower bound for .well-known cache period + WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 + ++# The maximum size (in bytes) to allow a well-known file to be. ++WELL_KNOWN_MAX_SIZE = 50 * 1024 # 50 KiB ++ + # Attempt to refetch a cached well-known N% of the TTL before it expires. + # e.g. if set to 0.2 and we have a cached entry with a TTL of 5mins, then + # we'll start trying to refetch 1 minute before it expires. +@@ -229,6 +234,9 @@ class WellKnownResolver: + server_name: name of the server, from the requested url + retry: Whether to retry the request if it fails. + ++ Raises: ++ _FetchWellKnownFailure if we fail to lookup a result ++ + Returns: + Returns the response object and body. Response may be a non-200 response. + """ +@@ -250,7 +258,11 @@ class WellKnownResolver: + b"GET", uri, headers=Headers(headers) + ) + ) +- body = await make_deferred_yieldable(readBody(response)) ++ body_stream = BytesIO() ++ await make_deferred_yieldable( ++ read_body_with_max_size(response, body_stream, WELL_KNOWN_MAX_SIZE) ++ ) ++ body = body_stream.getvalue() + + if 500 <= response.code < 600: + raise Exception("Non-200 response %s" % (response.code,)) +@@ -259,6 +271,15 @@ class WellKnownResolver: + except defer.CancelledError: + # Bail if we've been cancelled + raise ++ except BodyExceededMaxSize: ++ # If the well-known file was too large, do not keep attempting ++ # to download it, but consider it a temporary error. ++ logger.warning( ++ "Requested .well-known file for %s is too large > %r bytes", ++ server_name.decode("ascii"), ++ WELL_KNOWN_MAX_SIZE, ++ ) ++ raise _FetchWellKnownFailure(temporary=True) + except Exception as e: + if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: + logger.info("Error fetching %s: %s", uri_str, e) +diff --git a/synapse/http/matrixfederationclient.py b/synapse/http/matrixfederationclient.py +index c96299472..b261e078c 100644 +--- a/synapse/http/matrixfederationclient.py ++++ b/synapse/http/matrixfederationclient.py +@@ -37,16 +37,19 @@ from twisted.web.iweb import IBodyProducer, IResponse + import synapse.metrics + import synapse.util.retryutils + from synapse.api.errors import ( ++ Codes, + FederationDeniedError, + HttpResponseException, + RequestSendFailed, ++ SynapseError, + ) + from synapse.http import QuieterFileBodyProducer + from synapse.http.client import ( + BlacklistingAgentWrapper, + BlacklistingReactorWrapper, ++ BodyExceededMaxSize, + encode_query_args, +- readBodyToFile, ++ read_body_with_max_size, + ) + from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent + from synapse.logging.context import make_deferred_yieldable +@@ -975,9 +978,15 @@ class MatrixFederationHttpClient: + headers = dict(response.headers.getAllRawHeaders()) + + try: +- d = readBodyToFile(response, output_stream, max_size) ++ d = read_body_with_max_size(response, output_stream, max_size) + d.addTimeout(self.default_timeout, self.reactor) + length = await make_deferred_yieldable(d) ++ except BodyExceededMaxSize: ++ msg = "Requested file is too large > %r bytes" % (max_size,) ++ logger.warning( ++ "{%s} [%s] %s", request.txn_id, request.destination, msg, ++ ) ++ SynapseError(502, msg, Codes.TOO_LARGE) + except Exception as e: + logger.warning( + "{%s} [%s] Error reading response: %s", +diff --git a/tests/http/federation/test_matrix_federation_agent.py b/tests/http/federation/test_matrix_federation_agent.py +index 626acdcaa..4e51839d0 100644 +--- a/tests/http/federation/test_matrix_federation_agent.py ++++ b/tests/http/federation/test_matrix_federation_agent.py +@@ -36,6 +36,7 @@ from synapse.crypto.context_factory import FederationPolicyForHTTPS + from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent + from synapse.http.federation.srv_resolver import Server + from synapse.http.federation.well_known_resolver import ( ++ WELL_KNOWN_MAX_SIZE, + WellKnownResolver, + _cache_period_from_headers, + ) +@@ -1107,6 +1108,32 @@ class MatrixFederationAgentTests(unittest.TestCase): + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, None) + ++ def test_well_known_too_large(self): ++ """A well-known query that returns a result which is too large should be rejected.""" ++ self.reactor.lookups["testserv"] = "1.2.3.4" ++ ++ fetch_d = defer.ensureDeferred( ++ self.well_known_resolver.get_well_known(b"testserv") ++ ) ++ ++ # there should be an attempt to connect on port 443 for the .well-known ++ clients = self.reactor.tcpClients ++ self.assertEqual(len(clients), 1) ++ (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) ++ self.assertEqual(host, "1.2.3.4") ++ self.assertEqual(port, 443) ++ ++ self._handle_well_known_connection( ++ client_factory, ++ expected_sni=b"testserv", ++ response_headers={b"Cache-Control": b"max-age=1000"}, ++ content=b'{ "m.server": "' + (b"a" * WELL_KNOWN_MAX_SIZE) + b'" }', ++ ) ++ ++ # The result is sucessful, but disabled delegation. ++ r = self.successResultOf(fetch_d) ++ self.assertIsNone(r.delegated_server) ++ + def test_srv_fallbacks(self): + """Test that other SRV results are tried if the first one fails. + """ diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8e4785c0ddeca4ed2339b31917c36d18601b4884 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/post_context.md @@ -0,0 +1,2990 @@ +# Patch-overlapping Python context after the fix + +## `synapse/http/client.py` — `class:SimpleHttpClient` (lines 280-739) + +```python +class SimpleHttpClient: + """ + A simple, no-frills HTTP client with methods that wrap up common ways of + using HTTP in Matrix + """ + + def __init__( + self, + hs: "HomeServer", + treq_args: Dict[str, Any] = {}, + ip_whitelist: Optional[IPSet] = None, + ip_blacklist: Optional[IPSet] = None, + http_proxy: Optional[bytes] = None, + https_proxy: Optional[bytes] = None, + ): + """ + Args: + hs + treq_args: Extra keyword arguments to be given to treq.request. + ip_blacklist: The IP addresses that are blacklisted that + we may not request. + ip_whitelist: The whitelisted IP addresses, that we can + request if it were otherwise caught in a blacklist. + http_proxy: proxy server to use for http connections. host[:port] + https_proxy: proxy server to use for https connections. host[:port] + """ + self.hs = hs + + self._ip_whitelist = ip_whitelist + self._ip_blacklist = ip_blacklist + self._extra_treq_args = treq_args + + self.user_agent = hs.version_string + self.clock = hs.get_clock() + if hs.config.user_agent_suffix: + self.user_agent = "%s %s" % (self.user_agent, hs.config.user_agent_suffix) + + # We use this for our body producers to ensure that they use the correct + # reactor. + self._cooperator = Cooperator(scheduler=_make_scheduler(hs.get_reactor())) + + self.user_agent = self.user_agent.encode("ascii") + + if self._ip_blacklist: + # If we have an IP blacklist, we need to use a DNS resolver which + # filters out blacklisted IP addresses, to prevent DNS rebinding. + self.reactor = BlacklistingReactorWrapper( + hs.get_reactor(), self._ip_whitelist, self._ip_blacklist + ) + else: + self.reactor = hs.get_reactor() + + # the pusher makes lots of concurrent SSL connections to sygnal, and + # tends to do so in batches, so we need to allow the pool to keep + # lots of idle connections around. + pool = HTTPConnectionPool(self.reactor) + # XXX: The justification for using the cache factor here is that larger instances + # will need both more cache and more connections. + # Still, this should probably be a separate dial + pool.maxPersistentPerHost = max((100 * hs.config.caches.global_factor, 5)) + pool.cachedConnectionTimeout = 2 * 60 + + self.agent = ProxyAgent( + self.reactor, + connectTimeout=15, + contextFactory=self.hs.get_http_client_context_factory(), + pool=pool, + http_proxy=http_proxy, + https_proxy=https_proxy, + ) + + if self._ip_blacklist: + # If we have an IP blacklist, we then install the blacklisting Agent + # which prevents direct access to IP addresses, that are not caught + # by the DNS resolution. + self.agent = BlacklistingAgentWrapper( + self.agent, + ip_whitelist=self._ip_whitelist, + ip_blacklist=self._ip_blacklist, + ) + + async def request( + self, + method: str, + uri: str, + data: Optional[bytes] = None, + headers: Optional[Headers] = None, + ) -> IResponse: + """ + Args: + method: HTTP method to use. + uri: URI to query. + data: Data to send in the request body, if applicable. + headers: Request headers. + + Returns: + Response object, once the headers have been read. + + Raises: + RequestTimedOutError if the request times out before the headers are read + + """ + outgoing_requests_counter.labels(method).inc() + + # log request but strip `access_token` (AS requests for example include this) + logger.debug("Sending request %s %s", method, redact_uri(uri)) + + with start_active_span( + "outgoing-client-request", + tags={ + tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, + tags.HTTP_METHOD: method, + tags.HTTP_URL: uri, + }, + finish_on_close=True, + ): + try: + body_producer = None + if data is not None: + body_producer = QuieterFileBodyProducer( + BytesIO(data), cooperator=self._cooperator, + ) + + request_deferred = treq.request( + method, + uri, + agent=self.agent, + data=body_producer, + headers=headers, + **self._extra_treq_args, + ) # type: defer.Deferred + + # we use our own timeout mechanism rather than treq's as a workaround + # for https://twistedmatrix.com/trac/ticket/9534. + request_deferred = timeout_deferred( + request_deferred, 60, self.hs.get_reactor(), + ) + + # turn timeouts into RequestTimedOutErrors + request_deferred.addErrback(_timeout_to_request_timed_out_error) + + response = await make_deferred_yieldable(request_deferred) + + incoming_responses_counter.labels(method, response.code).inc() + logger.info( + "Received response to %s %s: %s", + method, + redact_uri(uri), + response.code, + ) + return response + except Exception as e: + incoming_responses_counter.labels(method, "ERR").inc() + logger.info( + "Error sending request to %s %s: %s %s", + method, + redact_uri(uri), + type(e).__name__, + e.args[0], + ) + set_tag(tags.ERROR, True) + set_tag("error_reason", e.args[0]) + raise + + async def post_urlencoded_get_json( + self, + uri: str, + args: Optional[Mapping[str, Union[str, List[str]]]] = None, + headers: Optional[RawHeaders] = None, + ) -> Any: + """ + Args: + uri: uri to query + args: parameters to be url-encoded in the body + headers: a map from header name to a list of values for that header + + Returns: + parsed json + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException: On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + + # TODO: Do we ever want to log message contents? + logger.debug("post_urlencoded_get_json args: %s", args) + + query_bytes = encode_query_args(args) + + actual_headers = { + b"Content-Type": [b"application/x-www-form-urlencoded"], + b"User-Agent": [self.user_agent], + b"Accept": [b"application/json"], + } + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request( + "POST", uri, headers=Headers(actual_headers), data=query_bytes + ) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return json_decoder.decode(body.decode("utf-8")) + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + async def post_json_get_json( + self, uri: str, post_json: Any, headers: Optional[RawHeaders] = None + ) -> Any: + """ + + Args: + uri: URI to query. + post_json: request body, to be encoded as json + headers: a map from header name to a list of values for that header + + Returns: + parsed json + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException: On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + json_str = encode_canonical_json(post_json) + + logger.debug("HTTP POST %s -> %s", json_str, uri) + + actual_headers = { + b"Content-Type": [b"application/json"], + b"User-Agent": [self.user_agent], + b"Accept": [b"application/json"], + } + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request( + "POST", uri, headers=Headers(actual_headers), data=json_str + ) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return json_decoder.decode(body.decode("utf-8")) + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + async def get_json( + self, + uri: str, + args: Optional[QueryParams] = None, + headers: Optional[RawHeaders] = None, + ) -> Any: + """Gets some json from the given URI. + + Args: + uri: The URI to request, not including query parameters + args: A dictionary used to create query string + headers: a map from header name to a list of values for that header + Returns: + Succeeds when we get a 2xx HTTP response, with the HTTP body as JSON. + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + actual_headers = {b"Accept": [b"application/json"]} + if headers: + actual_headers.update(headers) # type: ignore + + body = await self.get_raw(uri, args, headers=headers) + return json_decoder.decode(body.decode("utf-8")) + + async def put_json( + self, + uri: str, + json_body: Any, + args: Optional[QueryParams] = None, + headers: RawHeaders = None, + ) -> Any: + """Puts some json to the given URI. + + Args: + uri: The URI to request, not including query parameters + json_body: The JSON to put in the HTTP body, + args: A dictionary used to create query strings + headers: a map from header name to a list of values for that header + Returns: + Succeeds when we get a 2xx HTTP response, with the HTTP body as JSON. + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + if args: + query_str = urllib.parse.urlencode(args, True) + uri = "%s?%s" % (uri, query_str) + + json_str = encode_canonical_json(json_body) + + actual_headers = { + b"Content-Type": [b"application/json"], + b"User-Agent": [self.user_agent], + b"Accept": [b"application/json"], + } + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request( + "PUT", uri, headers=Headers(actual_headers), data=json_str + ) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return json_decoder.decode(body.decode("utf-8")) + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + async def get_raw( + self, + uri: str, + args: Optional[QueryParams] = None, + headers: Optional[RawHeaders] = None, + ) -> bytes: + """Gets raw text from the given URI. + + Args: + uri: The URI to request, not including query parameters + args: A dictionary used to create query strings + headers: a map from header name to a list of values for that header + Returns: + Succeeds when we get a 2xx HTTP response, with the + HTTP body as bytes. + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException on a non-2xx HTTP response. + """ + if args: + query_str = urllib.parse.urlencode(args, True) + uri = "%s?%s" % (uri, query_str) + + actual_headers = {b"User-Agent": [self.user_agent]} + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request("GET", uri, headers=Headers(actual_headers)) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return body + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + # XXX: FIXME: This is horribly copy-pasted from matrixfederationclient. + # The two should be factored out. + + async def get_file( + self, + url: str, + output_stream: BinaryIO, + max_size: Optional[int] = None, + headers: Optional[RawHeaders] = None, + ) -> Tuple[int, Dict[bytes, List[bytes]], str, int]: + """GETs a file from a given URL + Args: + url: The URL to GET + output_stream: File to write the response body to. + headers: A map from header name to a list of values for that header + Returns: + A tuple of the file length, dict of the response + headers, absolute URI of the response and HTTP response code. + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + SynapseError: if the response is not a 2xx, the remote file is too large, or + another exception happens during the download. + """ + + actual_headers = {b"User-Agent": [self.user_agent]} + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request("GET", url, headers=Headers(actual_headers)) + + resp_headers = dict(response.headers.getAllRawHeaders()) + + if ( + b"Content-Length" in resp_headers + and max_size + and int(resp_headers[b"Content-Length"][0]) > max_size + ): + logger.warning("Requested URL is too large > %r bytes" % (max_size,)) + raise SynapseError( + 502, + "Requested file is too large > %r bytes" % (max_size,), + Codes.TOO_LARGE, + ) + + if response.code > 299: + logger.warning("Got %d when downloading %s" % (response.code, url)) + raise SynapseError(502, "Got error %d" % (response.code,), Codes.UNKNOWN) + + # TODO: if our Content-Type is HTML or something, just read the first + # N bytes into RAM rather than saving it all to disk only to read it + # straight back in again + + try: + length = await make_deferred_yieldable( + read_body_with_max_size(response, output_stream, max_size) + ) + except BodyExceededMaxSize: + SynapseError( + 502, + "Requested file is too large > %r bytes" % (max_size,), + Codes.TOO_LARGE, + ) + except Exception as e: + raise SynapseError(502, ("Failed to download remote body: %s" % e)) from e + + return ( + length, + resp_headers, + response.request.absoluteURI.decode("ascii"), + response.code, + ) +``` + +## `synapse/http/client.py` — `function:SimpleHttpClient.get_file` (lines 668-739) + +```python + async def get_file( + self, + url: str, + output_stream: BinaryIO, + max_size: Optional[int] = None, + headers: Optional[RawHeaders] = None, + ) -> Tuple[int, Dict[bytes, List[bytes]], str, int]: + """GETs a file from a given URL + Args: + url: The URL to GET + output_stream: File to write the response body to. + headers: A map from header name to a list of values for that header + Returns: + A tuple of the file length, dict of the response + headers, absolute URI of the response and HTTP response code. + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + SynapseError: if the response is not a 2xx, the remote file is too large, or + another exception happens during the download. + """ + + actual_headers = {b"User-Agent": [self.user_agent]} + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request("GET", url, headers=Headers(actual_headers)) + + resp_headers = dict(response.headers.getAllRawHeaders()) + + if ( + b"Content-Length" in resp_headers + and max_size + and int(resp_headers[b"Content-Length"][0]) > max_size + ): + logger.warning("Requested URL is too large > %r bytes" % (max_size,)) + raise SynapseError( + 502, + "Requested file is too large > %r bytes" % (max_size,), + Codes.TOO_LARGE, + ) + + if response.code > 299: + logger.warning("Got %d when downloading %s" % (response.code, url)) + raise SynapseError(502, "Got error %d" % (response.code,), Codes.UNKNOWN) + + # TODO: if our Content-Type is HTML or something, just read the first + # N bytes into RAM rather than saving it all to disk only to read it + # straight back in again + + try: + length = await make_deferred_yieldable( + read_body_with_max_size(response, output_stream, max_size) + ) + except BodyExceededMaxSize: + SynapseError( + 502, + "Requested file is too large > %r bytes" % (max_size,), + Codes.TOO_LARGE, + ) + except Exception as e: + raise SynapseError(502, ("Failed to download remote body: %s" % e)) from e + + return ( + length, + resp_headers, + response.request.absoluteURI.decode("ascii"), + response.code, + ) +``` + +## `synapse/http/client.py` — `class:BodyExceededMaxSize` (lines 754-755) + +```python +class BodyExceededMaxSize(Exception): + """The maximum allowed size of the HTTP body was exceeded.""" +``` + +## `synapse/http/client.py` — `class:_ReadBodyWithMaxSizeProtocol` (lines 758-783) + +```python +class _ReadBodyWithMaxSizeProtocol(protocol.Protocol): + def __init__( + self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] + ): + self.stream = stream + self.deferred = deferred + self.length = 0 + self.max_size = max_size + + def dataReceived(self, data: bytes) -> None: + self.stream.write(data) + self.length += len(data) + if self.max_size is not None and self.length >= self.max_size: + self.deferred.errback(BodyExceededMaxSize()) + self.deferred = defer.Deferred() + self.transport.loseConnection() + + def connectionLost(self, reason: Failure) -> None: + if reason.check(ResponseDone): + self.deferred.callback(self.length) + elif reason.check(PotentialDataLoss): + # stolen from https://github.com/twisted/treq/pull/49/files + # http://twistedmatrix.com/trac/ticket/4840 + self.deferred.callback(self.length) + else: + self.deferred.errback(reason) +``` + +## `synapse/http/client.py` — `function:_ReadBodyWithMaxSizeProtocol.dataReceived` (lines 767-773) + +```python + def dataReceived(self, data: bytes) -> None: + self.stream.write(data) + self.length += len(data) + if self.max_size is not None and self.length >= self.max_size: + self.deferred.errback(BodyExceededMaxSize()) + self.deferred = defer.Deferred() + self.transport.loseConnection() +``` + +## `synapse/http/client.py` — `function:read_body_with_max_size` (lines 786-806) + +```python +def read_body_with_max_size( + response: IResponse, stream: BinaryIO, max_size: Optional[int] +) -> defer.Deferred: + """ + Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. + + If the maximum file size is reached, the returned Deferred will resolve to a + Failure with a BodyExceededMaxSize exception. + + Args: + response: The HTTP response to read from. + stream: The file-object to write to. + max_size: The maximum file size to allow. + + Returns: + A Deferred which resolves to the length of the read body. + """ + + d = defer.Deferred() + response.deliverBody(_ReadBodyWithMaxSizeProtocol(stream, d, max_size)) + return d +``` + +## `synapse/http/federation/well_known_resolver.py` — `class:WellKnownResolver` (lines 83-291) + +```python +class WellKnownResolver: + """Handles well-known lookups for matrix servers. + """ + + def __init__( + self, + reactor: IReactorTime, + agent: IAgent, + user_agent: bytes, + well_known_cache: Optional[TTLCache] = None, + had_well_known_cache: Optional[TTLCache] = None, + ): + self._reactor = reactor + self._clock = Clock(reactor) + + if well_known_cache is None: + well_known_cache = _well_known_cache + + if had_well_known_cache is None: + had_well_known_cache = _had_valid_well_known_cache + + self._well_known_cache = well_known_cache + self._had_valid_well_known_cache = had_well_known_cache + self._well_known_agent = RedirectAgent(agent) + self.user_agent = user_agent + + async def get_well_known(self, server_name: bytes) -> WellKnownLookupResult: + """Attempt to fetch and parse a .well-known file for the given server + + Args: + server_name: name of the server, from the requested url + + Returns: + The result of the lookup + """ + try: + prev_result, expiry, ttl = self._well_known_cache.get_with_expiry( + server_name + ) + + now = self._clock.time() + if now < expiry - WELL_KNOWN_GRACE_PERIOD_FACTOR * ttl: + return WellKnownLookupResult(delegated_server=prev_result) + except KeyError: + prev_result = None + + # TODO: should we linearise so that we don't end up doing two .well-known + # requests for the same server in parallel? + try: + with Measure(self._clock, "get_well_known"): + result, cache_period = await self._fetch_well_known( + server_name + ) # type: Optional[bytes], float + + except _FetchWellKnownFailure as e: + if prev_result and e.temporary: + # This is a temporary failure and we have a still valid cached + # result, so lets return that. Hopefully the next time we ask + # the remote will be back up again. + return WellKnownLookupResult(delegated_server=prev_result) + + result = None + + if self._had_valid_well_known_cache.get(server_name, False): + # We have recently seen a valid well-known record for this + # server, so we cache the lack of well-known for a shorter time. + cache_period = WELL_KNOWN_DOWN_CACHE_PERIOD + else: + cache_period = WELL_KNOWN_INVALID_CACHE_PERIOD + + # add some randomness to the TTL to avoid a stampeding herd + cache_period *= random.uniform( + 1 - WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + 1 + WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + ) + + if cache_period > 0: + self._well_known_cache.set(server_name, result, cache_period) + + return WellKnownLookupResult(delegated_server=result) + + async def _fetch_well_known(self, server_name: bytes) -> Tuple[bytes, float]: + """Actually fetch and parse a .well-known, without checking the cache + + Args: + server_name: name of the server, from the requested url + + Raises: + _FetchWellKnownFailure if we fail to lookup a result + + Returns: + The lookup result and cache period. + """ + + had_valid_well_known = self._had_valid_well_known_cache.get(server_name, False) + + # We do this in two steps to differentiate between possibly transient + # errors (e.g. can't connect to host, 503 response) and more permanent + # errors (such as getting a 404 response). + response, body = await self._make_well_known_request( + server_name, retry=had_valid_well_known + ) + + try: + if response.code != 200: + raise Exception("Non-200 response %s" % (response.code,)) + + parsed_body = json_decoder.decode(body.decode("utf-8")) + logger.info("Response from .well-known: %s", parsed_body) + + result = parsed_body["m.server"].encode("ascii") + except defer.CancelledError: + # Bail if we've been cancelled + raise + except Exception as e: + logger.info("Error parsing well-known for %s: %s", server_name, e) + raise _FetchWellKnownFailure(temporary=False) + + cache_period = _cache_period_from_headers( + response.headers, time_now=self._reactor.seconds + ) + if cache_period is None: + cache_period = WELL_KNOWN_DEFAULT_CACHE_PERIOD + # add some randomness to the TTL to avoid a stampeding herd every 24 hours + # after startup + cache_period *= random.uniform( + 1 - WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + 1 + WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + ) + else: + cache_period = min(cache_period, WELL_KNOWN_MAX_CACHE_PERIOD) + cache_period = max(cache_period, WELL_KNOWN_MIN_CACHE_PERIOD) + + # We got a success, mark as such in the cache + self._had_valid_well_known_cache.set( + server_name, + bool(result), + cache_period + WELL_KNOWN_REMEMBER_DOMAIN_HAD_VALID, + ) + + return result, cache_period + + async def _make_well_known_request( + self, server_name: bytes, retry: bool + ) -> Tuple[IResponse, bytes]: + """Make the well known request. + + This will retry the request if requested and it fails (with unable + to connect or receives a 5xx error). + + Args: + server_name: name of the server, from the requested url + retry: Whether to retry the request if it fails. + + Raises: + _FetchWellKnownFailure if we fail to lookup a result + + Returns: + Returns the response object and body. Response may be a non-200 response. + """ + uri = b"https://%s/.well-known/matrix/server" % (server_name,) + uri_str = uri.decode("ascii") + + headers = { + b"User-Agent": [self.user_agent], + } + + i = 0 + while True: + i += 1 + + logger.info("Fetching %s", uri_str) + try: + response = await make_deferred_yieldable( + self._well_known_agent.request( + b"GET", uri, headers=Headers(headers) + ) + ) + body_stream = BytesIO() + await make_deferred_yieldable( + read_body_with_max_size(response, body_stream, WELL_KNOWN_MAX_SIZE) + ) + body = body_stream.getvalue() + + if 500 <= response.code < 600: + raise Exception("Non-200 response %s" % (response.code,)) + + return response, body + except defer.CancelledError: + # Bail if we've been cancelled + raise + except BodyExceededMaxSize: + # If the well-known file was too large, do not keep attempting + # to download it, but consider it a temporary error. + logger.warning( + "Requested .well-known file for %s is too large > %r bytes", + server_name.decode("ascii"), + WELL_KNOWN_MAX_SIZE, + ) + raise _FetchWellKnownFailure(temporary=True) + except Exception as e: + if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: + logger.info("Error fetching %s: %s", uri_str, e) + raise _FetchWellKnownFailure(temporary=True) + + logger.info("Error fetching %s: %s. Retrying", uri_str, e) + + # Sleep briefly in the hopes that they come back up + await self._clock.sleep(0.5) +``` + +## `synapse/http/federation/well_known_resolver.py` — `function:WellKnownResolver._make_well_known_request` (lines 225-291) + +```python + async def _make_well_known_request( + self, server_name: bytes, retry: bool + ) -> Tuple[IResponse, bytes]: + """Make the well known request. + + This will retry the request if requested and it fails (with unable + to connect or receives a 5xx error). + + Args: + server_name: name of the server, from the requested url + retry: Whether to retry the request if it fails. + + Raises: + _FetchWellKnownFailure if we fail to lookup a result + + Returns: + Returns the response object and body. Response may be a non-200 response. + """ + uri = b"https://%s/.well-known/matrix/server" % (server_name,) + uri_str = uri.decode("ascii") + + headers = { + b"User-Agent": [self.user_agent], + } + + i = 0 + while True: + i += 1 + + logger.info("Fetching %s", uri_str) + try: + response = await make_deferred_yieldable( + self._well_known_agent.request( + b"GET", uri, headers=Headers(headers) + ) + ) + body_stream = BytesIO() + await make_deferred_yieldable( + read_body_with_max_size(response, body_stream, WELL_KNOWN_MAX_SIZE) + ) + body = body_stream.getvalue() + + if 500 <= response.code < 600: + raise Exception("Non-200 response %s" % (response.code,)) + + return response, body + except defer.CancelledError: + # Bail if we've been cancelled + raise + except BodyExceededMaxSize: + # If the well-known file was too large, do not keep attempting + # to download it, but consider it a temporary error. + logger.warning( + "Requested .well-known file for %s is too large > %r bytes", + server_name.decode("ascii"), + WELL_KNOWN_MAX_SIZE, + ) + raise _FetchWellKnownFailure(temporary=True) + except Exception as e: + if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: + logger.info("Error fetching %s: %s", uri_str, e) + raise _FetchWellKnownFailure(temporary=True) + + logger.info("Error fetching %s: %s. Retrying", uri_str, e) + + # Sleep briefly in the hopes that they come back up + await self._clock.sleep(0.5) +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@18` (lines 18-18) + +```python +from io import BytesIO +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@25` (lines 25-25) + +```python +from twisted.web.client import RedirectAgent +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@30` (lines 30-30) + +```python +from synapse.http.client import BodyExceededMaxSize, read_body_with_max_size +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@59` (lines 59-59) + +```python +WELL_KNOWN_MAX_SIZE = 50 * 1024 # 50 KiB +``` + +## `synapse/http/matrixfederationclient.py` — `class:MatrixFederationHttpClient` (lines 212-1008) + +```python +class MatrixFederationHttpClient: + """HTTP client used to talk to other homeservers over the federation + protocol. Send client certificates and signs requests. + + Attributes: + agent (twisted.web.client.Agent): The twisted Agent used to send the + requests. + """ + + def __init__(self, hs, tls_client_options_factory): + self.hs = hs + self.signing_key = hs.signing_key + self.server_name = hs.hostname + + # We need to use a DNS resolver which filters out blacklisted IP + # addresses, to prevent DNS rebinding. + self.reactor = BlacklistingReactorWrapper( + hs.get_reactor(), None, hs.config.federation_ip_range_blacklist + ) + + user_agent = hs.version_string + if hs.config.user_agent_suffix: + user_agent = "%s %s" % (user_agent, hs.config.user_agent_suffix) + user_agent = user_agent.encode("ascii") + + self.agent = MatrixFederationAgent( + self.reactor, + tls_client_options_factory, + user_agent, + hs.config.federation_ip_range_blacklist, + ) + + # Use a BlacklistingAgentWrapper to prevent circumventing the IP + # blacklist via IP literals in server names + self.agent = BlacklistingAgentWrapper( + self.agent, ip_blacklist=hs.config.federation_ip_range_blacklist, + ) + + self.clock = hs.get_clock() + self._store = hs.get_datastore() + self.version_string_bytes = hs.version_string.encode("ascii") + self.default_timeout = 60 + + def schedule(x): + self.reactor.callLater(_EPSILON, x) + + self._cooperator = Cooperator(scheduler=schedule) + + async def _send_request_with_optional_trailing_slash( + self, + request: MatrixFederationRequest, + try_trailing_slash_on_400: bool = False, + **send_request_args + ) -> IResponse: + """Wrapper for _send_request which can optionally retry the request + upon receiving a combination of a 400 HTTP response code and a + 'M_UNRECOGNIZED' errcode. This is a workaround for Synapse <= v0.99.3 + due to #3622. + + Args: + request: details of request to be sent + try_trailing_slash_on_400: Whether on receiving a 400 + 'M_UNRECOGNIZED' from the server to retry the request with a + trailing slash appended to the request path. + send_request_args: A dictionary of arguments to pass to `_send_request()`. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + + Returns: + Parsed JSON response body. + """ + try: + response = await self._send_request(request, **send_request_args) + except HttpResponseException as e: + # Received an HTTP error > 300. Check if it meets the requirements + # to retry with a trailing slash + if not try_trailing_slash_on_400: + raise + + if e.code != 400 or e.to_synapse_error().errcode != "M_UNRECOGNIZED": + raise + + # Retry with a trailing slash if we received a 400 with + # 'M_UNRECOGNIZED' which some endpoints can return when omitting a + # trailing slash on Synapse <= v0.99.3. + logger.info("Retrying request with trailing slash") + + # Request is frozen so we create a new instance + request = attr.evolve(request, path=request.path + "/") + + response = await self._send_request(request, **send_request_args) + + return response + + async def _send_request( + self, + request: MatrixFederationRequest, + retry_on_dns_fail: bool = True, + timeout: Optional[int] = None, + long_retries: bool = False, + ignore_backoff: bool = False, + backoff_on_404: bool = False, + ) -> IResponse: + """ + Sends a request to the given server. + + Args: + request: details of request to be sent + + retry_on_dns_fail: true if the request should be retied on DNS failures + + timeout: number of milliseconds to wait for the response headers + (including connecting to the server), *for each attempt*. + 60s by default. + + long_retries: whether to use the long retry algorithm. + + The regular retry algorithm makes 4 attempts, with intervals + [0.5s, 1s, 2s]. + + The long retry algorithm makes 11 attempts, with intervals + [4s, 16s, 60s, 60s, ...] + + Both algorithms add -20%/+40% jitter to the retry intervals. + + Note that the above intervals are *in addition* to the time spent + waiting for the request to complete (up to `timeout` ms). + + NB: the long retry algorithm takes over 20 minutes to complete, with + a default timeout of 60s! + + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + backoff_on_404: Back off if we get a 404 + + Returns: + Resolves with the HTTP response object on success. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + if timeout: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + if ( + self.hs.config.federation_domain_whitelist is not None + and request.destination not in self.hs.config.federation_domain_whitelist + ): + raise FederationDeniedError(request.destination) + + limiter = await synapse.util.retryutils.get_retry_limiter( + request.destination, + self.clock, + self._store, + backoff_on_404=backoff_on_404, + ignore_backoff=ignore_backoff, + ) + + method_bytes = request.method.encode("ascii") + destination_bytes = request.destination.encode("ascii") + path_bytes = request.path.encode("ascii") + if request.query: + query_bytes = encode_query_args(request.query) + else: + query_bytes = b"" + + scope = start_active_span( + "outgoing-federation-request", + tags={ + tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, + tags.PEER_ADDRESS: request.destination, + tags.HTTP_METHOD: request.method, + tags.HTTP_URL: request.path, + }, + finish_on_close=True, + ) + + # Inject the span into the headers + headers_dict = {} # type: Dict[bytes, List[bytes]] + inject_active_span_byte_dict(headers_dict, request.destination) + + headers_dict[b"User-Agent"] = [self.version_string_bytes] + + with limiter, scope: + # XXX: Would be much nicer to retry only at the transaction-layer + # (once we have reliable transactions in place) + if long_retries: + retries_left = MAX_LONG_RETRIES + else: + retries_left = MAX_SHORT_RETRIES + + url_bytes = request.uri + url_str = url_bytes.decode("ascii") + + url_to_sign_bytes = urllib.parse.urlunparse( + (b"", b"", path_bytes, None, query_bytes, b"") + ) + + while True: + try: + json = request.get_json() + if json: + headers_dict[b"Content-Type"] = [b"application/json"] + auth_headers = self.build_auth_headers( + destination_bytes, method_bytes, url_to_sign_bytes, json + ) + data = encode_canonical_json(json) + producer = QuieterFileBodyProducer( + BytesIO(data), cooperator=self._cooperator + ) # type: Optional[IBodyProducer] + else: + producer = None + auth_headers = self.build_auth_headers( + destination_bytes, method_bytes, url_to_sign_bytes + ) + + headers_dict[b"Authorization"] = auth_headers + + logger.debug( + "{%s} [%s] Sending request: %s %s; timeout %fs", + request.txn_id, + request.destination, + request.method, + url_str, + _sec_timeout, + ) + + outgoing_requests_counter.labels(request.method).inc() + + try: + with Measure(self.clock, "outbound_request"): + # we don't want all the fancy cookie and redirect handling + # that treq.request gives: just use the raw Agent. + request_deferred = self.agent.request( + method_bytes, + url_bytes, + headers=Headers(headers_dict), + bodyProducer=producer, + ) + + request_deferred = timeout_deferred( + request_deferred, + timeout=_sec_timeout, + reactor=self.reactor, + ) + + response = await request_deferred + except DNSLookupError as e: + raise RequestSendFailed(e, can_retry=retry_on_dns_fail) from e + except Exception as e: + raise RequestSendFailed(e, can_retry=True) from e + + incoming_responses_counter.labels( + request.method, response.code + ).inc() + + set_tag(tags.HTTP_STATUS_CODE, response.code) + response_phrase = response.phrase.decode("ascii", errors="replace") + + if 200 <= response.code < 300: + logger.debug( + "{%s} [%s] Got response headers: %d %s", + request.txn_id, + request.destination, + response.code, + response_phrase, + ) + pass + else: + logger.info( + "{%s} [%s] Got response headers: %d %s", + request.txn_id, + request.destination, + response.code, + response_phrase, + ) + # :'( + # Update transactions table? + d = treq.content(response) + d = timeout_deferred( + d, timeout=_sec_timeout, reactor=self.reactor + ) + + try: + body = await make_deferred_yieldable(d) + except Exception as e: + # Eh, we're already going to raise an exception so lets + # ignore if this fails. + logger.warning( + "{%s} [%s] Failed to get error response: %s %s: %s", + request.txn_id, + request.destination, + request.method, + url_str, + _flatten_response_never_received(e), + ) + body = None + + exc = HttpResponseException( + response.code, response_phrase, body + ) + + # Retry if the error is a 429 (Too Many Requests), + # otherwise just raise a standard HttpResponseException + if response.code == 429: + raise RequestSendFailed(exc, can_retry=True) from exc + else: + raise exc + + break + except RequestSendFailed as e: + logger.info( + "{%s} [%s] Request failed: %s %s: %s", + request.txn_id, + request.destination, + request.method, + url_str, + _flatten_response_never_received(e.inner_exception), + ) + + if not e.can_retry: + raise + + if retries_left and not timeout: + if long_retries: + delay = 4 ** (MAX_LONG_RETRIES + 1 - retries_left) + delay = min(delay, 60) + delay *= random.uniform(0.8, 1.4) + else: + delay = 0.5 * 2 ** (MAX_SHORT_RETRIES - retries_left) + delay = min(delay, 2) + delay *= random.uniform(0.8, 1.4) + + logger.debug( + "{%s} [%s] Waiting %ss before re-sending...", + request.txn_id, + request.destination, + delay, + ) + + await self.clock.sleep(delay) + retries_left -= 1 + else: + raise + + except Exception as e: + logger.warning( + "{%s} [%s] Request failed: %s %s: %s", + request.txn_id, + request.destination, + request.method, + url_str, + _flatten_response_never_received(e), + ) + raise + return response + + def build_auth_headers( + self, + destination: Optional[bytes], + method: bytes, + url_bytes: bytes, + content: Optional[JsonDict] = None, + destination_is: Optional[bytes] = None, + ) -> List[bytes]: + """ + Builds the Authorization headers for a federation request + Args: + destination: The destination homeserver of the request. + May be None if the destination is an identity server, in which case + destination_is must be non-None. + method: The HTTP method of the request + url_bytes: The URI path of the request + content: The body of the request + destination_is: As 'destination', but if the destination is an + identity server + + Returns: + A list of headers to be added as "Authorization:" headers + """ + request = { + "method": method.decode("ascii"), + "uri": url_bytes.decode("ascii"), + "origin": self.server_name, + } + + if destination is not None: + request["destination"] = destination.decode("ascii") + + if destination_is is not None: + request["destination_is"] = destination_is.decode("ascii") + + if content is not None: + request["content"] = content + + request = sign_json(request, self.server_name, self.signing_key) + + auth_headers = [] + + for key, sig in request["signatures"][self.server_name].items(): + auth_headers.append( + ( + 'X-Matrix origin=%s,key="%s",sig="%s"' + % (self.server_name, key, sig) + ).encode("ascii") + ) + return auth_headers + + async def put_json( + self, + destination: str, + path: str, + args: Optional[QueryArgs] = None, + data: Optional[JsonDict] = None, + json_data_callback: Optional[Callable[[], JsonDict]] = None, + long_retries: bool = False, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + backoff_on_404: bool = False, + try_trailing_slash_on_400: bool = False, + ) -> Union[JsonDict, list]: + """ Sends the specified json data using PUT + + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path. + args: query params + data: A dict containing the data that will be used as + the request body. This will be encoded as JSON. + json_data_callback: A callable returning the dict to + use as the request body. + + long_retries: whether to use the long retry algorithm. See + docs on _send_request for details. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + backoff_on_404: True if we should count a 404 response as + a failure of the server (and should therefore back off future + requests). + try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED + response we should try appending a trailing slash to the end + of the request. Workaround for #3622 in Synapse <= v0.99.3. This + will be attempted before backing off if backing off has been + enabled. + + Returns: + Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="PUT", + destination=destination, + path=path, + query=args, + json_callback=json_data_callback, + json=data, + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request_with_optional_trailing_slash( + request, + try_trailing_slash_on_400, + backoff_on_404=backoff_on_404, + ignore_backoff=ignore_backoff, + long_retries=long_retries, + timeout=timeout, + ) + + if timeout is not None: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms + ) + + return body + + async def post_json( + self, + destination: str, + path: str, + data: Optional[JsonDict] = None, + long_retries: bool = False, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + args: Optional[QueryArgs] = None, + ) -> Union[JsonDict, list]: + """ Sends the specified json data using POST + + Args: + destination: The remote server to send the HTTP request to. + + path: The HTTP path. + + data: A dict containing the data that will be used as + the request body. This will be encoded as JSON. + + long_retries: whether to use the long retry algorithm. See + docs on _send_request for details. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data and + try the request anyway. + + args: query params + Returns: + dict|list: Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + + request = MatrixFederationRequest( + method="POST", destination=destination, path=path, query=args, json=data + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request( + request, + long_retries=long_retries, + timeout=timeout, + ignore_backoff=ignore_backoff, + ) + + if timeout: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms, + ) + return body + + async def get_json( + self, + destination: str, + path: str, + args: Optional[QueryArgs] = None, + retry_on_dns_fail: bool = True, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + try_trailing_slash_on_400: bool = False, + ) -> Union[JsonDict, list]: + """ GETs some json from the given host homeserver and path + + Args: + destination: The remote server to send the HTTP request to. + + path: The HTTP path. + + args: A dictionary used to create query strings, defaults to + None. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED + response we should try appending a trailing slash to the end of + the request. Workaround for #3622 in Synapse <= v0.99.3. + Returns: + Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="GET", destination=destination, path=path, query=args + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request_with_optional_trailing_slash( + request, + try_trailing_slash_on_400, + backoff_on_404=False, + ignore_backoff=ignore_backoff, + retry_on_dns_fail=retry_on_dns_fail, + timeout=timeout, + ) + + if timeout is not None: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms + ) + + return body + + async def delete_json( + self, + destination: str, + path: str, + long_retries: bool = False, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + args: Optional[QueryArgs] = None, + ) -> Union[JsonDict, list]: + """Send a DELETE request to the remote expecting some json response + + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path. + + long_retries: whether to use the long retry algorithm. See + docs on _send_request for details. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data and + try the request anyway. + + args: query params + Returns: + Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="DELETE", destination=destination, path=path, query=args + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request( + request, + long_retries=long_retries, + timeout=timeout, + ignore_backoff=ignore_backoff, + ) + + if timeout is not None: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms + ) + return body + + async def get_file( + self, + destination: str, + path: str, + output_stream, + args: Optional[QueryArgs] = None, + retry_on_dns_fail: bool = True, + max_size: Optional[int] = None, + ignore_backoff: bool = False, + ) -> Tuple[int, Dict[bytes, List[bytes]]]: + """GETs a file from a given homeserver + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path to GET. + output_stream: File to write the response body to. + args: Optional dictionary used to create the query string. + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + Returns: + Resolves with an (int,dict) tuple of + the file length and a dict of the response headers. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="GET", destination=destination, path=path, query=args + ) + + response = await self._send_request( + request, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff + ) + + headers = dict(response.headers.getAllRawHeaders()) + + try: + d = read_body_with_max_size(response, output_stream, max_size) + d.addTimeout(self.default_timeout, self.reactor) + length = await make_deferred_yieldable(d) + except BodyExceededMaxSize: + msg = "Requested file is too large > %r bytes" % (max_size,) + logger.warning( + "{%s} [%s] %s", request.txn_id, request.destination, msg, + ) + SynapseError(502, msg, Codes.TOO_LARGE) + except Exception as e: + logger.warning( + "{%s} [%s] Error reading response: %s", + request.txn_id, + request.destination, + e, + ) + raise + logger.info( + "{%s} [%s] Completed: %d %s [%d bytes] %s %s", + request.txn_id, + request.destination, + response.code, + response.phrase.decode("ascii", errors="replace"), + length, + request.method, + request.uri.decode("ascii"), + ) + return (length, headers) +``` + +## `synapse/http/matrixfederationclient.py` — `function:MatrixFederationHttpClient.get_file` (lines 937-1008) + +```python + async def get_file( + self, + destination: str, + path: str, + output_stream, + args: Optional[QueryArgs] = None, + retry_on_dns_fail: bool = True, + max_size: Optional[int] = None, + ignore_backoff: bool = False, + ) -> Tuple[int, Dict[bytes, List[bytes]]]: + """GETs a file from a given homeserver + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path to GET. + output_stream: File to write the response body to. + args: Optional dictionary used to create the query string. + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + Returns: + Resolves with an (int,dict) tuple of + the file length and a dict of the response headers. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="GET", destination=destination, path=path, query=args + ) + + response = await self._send_request( + request, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff + ) + + headers = dict(response.headers.getAllRawHeaders()) + + try: + d = read_body_with_max_size(response, output_stream, max_size) + d.addTimeout(self.default_timeout, self.reactor) + length = await make_deferred_yieldable(d) + except BodyExceededMaxSize: + msg = "Requested file is too large > %r bytes" % (max_size,) + logger.warning( + "{%s} [%s] %s", request.txn_id, request.destination, msg, + ) + SynapseError(502, msg, Codes.TOO_LARGE) + except Exception as e: + logger.warning( + "{%s} [%s] Error reading response: %s", + request.txn_id, + request.destination, + e, + ) + raise + logger.info( + "{%s} [%s] Completed: %d %s [%d bytes] %s %s", + request.txn_id, + request.destination, + response.code, + response.phrase.decode("ascii", errors="replace"), + length, + request.method, + request.uri.decode("ascii"), + ) + return (length, headers) +``` + +## `synapse/http/matrixfederationclient.py` — `module:@39` (lines 39-45) + +```python +from synapse.api.errors import ( + Codes, + FederationDeniedError, + HttpResponseException, + RequestSendFailed, + SynapseError, +) +``` + +## `synapse/http/matrixfederationclient.py` — `module:@47` (lines 47-53) + +```python +from synapse.http.client import ( + BlacklistingAgentWrapper, + BlacklistingReactorWrapper, + BodyExceededMaxSize, + encode_query_args, + read_body_with_max_size, +) +``` + +## `tests/http/federation/test_matrix_federation_agent.py` — `class:MatrixFederationAgentTests` (lines 80-1192) + +```python +class MatrixFederationAgentTests(unittest.TestCase): + def setUp(self): + self.reactor = ThreadedMemoryReactorClock() + + self.mock_resolver = Mock() + + config_dict = default_config("test", parse=False) + config_dict["federation_custom_ca_list"] = [get_test_ca_cert_file()] + + self._config = config = HomeServerConfig() + config.parse_config_dict(config_dict, "", "") + + self.tls_factory = FederationPolicyForHTTPS(config) + + self.well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds) + self.had_well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds) + self.well_known_resolver = WellKnownResolver( + self.reactor, + Agent(self.reactor, contextFactory=self.tls_factory), + b"test-agent", + well_known_cache=self.well_known_cache, + had_well_known_cache=self.had_well_known_cache, + ) + + self.agent = MatrixFederationAgent( + reactor=self.reactor, + tls_client_options_factory=self.tls_factory, + user_agent="test-agent", # Note that this is unused since _well_known_resolver is provided. + ip_blacklist=IPSet(), + _srv_resolver=self.mock_resolver, + _well_known_resolver=self.well_known_resolver, + ) + + def _make_connection(self, client_factory, expected_sni): + """Builds a test server, and completes the outgoing client connection + + Returns: + HTTPChannel: the test server + """ + + # build the test server + server_tls_protocol = _build_test_server(get_connection_factory()) + + # now, tell the client protocol factory to build the client protocol (it will be a + # _WrappingProtocol, around a TLSMemoryBIOProtocol, around an + # HTTP11ClientProtocol) and wire the output of said protocol up to the server via + # a FakeTransport. + # + # Normally this would be done by the TCP socket code in Twisted, but we are + # stubbing that out here. + client_protocol = client_factory.buildProtocol(None) + client_protocol.makeConnection( + FakeTransport(server_tls_protocol, self.reactor, client_protocol) + ) + + # tell the server tls protocol to send its stuff back to the client, too + server_tls_protocol.makeConnection( + FakeTransport(client_protocol, self.reactor, server_tls_protocol) + ) + + # grab a hold of the TLS connection, in case it gets torn down + server_tls_connection = server_tls_protocol._tlsConnection + + # fish the test server back out of the server-side TLS protocol. + http_protocol = server_tls_protocol.wrappedProtocol + + # give the reactor a pump to get the TLS juices flowing. + self.reactor.pump((0.1,)) + + # check the SNI + server_name = server_tls_connection.get_servername() + self.assertEqual( + server_name, + expected_sni, + "Expected SNI %s but got %s" % (expected_sni, server_name), + ) + + return http_protocol + + @defer.inlineCallbacks + def _make_get_request(self, uri): + """ + Sends a simple GET request via the agent, and checks its logcontext management + """ + with LoggingContext("one") as context: + fetch_d = self.agent.request(b"GET", uri) + + # Nothing happened yet + self.assertNoResult(fetch_d) + + # should have reset logcontext to the sentinel + _check_logcontext(SENTINEL_CONTEXT) + + try: + fetch_res = yield fetch_d + return fetch_res + except Exception as e: + logger.info("Fetch of %s failed: %s", uri.decode("ascii"), e) + raise + finally: + _check_logcontext(context) + + def _handle_well_known_connection( + self, client_factory, expected_sni, content, response_headers={} + ): + """Handle an outgoing HTTPs connection: wire it up to a server, check that the + request is for a .well-known, and send the response. + + Args: + client_factory (IProtocolFactory): outgoing connection + expected_sni (bytes): SNI that we expect the outgoing connection to send + content (bytes): content to send back as the .well-known + Returns: + HTTPChannel: server impl + """ + # make the connection for .well-known + well_known_server = self._make_connection( + client_factory, expected_sni=expected_sni + ) + # check the .well-known request and send a response + self.assertEqual(len(well_known_server.requests), 1) + request = well_known_server.requests[0] + self.assertEqual( + request.requestHeaders.getRawHeaders(b"user-agent"), [b"test-agent"] + ) + self._send_well_known_response(request, content, headers=response_headers) + return well_known_server + + def _send_well_known_response(self, request, content, headers={}): + """Check that an incoming request looks like a valid .well-known request, and + send back the response. + """ + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/.well-known/matrix/server") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + # send back a response + for k, v in headers.items(): + request.setHeader(k, v) + request.write(content) + request.finish() + + self.reactor.pump((0.1,)) + + def test_get(self): + """ + happy-path test of a GET request with an explicit port + """ + self.reactor.lookups["testserv"] = "1.2.3.4" + test_d = self._make_get_request(b"matrix://testserv:8448/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"testserv:8448"] + ) + self.assertEqual( + request.requestHeaders.getRawHeaders(b"user-agent"), [b"test-agent"] + ) + content = request.content.read() + self.assertEqual(content, b"") + + # Deferred is still without a result + self.assertNoResult(test_d) + + # send the headers + request.responseHeaders.setRawHeaders(b"Content-Type", [b"application/json"]) + request.write("") + + self.reactor.pump((0.1,)) + + response = self.successResultOf(test_d) + + # that should give us a Response object + self.assertEqual(response.code, 200) + + # Send the body + request.write('{ "a": 1 }'.encode("ascii")) + request.finish() + + self.reactor.pump((0.1,)) + + # check it can be read + json = self.successResultOf(treq.json_content(response)) + self.assertEqual(json, {"a": 1}) + + def test_get_ip_address(self): + """ + Test the behaviour when the server name contains an explicit IP (with no port) + """ + # there will be a getaddrinfo on the IP + self.reactor.lookups["1.2.3.4"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://1.2.3.4/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"1.2.3.4"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_ipv6_address(self): + """ + Test the behaviour when the server name contains an explicit IPv6 address + (with no port) + """ + + # there will be a getaddrinfo on the IP + self.reactor.lookups["::1"] = "::1" + + test_d = self._make_get_request(b"matrix://[::1]/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "::1") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"[::1]"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_ipv6_address_with_port(self): + """ + Test the behaviour when the server name contains an explicit IPv6 address + (with explicit port) + """ + + # there will be a getaddrinfo on the IP + self.reactor.lookups["::1"] = "::1" + + test_d = self._make_get_request(b"matrix://[::1]:80/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "::1") + self.assertEqual(port, 80) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"[::1]:80"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_hostname_bad_cert(self): + """ + Test the behaviour when the certificate on the server doesn't match the hostname + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv1"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv1/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + # fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the + # .well-known request fails. + self.reactor.pump((0.4,)) + + # now there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv1" + ) + + # we should fall back to a direct connection + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv1") + + # there should be no requests + self.assertEqual(len(http_server.requests), 0) + + # ... and the request should have failed + e = self.failureResultOf(test_d, ResponseNeverReceived) + failure_reason = e.value.reasons[0] + self.assertIsInstance(failure_reason.value, VerificationError) + + def test_get_ip_address_bad_cert(self): + """ + Test the behaviour when the server name contains an explicit IP, but + the server cert doesn't cover it + """ + # there will be a getaddrinfo on the IP + self.reactor.lookups["1.2.3.5"] = "1.2.3.5" + + test_d = self._make_get_request(b"matrix://1.2.3.5/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.5") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + # there should be no requests + self.assertEqual(len(http_server.requests), 0) + + # ... and the request should have failed + e = self.failureResultOf(test_d, ResponseNeverReceived) + failure_reason = e.value.reasons[0] + self.assertIsInstance(failure_reason.value, VerificationError) + + def test_get_no_srv_no_well_known(self): + """ + Test the behaviour when the server name has no port, no SRV, and no well-known + """ + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + # fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the + # .well-known request fails. + self.reactor.pump((0.4,)) + + # now there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # we should fall back to a direct connection + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_well_known(self): + """Test the behaviour when the .well-known delegates elsewhere + """ + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + self.reactor.lookups["target-server"] = "1::f" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + content=b'{ "m.server": "target-server" }', + ) + + # there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.target-server" + ) + + # now we should get a connection to the target server + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1::f") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"target-server" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"target-server"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + self.assertEqual(self.well_known_cache[b"testserv"], b"target-server") + + # check the cache expires + self.reactor.pump((48 * 3600,)) + self.well_known_cache.expire() + self.assertNotIn(b"testserv", self.well_known_cache) + + def test_get_well_known_redirect(self): + """Test the behaviour when the server name has no port and no SRV record, but + the .well-known has a 300 redirect + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + self.reactor.lookups["target-server"] = "1::f" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + redirect_server = self._make_connection( + client_factory, expected_sni=b"testserv" + ) + + # send a 302 redirect + self.assertEqual(len(redirect_server.requests), 1) + request = redirect_server.requests[0] + request.redirect(b"https://testserv/even_better_known") + request.finish() + + self.reactor.pump((0.1,)) + + # now there should be another connection + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + well_known_server = self._make_connection( + client_factory, expected_sni=b"testserv" + ) + + self.assertEqual(len(well_known_server.requests), 1, "No request after 302") + request = well_known_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/even_better_known") + request.write(b'{ "m.server": "target-server" }') + request.finish() + + self.reactor.pump((0.1,)) + + # there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.target-server" + ) + + # now we should get a connection to the target server + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1::f") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"target-server" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"target-server"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + self.assertEqual(self.well_known_cache[b"testserv"], b"target-server") + + # check the cache expires + self.reactor.pump((48 * 3600,)) + self.well_known_cache.expire() + self.assertNotIn(b"testserv", self.well_known_cache) + + def test_get_invalid_well_known(self): + """ + Test the behaviour when the server name has an *invalid* well-known (and no SRV) + """ + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, expected_sni=b"testserv", content=b"NOT JSON" + ) + + # now there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # we should fall back to a direct connection + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_well_known_unsigned_cert(self): + """Test the behaviour when the .well-known server presents a cert + not signed by a CA + """ + + # we use the same test server as the other tests, but use an agent with + # the config left to the default, which will not trust it (since the + # presented cert is signed by a test CA) + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + + config = default_config("test", parse=True) + + # Build a new agent and WellKnownResolver with a different tls factory + tls_factory = FederationPolicyForHTTPS(config) + agent = MatrixFederationAgent( + reactor=self.reactor, + tls_client_options_factory=tls_factory, + user_agent=b"test-agent", # This is unused since _well_known_resolver is passed below. + ip_blacklist=IPSet(), + _srv_resolver=self.mock_resolver, + _well_known_resolver=WellKnownResolver( + self.reactor, + Agent(self.reactor, contextFactory=tls_factory), + b"test-agent", + well_known_cache=self.well_known_cache, + had_well_known_cache=self.had_well_known_cache, + ), + ) + + test_d = agent.request(b"GET", b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + http_proto = self._make_connection(client_factory, expected_sni=b"testserv") + + # there should be no requests + self.assertEqual(len(http_proto.requests), 0) + + # and there should be a SRV lookup instead + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + def test_get_hostname_srv(self): + """ + Test the behaviour when there is a single SRV record + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [Server(host=b"srvtarget", port=8443)] + ) + self.reactor.lookups["srvtarget"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # the request for a .well-known will have failed with a DNS lookup error. + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_well_known_srv(self): + """Test the behaviour when the .well-known redirects to a place where there + is a SRV. + """ + self.reactor.lookups["testserv"] = "1.2.3.4" + self.reactor.lookups["srvtarget"] = "5.6.7.8" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [Server(host=b"srvtarget", port=8443)] + ) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + content=b'{ "m.server": "target-server" }', + ) + + # there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.target-server" + ) + + # now we should get a connection to the target of the SRV record + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "5.6.7.8") + self.assertEqual(port, 8443) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"target-server" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"target-server"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_idna_servername(self): + """test the behaviour when the server name has idna chars in""" + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + + # the resolver is always called with the IDNA hostname as a native string. + self.reactor.lookups["xn--bcher-kva.com"] = "1.2.3.4" + + # this is idna for bücher.com + test_d = self._make_get_request(b"matrix://xn--bcher-kva.com/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + # fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the + # .well-known request fails. + self.reactor.pump((0.4,)) + + # now there should have been a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.xn--bcher-kva.com" + ) + + # We should fall back to port 8448 + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"xn--bcher-kva.com" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"xn--bcher-kva.com"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_idna_srv_target(self): + """test the behaviour when the target of a SRV record has idna chars""" + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [Server(host=b"xn--trget-3qa.com", port=8443)] # târget.com + ) + self.reactor.lookups["xn--trget-3qa.com"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://xn--bcher-kva.com/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.xn--bcher-kva.com" + ) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"xn--bcher-kva.com" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"xn--bcher-kva.com"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_well_known_cache(self): + self.reactor.lookups["testserv"] = "1.2.3.4" + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + well_known_server = self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + response_headers={b"Cache-Control": b"max-age=1000"}, + content=b'{ "m.server": "target-server" }', + ) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # close the tcp connection + well_known_server.loseConnection() + + # repeat the request: it should hit the cache + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # expire the cache + self.reactor.pump((1000.0,)) + + # now it should connect again + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + content=b'{ "m.server": "other-server" }', + ) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"other-server") + + def test_well_known_cache_with_temp_failure(self): + """Test that we refetch well-known before the cache expires, and that + it ignores transient errors. + """ + + self.reactor.lookups["testserv"] = "1.2.3.4" + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + well_known_server = self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + response_headers={b"Cache-Control": b"max-age=1000"}, + content=b'{ "m.server": "target-server" }', + ) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # close the tcp connection + well_known_server.loseConnection() + + # Get close to the cache expiry, this will cause the resolver to do + # another lookup. + self.reactor.pump((900.0,)) + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # The resolver may retry a few times, so fonx all requests that come along + attempts = 0 + while self.reactor.tcpClients: + clients = self.reactor.tcpClients + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + + attempts += 1 + + # fonx the connection attempt, this will be treated as a temporary + # failure. + client_factory.clientConnectionFailed(None, Exception("nope")) + + # There's a few sleeps involved, so we have to pump the reactor a + # bit. + self.reactor.pump((1.0, 1.0)) + + # We expect to see more than one attempt as there was previously a valid + # well known. + self.assertGreater(attempts, 1) + + # Resolver should return cached value, despite the lookup failing. + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # Expire both caches and repeat the request + self.reactor.pump((10000.0,)) + + # Repated the request, this time it should fail if the lookup fails. + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + clients = self.reactor.tcpClients + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + client_factory.clientConnectionFailed(None, Exception("nope")) + self.reactor.pump((0.4,)) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, None) + + def test_well_known_too_large(self): + """A well-known query that returns a result which is too large should be rejected.""" + self.reactor.lookups["testserv"] = "1.2.3.4" + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + response_headers={b"Cache-Control": b"max-age=1000"}, + content=b'{ "m.server": "' + (b"a" * WELL_KNOWN_MAX_SIZE) + b'" }', + ) + + # The result is sucessful, but disabled delegation. + r = self.successResultOf(fetch_d) + self.assertIsNone(r.delegated_server) + + def test_srv_fallbacks(self): + """Test that other SRV results are tried if the first one fails. + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [ + Server(host=b"target.com", port=8443), + Server(host=b"target.com", port=8444), + ] + ) + self.reactor.lookups["target.com"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # We should see an attempt to connect to the first server + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # Fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # There's a 300ms delay in HostnameEndpoint + self.reactor.pump((0.4,)) + + # Hasn't failed yet + self.assertNoResult(test_d) + + # We shouldnow see an attempt to connect to the second server + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8444) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) +``` + +## `tests/http/federation/test_matrix_federation_agent.py` — `function:MatrixFederationAgentTests.test_well_known_too_large` (lines 1111-1135) + +```python + def test_well_known_too_large(self): + """A well-known query that returns a result which is too large should be rejected.""" + self.reactor.lookups["testserv"] = "1.2.3.4" + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + response_headers={b"Cache-Control": b"max-age=1000"}, + content=b'{ "m.server": "' + (b"a" * WELL_KNOWN_MAX_SIZE) + b'" }', + ) + + # The result is sucessful, but disabled delegation. + r = self.successResultOf(fetch_d) + self.assertIsNone(r.delegated_server) +``` + +## `tests/http/federation/test_matrix_federation_agent.py` — `module:@38` (lines 38-42) + +```python +from synapse.http.federation.well_known_resolver import ( + WELL_KNOWN_MAX_SIZE, + WellKnownResolver, + _cache_period_from_headers, +) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8961ef13a4e9bfa20904bff194983ea6a9e8091a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/pre_context.md @@ -0,0 +1,2955 @@ +# Patch-overlapping Python context before the fix + +## `synapse/http/client.py` — `class:SimpleHttpClient` (lines 280-736) + +```python +class SimpleHttpClient: + """ + A simple, no-frills HTTP client with methods that wrap up common ways of + using HTTP in Matrix + """ + + def __init__( + self, + hs: "HomeServer", + treq_args: Dict[str, Any] = {}, + ip_whitelist: Optional[IPSet] = None, + ip_blacklist: Optional[IPSet] = None, + http_proxy: Optional[bytes] = None, + https_proxy: Optional[bytes] = None, + ): + """ + Args: + hs + treq_args: Extra keyword arguments to be given to treq.request. + ip_blacklist: The IP addresses that are blacklisted that + we may not request. + ip_whitelist: The whitelisted IP addresses, that we can + request if it were otherwise caught in a blacklist. + http_proxy: proxy server to use for http connections. host[:port] + https_proxy: proxy server to use for https connections. host[:port] + """ + self.hs = hs + + self._ip_whitelist = ip_whitelist + self._ip_blacklist = ip_blacklist + self._extra_treq_args = treq_args + + self.user_agent = hs.version_string + self.clock = hs.get_clock() + if hs.config.user_agent_suffix: + self.user_agent = "%s %s" % (self.user_agent, hs.config.user_agent_suffix) + + # We use this for our body producers to ensure that they use the correct + # reactor. + self._cooperator = Cooperator(scheduler=_make_scheduler(hs.get_reactor())) + + self.user_agent = self.user_agent.encode("ascii") + + if self._ip_blacklist: + # If we have an IP blacklist, we need to use a DNS resolver which + # filters out blacklisted IP addresses, to prevent DNS rebinding. + self.reactor = BlacklistingReactorWrapper( + hs.get_reactor(), self._ip_whitelist, self._ip_blacklist + ) + else: + self.reactor = hs.get_reactor() + + # the pusher makes lots of concurrent SSL connections to sygnal, and + # tends to do so in batches, so we need to allow the pool to keep + # lots of idle connections around. + pool = HTTPConnectionPool(self.reactor) + # XXX: The justification for using the cache factor here is that larger instances + # will need both more cache and more connections. + # Still, this should probably be a separate dial + pool.maxPersistentPerHost = max((100 * hs.config.caches.global_factor, 5)) + pool.cachedConnectionTimeout = 2 * 60 + + self.agent = ProxyAgent( + self.reactor, + connectTimeout=15, + contextFactory=self.hs.get_http_client_context_factory(), + pool=pool, + http_proxy=http_proxy, + https_proxy=https_proxy, + ) + + if self._ip_blacklist: + # If we have an IP blacklist, we then install the blacklisting Agent + # which prevents direct access to IP addresses, that are not caught + # by the DNS resolution. + self.agent = BlacklistingAgentWrapper( + self.agent, + ip_whitelist=self._ip_whitelist, + ip_blacklist=self._ip_blacklist, + ) + + async def request( + self, + method: str, + uri: str, + data: Optional[bytes] = None, + headers: Optional[Headers] = None, + ) -> IResponse: + """ + Args: + method: HTTP method to use. + uri: URI to query. + data: Data to send in the request body, if applicable. + headers: Request headers. + + Returns: + Response object, once the headers have been read. + + Raises: + RequestTimedOutError if the request times out before the headers are read + + """ + outgoing_requests_counter.labels(method).inc() + + # log request but strip `access_token` (AS requests for example include this) + logger.debug("Sending request %s %s", method, redact_uri(uri)) + + with start_active_span( + "outgoing-client-request", + tags={ + tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, + tags.HTTP_METHOD: method, + tags.HTTP_URL: uri, + }, + finish_on_close=True, + ): + try: + body_producer = None + if data is not None: + body_producer = QuieterFileBodyProducer( + BytesIO(data), cooperator=self._cooperator, + ) + + request_deferred = treq.request( + method, + uri, + agent=self.agent, + data=body_producer, + headers=headers, + **self._extra_treq_args, + ) # type: defer.Deferred + + # we use our own timeout mechanism rather than treq's as a workaround + # for https://twistedmatrix.com/trac/ticket/9534. + request_deferred = timeout_deferred( + request_deferred, 60, self.hs.get_reactor(), + ) + + # turn timeouts into RequestTimedOutErrors + request_deferred.addErrback(_timeout_to_request_timed_out_error) + + response = await make_deferred_yieldable(request_deferred) + + incoming_responses_counter.labels(method, response.code).inc() + logger.info( + "Received response to %s %s: %s", + method, + redact_uri(uri), + response.code, + ) + return response + except Exception as e: + incoming_responses_counter.labels(method, "ERR").inc() + logger.info( + "Error sending request to %s %s: %s %s", + method, + redact_uri(uri), + type(e).__name__, + e.args[0], + ) + set_tag(tags.ERROR, True) + set_tag("error_reason", e.args[0]) + raise + + async def post_urlencoded_get_json( + self, + uri: str, + args: Optional[Mapping[str, Union[str, List[str]]]] = None, + headers: Optional[RawHeaders] = None, + ) -> Any: + """ + Args: + uri: uri to query + args: parameters to be url-encoded in the body + headers: a map from header name to a list of values for that header + + Returns: + parsed json + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException: On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + + # TODO: Do we ever want to log message contents? + logger.debug("post_urlencoded_get_json args: %s", args) + + query_bytes = encode_query_args(args) + + actual_headers = { + b"Content-Type": [b"application/x-www-form-urlencoded"], + b"User-Agent": [self.user_agent], + b"Accept": [b"application/json"], + } + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request( + "POST", uri, headers=Headers(actual_headers), data=query_bytes + ) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return json_decoder.decode(body.decode("utf-8")) + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + async def post_json_get_json( + self, uri: str, post_json: Any, headers: Optional[RawHeaders] = None + ) -> Any: + """ + + Args: + uri: URI to query. + post_json: request body, to be encoded as json + headers: a map from header name to a list of values for that header + + Returns: + parsed json + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException: On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + json_str = encode_canonical_json(post_json) + + logger.debug("HTTP POST %s -> %s", json_str, uri) + + actual_headers = { + b"Content-Type": [b"application/json"], + b"User-Agent": [self.user_agent], + b"Accept": [b"application/json"], + } + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request( + "POST", uri, headers=Headers(actual_headers), data=json_str + ) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return json_decoder.decode(body.decode("utf-8")) + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + async def get_json( + self, + uri: str, + args: Optional[QueryParams] = None, + headers: Optional[RawHeaders] = None, + ) -> Any: + """Gets some json from the given URI. + + Args: + uri: The URI to request, not including query parameters + args: A dictionary used to create query string + headers: a map from header name to a list of values for that header + Returns: + Succeeds when we get a 2xx HTTP response, with the HTTP body as JSON. + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + actual_headers = {b"Accept": [b"application/json"]} + if headers: + actual_headers.update(headers) # type: ignore + + body = await self.get_raw(uri, args, headers=headers) + return json_decoder.decode(body.decode("utf-8")) + + async def put_json( + self, + uri: str, + json_body: Any, + args: Optional[QueryParams] = None, + headers: RawHeaders = None, + ) -> Any: + """Puts some json to the given URI. + + Args: + uri: The URI to request, not including query parameters + json_body: The JSON to put in the HTTP body, + args: A dictionary used to create query strings + headers: a map from header name to a list of values for that header + Returns: + Succeeds when we get a 2xx HTTP response, with the HTTP body as JSON. + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException On a non-2xx HTTP response. + + ValueError: if the response was not JSON + """ + if args: + query_str = urllib.parse.urlencode(args, True) + uri = "%s?%s" % (uri, query_str) + + json_str = encode_canonical_json(json_body) + + actual_headers = { + b"Content-Type": [b"application/json"], + b"User-Agent": [self.user_agent], + b"Accept": [b"application/json"], + } + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request( + "PUT", uri, headers=Headers(actual_headers), data=json_str + ) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return json_decoder.decode(body.decode("utf-8")) + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + async def get_raw( + self, + uri: str, + args: Optional[QueryParams] = None, + headers: Optional[RawHeaders] = None, + ) -> bytes: + """Gets raw text from the given URI. + + Args: + uri: The URI to request, not including query parameters + args: A dictionary used to create query strings + headers: a map from header name to a list of values for that header + Returns: + Succeeds when we get a 2xx HTTP response, with the + HTTP body as bytes. + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + HttpResponseException on a non-2xx HTTP response. + """ + if args: + query_str = urllib.parse.urlencode(args, True) + uri = "%s?%s" % (uri, query_str) + + actual_headers = {b"User-Agent": [self.user_agent]} + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request("GET", uri, headers=Headers(actual_headers)) + + body = await make_deferred_yieldable(readBody(response)) + + if 200 <= response.code < 300: + return body + else: + raise HttpResponseException( + response.code, response.phrase.decode("ascii", errors="replace"), body + ) + + # XXX: FIXME: This is horribly copy-pasted from matrixfederationclient. + # The two should be factored out. + + async def get_file( + self, + url: str, + output_stream: BinaryIO, + max_size: Optional[int] = None, + headers: Optional[RawHeaders] = None, + ) -> Tuple[int, Dict[bytes, List[bytes]], str, int]: + """GETs a file from a given URL + Args: + url: The URL to GET + output_stream: File to write the response body to. + headers: A map from header name to a list of values for that header + Returns: + A tuple of the file length, dict of the response + headers, absolute URI of the response and HTTP response code. + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + SynapseError: if the response is not a 2xx, the remote file is too large, or + another exception happens during the download. + """ + + actual_headers = {b"User-Agent": [self.user_agent]} + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request("GET", url, headers=Headers(actual_headers)) + + resp_headers = dict(response.headers.getAllRawHeaders()) + + if ( + b"Content-Length" in resp_headers + and max_size + and int(resp_headers[b"Content-Length"][0]) > max_size + ): + logger.warning("Requested URL is too large > %r bytes" % (max_size,)) + raise SynapseError( + 502, + "Requested file is too large > %r bytes" % (max_size,), + Codes.TOO_LARGE, + ) + + if response.code > 299: + logger.warning("Got %d when downloading %s" % (response.code, url)) + raise SynapseError(502, "Got error %d" % (response.code,), Codes.UNKNOWN) + + # TODO: if our Content-Type is HTML or something, just read the first + # N bytes into RAM rather than saving it all to disk only to read it + # straight back in again + + try: + length = await make_deferred_yieldable( + readBodyToFile(response, output_stream, max_size) + ) + except SynapseError: + # This can happen e.g. because the body is too large. + raise + except Exception as e: + raise SynapseError(502, ("Failed to download remote body: %s" % e)) from e + + return ( + length, + resp_headers, + response.request.absoluteURI.decode("ascii"), + response.code, + ) +``` + +## `synapse/http/client.py` — `function:SimpleHttpClient.get_file` (lines 668-736) + +```python + async def get_file( + self, + url: str, + output_stream: BinaryIO, + max_size: Optional[int] = None, + headers: Optional[RawHeaders] = None, + ) -> Tuple[int, Dict[bytes, List[bytes]], str, int]: + """GETs a file from a given URL + Args: + url: The URL to GET + output_stream: File to write the response body to. + headers: A map from header name to a list of values for that header + Returns: + A tuple of the file length, dict of the response + headers, absolute URI of the response and HTTP response code. + + Raises: + RequestTimedOutError: if there is a timeout before the response headers + are received. Note there is currently no timeout on reading the response + body. + + SynapseError: if the response is not a 2xx, the remote file is too large, or + another exception happens during the download. + """ + + actual_headers = {b"User-Agent": [self.user_agent]} + if headers: + actual_headers.update(headers) # type: ignore + + response = await self.request("GET", url, headers=Headers(actual_headers)) + + resp_headers = dict(response.headers.getAllRawHeaders()) + + if ( + b"Content-Length" in resp_headers + and max_size + and int(resp_headers[b"Content-Length"][0]) > max_size + ): + logger.warning("Requested URL is too large > %r bytes" % (max_size,)) + raise SynapseError( + 502, + "Requested file is too large > %r bytes" % (max_size,), + Codes.TOO_LARGE, + ) + + if response.code > 299: + logger.warning("Got %d when downloading %s" % (response.code, url)) + raise SynapseError(502, "Got error %d" % (response.code,), Codes.UNKNOWN) + + # TODO: if our Content-Type is HTML or something, just read the first + # N bytes into RAM rather than saving it all to disk only to read it + # straight back in again + + try: + length = await make_deferred_yieldable( + readBodyToFile(response, output_stream, max_size) + ) + except SynapseError: + # This can happen e.g. because the body is too large. + raise + except Exception as e: + raise SynapseError(502, ("Failed to download remote body: %s" % e)) from e + + return ( + length, + resp_headers, + response.request.absoluteURI.decode("ascii"), + response.code, + ) +``` + +## `synapse/http/client.py` — `class:_ReadBodyToFileProtocol` (lines 751-782) + +```python +class _ReadBodyToFileProtocol(protocol.Protocol): + def __init__( + self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] + ): + self.stream = stream + self.deferred = deferred + self.length = 0 + self.max_size = max_size + + def dataReceived(self, data: bytes) -> None: + self.stream.write(data) + self.length += len(data) + if self.max_size is not None and self.length >= self.max_size: + self.deferred.errback( + SynapseError( + 502, + "Requested file is too large > %r bytes" % (self.max_size,), + Codes.TOO_LARGE, + ) + ) + self.deferred = defer.Deferred() + self.transport.loseConnection() + + def connectionLost(self, reason: Failure) -> None: + if reason.check(ResponseDone): + self.deferred.callback(self.length) + elif reason.check(PotentialDataLoss): + # stolen from https://github.com/twisted/treq/pull/49/files + # http://twistedmatrix.com/trac/ticket/4840 + self.deferred.callback(self.length) + else: + self.deferred.errback(reason) +``` + +## `synapse/http/client.py` — `function:_ReadBodyToFileProtocol.__init__` (lines 752-758) + +```python + def __init__( + self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] + ): + self.stream = stream + self.deferred = deferred + self.length = 0 + self.max_size = max_size +``` + +## `synapse/http/client.py` — `function:_ReadBodyToFileProtocol.dataReceived` (lines 760-772) + +```python + def dataReceived(self, data: bytes) -> None: + self.stream.write(data) + self.length += len(data) + if self.max_size is not None and self.length >= self.max_size: + self.deferred.errback( + SynapseError( + 502, + "Requested file is too large > %r bytes" % (self.max_size,), + Codes.TOO_LARGE, + ) + ) + self.deferred = defer.Deferred() + self.transport.loseConnection() +``` + +## `synapse/http/client.py` — `function:readBodyToFile` (lines 785-802) + +```python +def readBodyToFile( + response: IResponse, stream: BinaryIO, max_size: Optional[int] +) -> defer.Deferred: + """ + Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. + + Args: + response: The HTTP response to read from. + stream: The file-object to write to. + max_size: The maximum file size to allow. + + Returns: + A Deferred which resolves to the length of the read body. + """ + + d = defer.Deferred() + response.deliverBody(_ReadBodyToFileProtocol(stream, d, max_size)) + return d +``` + +## `synapse/http/federation/well_known_resolver.py` — `class:WellKnownResolver` (lines 78-270) + +```python +class WellKnownResolver: + """Handles well-known lookups for matrix servers. + """ + + def __init__( + self, + reactor: IReactorTime, + agent: IAgent, + user_agent: bytes, + well_known_cache: Optional[TTLCache] = None, + had_well_known_cache: Optional[TTLCache] = None, + ): + self._reactor = reactor + self._clock = Clock(reactor) + + if well_known_cache is None: + well_known_cache = _well_known_cache + + if had_well_known_cache is None: + had_well_known_cache = _had_valid_well_known_cache + + self._well_known_cache = well_known_cache + self._had_valid_well_known_cache = had_well_known_cache + self._well_known_agent = RedirectAgent(agent) + self.user_agent = user_agent + + async def get_well_known(self, server_name: bytes) -> WellKnownLookupResult: + """Attempt to fetch and parse a .well-known file for the given server + + Args: + server_name: name of the server, from the requested url + + Returns: + The result of the lookup + """ + try: + prev_result, expiry, ttl = self._well_known_cache.get_with_expiry( + server_name + ) + + now = self._clock.time() + if now < expiry - WELL_KNOWN_GRACE_PERIOD_FACTOR * ttl: + return WellKnownLookupResult(delegated_server=prev_result) + except KeyError: + prev_result = None + + # TODO: should we linearise so that we don't end up doing two .well-known + # requests for the same server in parallel? + try: + with Measure(self._clock, "get_well_known"): + result, cache_period = await self._fetch_well_known( + server_name + ) # type: Optional[bytes], float + + except _FetchWellKnownFailure as e: + if prev_result and e.temporary: + # This is a temporary failure and we have a still valid cached + # result, so lets return that. Hopefully the next time we ask + # the remote will be back up again. + return WellKnownLookupResult(delegated_server=prev_result) + + result = None + + if self._had_valid_well_known_cache.get(server_name, False): + # We have recently seen a valid well-known record for this + # server, so we cache the lack of well-known for a shorter time. + cache_period = WELL_KNOWN_DOWN_CACHE_PERIOD + else: + cache_period = WELL_KNOWN_INVALID_CACHE_PERIOD + + # add some randomness to the TTL to avoid a stampeding herd + cache_period *= random.uniform( + 1 - WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + 1 + WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + ) + + if cache_period > 0: + self._well_known_cache.set(server_name, result, cache_period) + + return WellKnownLookupResult(delegated_server=result) + + async def _fetch_well_known(self, server_name: bytes) -> Tuple[bytes, float]: + """Actually fetch and parse a .well-known, without checking the cache + + Args: + server_name: name of the server, from the requested url + + Raises: + _FetchWellKnownFailure if we fail to lookup a result + + Returns: + The lookup result and cache period. + """ + + had_valid_well_known = self._had_valid_well_known_cache.get(server_name, False) + + # We do this in two steps to differentiate between possibly transient + # errors (e.g. can't connect to host, 503 response) and more permanent + # errors (such as getting a 404 response). + response, body = await self._make_well_known_request( + server_name, retry=had_valid_well_known + ) + + try: + if response.code != 200: + raise Exception("Non-200 response %s" % (response.code,)) + + parsed_body = json_decoder.decode(body.decode("utf-8")) + logger.info("Response from .well-known: %s", parsed_body) + + result = parsed_body["m.server"].encode("ascii") + except defer.CancelledError: + # Bail if we've been cancelled + raise + except Exception as e: + logger.info("Error parsing well-known for %s: %s", server_name, e) + raise _FetchWellKnownFailure(temporary=False) + + cache_period = _cache_period_from_headers( + response.headers, time_now=self._reactor.seconds + ) + if cache_period is None: + cache_period = WELL_KNOWN_DEFAULT_CACHE_PERIOD + # add some randomness to the TTL to avoid a stampeding herd every 24 hours + # after startup + cache_period *= random.uniform( + 1 - WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + 1 + WELL_KNOWN_DEFAULT_CACHE_PERIOD_JITTER, + ) + else: + cache_period = min(cache_period, WELL_KNOWN_MAX_CACHE_PERIOD) + cache_period = max(cache_period, WELL_KNOWN_MIN_CACHE_PERIOD) + + # We got a success, mark as such in the cache + self._had_valid_well_known_cache.set( + server_name, + bool(result), + cache_period + WELL_KNOWN_REMEMBER_DOMAIN_HAD_VALID, + ) + + return result, cache_period + + async def _make_well_known_request( + self, server_name: bytes, retry: bool + ) -> Tuple[IResponse, bytes]: + """Make the well known request. + + This will retry the request if requested and it fails (with unable + to connect or receives a 5xx error). + + Args: + server_name: name of the server, from the requested url + retry: Whether to retry the request if it fails. + + Returns: + Returns the response object and body. Response may be a non-200 response. + """ + uri = b"https://%s/.well-known/matrix/server" % (server_name,) + uri_str = uri.decode("ascii") + + headers = { + b"User-Agent": [self.user_agent], + } + + i = 0 + while True: + i += 1 + + logger.info("Fetching %s", uri_str) + try: + response = await make_deferred_yieldable( + self._well_known_agent.request( + b"GET", uri, headers=Headers(headers) + ) + ) + body = await make_deferred_yieldable(readBody(response)) + + if 500 <= response.code < 600: + raise Exception("Non-200 response %s" % (response.code,)) + + return response, body + except defer.CancelledError: + # Bail if we've been cancelled + raise + except Exception as e: + if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: + logger.info("Error fetching %s: %s", uri_str, e) + raise _FetchWellKnownFailure(temporary=True) + + logger.info("Error fetching %s: %s. Retrying", uri_str, e) + + # Sleep briefly in the hopes that they come back up + await self._clock.sleep(0.5) +``` + +## `synapse/http/federation/well_known_resolver.py` — `function:WellKnownResolver._make_well_known_request` (lines 220-270) + +```python + async def _make_well_known_request( + self, server_name: bytes, retry: bool + ) -> Tuple[IResponse, bytes]: + """Make the well known request. + + This will retry the request if requested and it fails (with unable + to connect or receives a 5xx error). + + Args: + server_name: name of the server, from the requested url + retry: Whether to retry the request if it fails. + + Returns: + Returns the response object and body. Response may be a non-200 response. + """ + uri = b"https://%s/.well-known/matrix/server" % (server_name,) + uri_str = uri.decode("ascii") + + headers = { + b"User-Agent": [self.user_agent], + } + + i = 0 + while True: + i += 1 + + logger.info("Fetching %s", uri_str) + try: + response = await make_deferred_yieldable( + self._well_known_agent.request( + b"GET", uri, headers=Headers(headers) + ) + ) + body = await make_deferred_yieldable(readBody(response)) + + if 500 <= response.code < 600: + raise Exception("Non-200 response %s" % (response.code,)) + + return response, body + except defer.CancelledError: + # Bail if we've been cancelled + raise + except Exception as e: + if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: + logger.info("Error fetching %s: %s", uri_str, e) + raise _FetchWellKnownFailure(temporary=True) + + logger.info("Error fetching %s: %s. Retrying", uri_str, e) + + # Sleep briefly in the hopes that they come back up + await self._clock.sleep(0.5) +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@18` (lines 18-18) + +```python +from typing import Callable, Dict, Optional, Tuple +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@24` (lines 24-24) + +```python +from twisted.web.client import RedirectAgent, readBody +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@25` (lines 25-25) + +```python +from twisted.web.http import stringToDatetime +``` + +## `synapse/http/federation/well_known_resolver.py` — `module:@29` (lines 29-29) + +```python +from synapse.logging.context import make_deferred_yieldable +``` + +## `synapse/http/matrixfederationclient.py` — `class:MatrixFederationHttpClient` (lines 209-999) + +```python +class MatrixFederationHttpClient: + """HTTP client used to talk to other homeservers over the federation + protocol. Send client certificates and signs requests. + + Attributes: + agent (twisted.web.client.Agent): The twisted Agent used to send the + requests. + """ + + def __init__(self, hs, tls_client_options_factory): + self.hs = hs + self.signing_key = hs.signing_key + self.server_name = hs.hostname + + # We need to use a DNS resolver which filters out blacklisted IP + # addresses, to prevent DNS rebinding. + self.reactor = BlacklistingReactorWrapper( + hs.get_reactor(), None, hs.config.federation_ip_range_blacklist + ) + + user_agent = hs.version_string + if hs.config.user_agent_suffix: + user_agent = "%s %s" % (user_agent, hs.config.user_agent_suffix) + user_agent = user_agent.encode("ascii") + + self.agent = MatrixFederationAgent( + self.reactor, + tls_client_options_factory, + user_agent, + hs.config.federation_ip_range_blacklist, + ) + + # Use a BlacklistingAgentWrapper to prevent circumventing the IP + # blacklist via IP literals in server names + self.agent = BlacklistingAgentWrapper( + self.agent, ip_blacklist=hs.config.federation_ip_range_blacklist, + ) + + self.clock = hs.get_clock() + self._store = hs.get_datastore() + self.version_string_bytes = hs.version_string.encode("ascii") + self.default_timeout = 60 + + def schedule(x): + self.reactor.callLater(_EPSILON, x) + + self._cooperator = Cooperator(scheduler=schedule) + + async def _send_request_with_optional_trailing_slash( + self, + request: MatrixFederationRequest, + try_trailing_slash_on_400: bool = False, + **send_request_args + ) -> IResponse: + """Wrapper for _send_request which can optionally retry the request + upon receiving a combination of a 400 HTTP response code and a + 'M_UNRECOGNIZED' errcode. This is a workaround for Synapse <= v0.99.3 + due to #3622. + + Args: + request: details of request to be sent + try_trailing_slash_on_400: Whether on receiving a 400 + 'M_UNRECOGNIZED' from the server to retry the request with a + trailing slash appended to the request path. + send_request_args: A dictionary of arguments to pass to `_send_request()`. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + + Returns: + Parsed JSON response body. + """ + try: + response = await self._send_request(request, **send_request_args) + except HttpResponseException as e: + # Received an HTTP error > 300. Check if it meets the requirements + # to retry with a trailing slash + if not try_trailing_slash_on_400: + raise + + if e.code != 400 or e.to_synapse_error().errcode != "M_UNRECOGNIZED": + raise + + # Retry with a trailing slash if we received a 400 with + # 'M_UNRECOGNIZED' which some endpoints can return when omitting a + # trailing slash on Synapse <= v0.99.3. + logger.info("Retrying request with trailing slash") + + # Request is frozen so we create a new instance + request = attr.evolve(request, path=request.path + "/") + + response = await self._send_request(request, **send_request_args) + + return response + + async def _send_request( + self, + request: MatrixFederationRequest, + retry_on_dns_fail: bool = True, + timeout: Optional[int] = None, + long_retries: bool = False, + ignore_backoff: bool = False, + backoff_on_404: bool = False, + ) -> IResponse: + """ + Sends a request to the given server. + + Args: + request: details of request to be sent + + retry_on_dns_fail: true if the request should be retied on DNS failures + + timeout: number of milliseconds to wait for the response headers + (including connecting to the server), *for each attempt*. + 60s by default. + + long_retries: whether to use the long retry algorithm. + + The regular retry algorithm makes 4 attempts, with intervals + [0.5s, 1s, 2s]. + + The long retry algorithm makes 11 attempts, with intervals + [4s, 16s, 60s, 60s, ...] + + Both algorithms add -20%/+40% jitter to the retry intervals. + + Note that the above intervals are *in addition* to the time spent + waiting for the request to complete (up to `timeout` ms). + + NB: the long retry algorithm takes over 20 minutes to complete, with + a default timeout of 60s! + + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + backoff_on_404: Back off if we get a 404 + + Returns: + Resolves with the HTTP response object on success. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + if timeout: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + if ( + self.hs.config.federation_domain_whitelist is not None + and request.destination not in self.hs.config.federation_domain_whitelist + ): + raise FederationDeniedError(request.destination) + + limiter = await synapse.util.retryutils.get_retry_limiter( + request.destination, + self.clock, + self._store, + backoff_on_404=backoff_on_404, + ignore_backoff=ignore_backoff, + ) + + method_bytes = request.method.encode("ascii") + destination_bytes = request.destination.encode("ascii") + path_bytes = request.path.encode("ascii") + if request.query: + query_bytes = encode_query_args(request.query) + else: + query_bytes = b"" + + scope = start_active_span( + "outgoing-federation-request", + tags={ + tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, + tags.PEER_ADDRESS: request.destination, + tags.HTTP_METHOD: request.method, + tags.HTTP_URL: request.path, + }, + finish_on_close=True, + ) + + # Inject the span into the headers + headers_dict = {} # type: Dict[bytes, List[bytes]] + inject_active_span_byte_dict(headers_dict, request.destination) + + headers_dict[b"User-Agent"] = [self.version_string_bytes] + + with limiter, scope: + # XXX: Would be much nicer to retry only at the transaction-layer + # (once we have reliable transactions in place) + if long_retries: + retries_left = MAX_LONG_RETRIES + else: + retries_left = MAX_SHORT_RETRIES + + url_bytes = request.uri + url_str = url_bytes.decode("ascii") + + url_to_sign_bytes = urllib.parse.urlunparse( + (b"", b"", path_bytes, None, query_bytes, b"") + ) + + while True: + try: + json = request.get_json() + if json: + headers_dict[b"Content-Type"] = [b"application/json"] + auth_headers = self.build_auth_headers( + destination_bytes, method_bytes, url_to_sign_bytes, json + ) + data = encode_canonical_json(json) + producer = QuieterFileBodyProducer( + BytesIO(data), cooperator=self._cooperator + ) # type: Optional[IBodyProducer] + else: + producer = None + auth_headers = self.build_auth_headers( + destination_bytes, method_bytes, url_to_sign_bytes + ) + + headers_dict[b"Authorization"] = auth_headers + + logger.debug( + "{%s} [%s] Sending request: %s %s; timeout %fs", + request.txn_id, + request.destination, + request.method, + url_str, + _sec_timeout, + ) + + outgoing_requests_counter.labels(request.method).inc() + + try: + with Measure(self.clock, "outbound_request"): + # we don't want all the fancy cookie and redirect handling + # that treq.request gives: just use the raw Agent. + request_deferred = self.agent.request( + method_bytes, + url_bytes, + headers=Headers(headers_dict), + bodyProducer=producer, + ) + + request_deferred = timeout_deferred( + request_deferred, + timeout=_sec_timeout, + reactor=self.reactor, + ) + + response = await request_deferred + except DNSLookupError as e: + raise RequestSendFailed(e, can_retry=retry_on_dns_fail) from e + except Exception as e: + raise RequestSendFailed(e, can_retry=True) from e + + incoming_responses_counter.labels( + request.method, response.code + ).inc() + + set_tag(tags.HTTP_STATUS_CODE, response.code) + response_phrase = response.phrase.decode("ascii", errors="replace") + + if 200 <= response.code < 300: + logger.debug( + "{%s} [%s] Got response headers: %d %s", + request.txn_id, + request.destination, + response.code, + response_phrase, + ) + pass + else: + logger.info( + "{%s} [%s] Got response headers: %d %s", + request.txn_id, + request.destination, + response.code, + response_phrase, + ) + # :'( + # Update transactions table? + d = treq.content(response) + d = timeout_deferred( + d, timeout=_sec_timeout, reactor=self.reactor + ) + + try: + body = await make_deferred_yieldable(d) + except Exception as e: + # Eh, we're already going to raise an exception so lets + # ignore if this fails. + logger.warning( + "{%s} [%s] Failed to get error response: %s %s: %s", + request.txn_id, + request.destination, + request.method, + url_str, + _flatten_response_never_received(e), + ) + body = None + + exc = HttpResponseException( + response.code, response_phrase, body + ) + + # Retry if the error is a 429 (Too Many Requests), + # otherwise just raise a standard HttpResponseException + if response.code == 429: + raise RequestSendFailed(exc, can_retry=True) from exc + else: + raise exc + + break + except RequestSendFailed as e: + logger.info( + "{%s} [%s] Request failed: %s %s: %s", + request.txn_id, + request.destination, + request.method, + url_str, + _flatten_response_never_received(e.inner_exception), + ) + + if not e.can_retry: + raise + + if retries_left and not timeout: + if long_retries: + delay = 4 ** (MAX_LONG_RETRIES + 1 - retries_left) + delay = min(delay, 60) + delay *= random.uniform(0.8, 1.4) + else: + delay = 0.5 * 2 ** (MAX_SHORT_RETRIES - retries_left) + delay = min(delay, 2) + delay *= random.uniform(0.8, 1.4) + + logger.debug( + "{%s} [%s] Waiting %ss before re-sending...", + request.txn_id, + request.destination, + delay, + ) + + await self.clock.sleep(delay) + retries_left -= 1 + else: + raise + + except Exception as e: + logger.warning( + "{%s} [%s] Request failed: %s %s: %s", + request.txn_id, + request.destination, + request.method, + url_str, + _flatten_response_never_received(e), + ) + raise + return response + + def build_auth_headers( + self, + destination: Optional[bytes], + method: bytes, + url_bytes: bytes, + content: Optional[JsonDict] = None, + destination_is: Optional[bytes] = None, + ) -> List[bytes]: + """ + Builds the Authorization headers for a federation request + Args: + destination: The destination homeserver of the request. + May be None if the destination is an identity server, in which case + destination_is must be non-None. + method: The HTTP method of the request + url_bytes: The URI path of the request + content: The body of the request + destination_is: As 'destination', but if the destination is an + identity server + + Returns: + A list of headers to be added as "Authorization:" headers + """ + request = { + "method": method.decode("ascii"), + "uri": url_bytes.decode("ascii"), + "origin": self.server_name, + } + + if destination is not None: + request["destination"] = destination.decode("ascii") + + if destination_is is not None: + request["destination_is"] = destination_is.decode("ascii") + + if content is not None: + request["content"] = content + + request = sign_json(request, self.server_name, self.signing_key) + + auth_headers = [] + + for key, sig in request["signatures"][self.server_name].items(): + auth_headers.append( + ( + 'X-Matrix origin=%s,key="%s",sig="%s"' + % (self.server_name, key, sig) + ).encode("ascii") + ) + return auth_headers + + async def put_json( + self, + destination: str, + path: str, + args: Optional[QueryArgs] = None, + data: Optional[JsonDict] = None, + json_data_callback: Optional[Callable[[], JsonDict]] = None, + long_retries: bool = False, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + backoff_on_404: bool = False, + try_trailing_slash_on_400: bool = False, + ) -> Union[JsonDict, list]: + """ Sends the specified json data using PUT + + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path. + args: query params + data: A dict containing the data that will be used as + the request body. This will be encoded as JSON. + json_data_callback: A callable returning the dict to + use as the request body. + + long_retries: whether to use the long retry algorithm. See + docs on _send_request for details. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + backoff_on_404: True if we should count a 404 response as + a failure of the server (and should therefore back off future + requests). + try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED + response we should try appending a trailing slash to the end + of the request. Workaround for #3622 in Synapse <= v0.99.3. This + will be attempted before backing off if backing off has been + enabled. + + Returns: + Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="PUT", + destination=destination, + path=path, + query=args, + json_callback=json_data_callback, + json=data, + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request_with_optional_trailing_slash( + request, + try_trailing_slash_on_400, + backoff_on_404=backoff_on_404, + ignore_backoff=ignore_backoff, + long_retries=long_retries, + timeout=timeout, + ) + + if timeout is not None: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms + ) + + return body + + async def post_json( + self, + destination: str, + path: str, + data: Optional[JsonDict] = None, + long_retries: bool = False, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + args: Optional[QueryArgs] = None, + ) -> Union[JsonDict, list]: + """ Sends the specified json data using POST + + Args: + destination: The remote server to send the HTTP request to. + + path: The HTTP path. + + data: A dict containing the data that will be used as + the request body. This will be encoded as JSON. + + long_retries: whether to use the long retry algorithm. See + docs on _send_request for details. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data and + try the request anyway. + + args: query params + Returns: + dict|list: Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + + request = MatrixFederationRequest( + method="POST", destination=destination, path=path, query=args, json=data + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request( + request, + long_retries=long_retries, + timeout=timeout, + ignore_backoff=ignore_backoff, + ) + + if timeout: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms, + ) + return body + + async def get_json( + self, + destination: str, + path: str, + args: Optional[QueryArgs] = None, + retry_on_dns_fail: bool = True, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + try_trailing_slash_on_400: bool = False, + ) -> Union[JsonDict, list]: + """ GETs some json from the given host homeserver and path + + Args: + destination: The remote server to send the HTTP request to. + + path: The HTTP path. + + args: A dictionary used to create query strings, defaults to + None. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED + response we should try appending a trailing slash to the end of + the request. Workaround for #3622 in Synapse <= v0.99.3. + Returns: + Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="GET", destination=destination, path=path, query=args + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request_with_optional_trailing_slash( + request, + try_trailing_slash_on_400, + backoff_on_404=False, + ignore_backoff=ignore_backoff, + retry_on_dns_fail=retry_on_dns_fail, + timeout=timeout, + ) + + if timeout is not None: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms + ) + + return body + + async def delete_json( + self, + destination: str, + path: str, + long_retries: bool = False, + timeout: Optional[int] = None, + ignore_backoff: bool = False, + args: Optional[QueryArgs] = None, + ) -> Union[JsonDict, list]: + """Send a DELETE request to the remote expecting some json response + + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path. + + long_retries: whether to use the long retry algorithm. See + docs on _send_request for details. + + timeout: number of milliseconds to wait for the response. + self._default_timeout (60s) by default. + + Note that we may make several attempts to send the request; this + timeout applies to the time spent waiting for response headers for + *each* attempt (including connection time) as well as the time spent + reading the response body after a 200 response. + + ignore_backoff: true to ignore the historical backoff data and + try the request anyway. + + args: query params + Returns: + Succeeds when we get a 2xx HTTP response. The + result will be the decoded JSON body. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="DELETE", destination=destination, path=path, query=args + ) + + start_ms = self.clock.time_msec() + + response = await self._send_request( + request, + long_retries=long_retries, + timeout=timeout, + ignore_backoff=ignore_backoff, + ) + + if timeout is not None: + _sec_timeout = timeout / 1000 + else: + _sec_timeout = self.default_timeout + + body = await _handle_json_response( + self.reactor, _sec_timeout, request, response, start_ms + ) + return body + + async def get_file( + self, + destination: str, + path: str, + output_stream, + args: Optional[QueryArgs] = None, + retry_on_dns_fail: bool = True, + max_size: Optional[int] = None, + ignore_backoff: bool = False, + ) -> Tuple[int, Dict[bytes, List[bytes]]]: + """GETs a file from a given homeserver + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path to GET. + output_stream: File to write the response body to. + args: Optional dictionary used to create the query string. + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + Returns: + Resolves with an (int,dict) tuple of + the file length and a dict of the response headers. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="GET", destination=destination, path=path, query=args + ) + + response = await self._send_request( + request, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff + ) + + headers = dict(response.headers.getAllRawHeaders()) + + try: + d = readBodyToFile(response, output_stream, max_size) + d.addTimeout(self.default_timeout, self.reactor) + length = await make_deferred_yieldable(d) + except Exception as e: + logger.warning( + "{%s} [%s] Error reading response: %s", + request.txn_id, + request.destination, + e, + ) + raise + logger.info( + "{%s} [%s] Completed: %d %s [%d bytes] %s %s", + request.txn_id, + request.destination, + response.code, + response.phrase.decode("ascii", errors="replace"), + length, + request.method, + request.uri.decode("ascii"), + ) + return (length, headers) +``` + +## `synapse/http/matrixfederationclient.py` — `function:MatrixFederationHttpClient.get_file` (lines 934-999) + +```python + async def get_file( + self, + destination: str, + path: str, + output_stream, + args: Optional[QueryArgs] = None, + retry_on_dns_fail: bool = True, + max_size: Optional[int] = None, + ignore_backoff: bool = False, + ) -> Tuple[int, Dict[bytes, List[bytes]]]: + """GETs a file from a given homeserver + Args: + destination: The remote server to send the HTTP request to. + path: The HTTP path to GET. + output_stream: File to write the response body to. + args: Optional dictionary used to create the query string. + ignore_backoff: true to ignore the historical backoff data + and try the request anyway. + + Returns: + Resolves with an (int,dict) tuple of + the file length and a dict of the response headers. + + Raises: + HttpResponseException: If we get an HTTP response code >= 300 + (except 429). + NotRetryingDestination: If we are not yet ready to retry this + server. + FederationDeniedError: If this destination is not on our + federation whitelist + RequestSendFailed: If there were problems connecting to the + remote, due to e.g. DNS failures, connection timeouts etc. + """ + request = MatrixFederationRequest( + method="GET", destination=destination, path=path, query=args + ) + + response = await self._send_request( + request, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff + ) + + headers = dict(response.headers.getAllRawHeaders()) + + try: + d = readBodyToFile(response, output_stream, max_size) + d.addTimeout(self.default_timeout, self.reactor) + length = await make_deferred_yieldable(d) + except Exception as e: + logger.warning( + "{%s} [%s] Error reading response: %s", + request.txn_id, + request.destination, + e, + ) + raise + logger.info( + "{%s} [%s] Completed: %d %s [%d bytes] %s %s", + request.txn_id, + request.destination, + response.code, + response.phrase.decode("ascii", errors="replace"), + length, + request.method, + request.uri.decode("ascii"), + ) + return (length, headers) +``` + +## `synapse/http/matrixfederationclient.py` — `module:@39` (lines 39-43) + +```python +from synapse.api.errors import ( + FederationDeniedError, + HttpResponseException, + RequestSendFailed, +) +``` + +## `synapse/http/matrixfederationclient.py` — `module:@45` (lines 45-50) + +```python +from synapse.http.client import ( + BlacklistingAgentWrapper, + BlacklistingReactorWrapper, + encode_query_args, + readBodyToFile, +) +``` + +## `tests/http/federation/test_matrix_federation_agent.py` — `class:MatrixFederationAgentTests` (lines 79-1165) + +```python +class MatrixFederationAgentTests(unittest.TestCase): + def setUp(self): + self.reactor = ThreadedMemoryReactorClock() + + self.mock_resolver = Mock() + + config_dict = default_config("test", parse=False) + config_dict["federation_custom_ca_list"] = [get_test_ca_cert_file()] + + self._config = config = HomeServerConfig() + config.parse_config_dict(config_dict, "", "") + + self.tls_factory = FederationPolicyForHTTPS(config) + + self.well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds) + self.had_well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds) + self.well_known_resolver = WellKnownResolver( + self.reactor, + Agent(self.reactor, contextFactory=self.tls_factory), + b"test-agent", + well_known_cache=self.well_known_cache, + had_well_known_cache=self.had_well_known_cache, + ) + + self.agent = MatrixFederationAgent( + reactor=self.reactor, + tls_client_options_factory=self.tls_factory, + user_agent="test-agent", # Note that this is unused since _well_known_resolver is provided. + ip_blacklist=IPSet(), + _srv_resolver=self.mock_resolver, + _well_known_resolver=self.well_known_resolver, + ) + + def _make_connection(self, client_factory, expected_sni): + """Builds a test server, and completes the outgoing client connection + + Returns: + HTTPChannel: the test server + """ + + # build the test server + server_tls_protocol = _build_test_server(get_connection_factory()) + + # now, tell the client protocol factory to build the client protocol (it will be a + # _WrappingProtocol, around a TLSMemoryBIOProtocol, around an + # HTTP11ClientProtocol) and wire the output of said protocol up to the server via + # a FakeTransport. + # + # Normally this would be done by the TCP socket code in Twisted, but we are + # stubbing that out here. + client_protocol = client_factory.buildProtocol(None) + client_protocol.makeConnection( + FakeTransport(server_tls_protocol, self.reactor, client_protocol) + ) + + # tell the server tls protocol to send its stuff back to the client, too + server_tls_protocol.makeConnection( + FakeTransport(client_protocol, self.reactor, server_tls_protocol) + ) + + # grab a hold of the TLS connection, in case it gets torn down + server_tls_connection = server_tls_protocol._tlsConnection + + # fish the test server back out of the server-side TLS protocol. + http_protocol = server_tls_protocol.wrappedProtocol + + # give the reactor a pump to get the TLS juices flowing. + self.reactor.pump((0.1,)) + + # check the SNI + server_name = server_tls_connection.get_servername() + self.assertEqual( + server_name, + expected_sni, + "Expected SNI %s but got %s" % (expected_sni, server_name), + ) + + return http_protocol + + @defer.inlineCallbacks + def _make_get_request(self, uri): + """ + Sends a simple GET request via the agent, and checks its logcontext management + """ + with LoggingContext("one") as context: + fetch_d = self.agent.request(b"GET", uri) + + # Nothing happened yet + self.assertNoResult(fetch_d) + + # should have reset logcontext to the sentinel + _check_logcontext(SENTINEL_CONTEXT) + + try: + fetch_res = yield fetch_d + return fetch_res + except Exception as e: + logger.info("Fetch of %s failed: %s", uri.decode("ascii"), e) + raise + finally: + _check_logcontext(context) + + def _handle_well_known_connection( + self, client_factory, expected_sni, content, response_headers={} + ): + """Handle an outgoing HTTPs connection: wire it up to a server, check that the + request is for a .well-known, and send the response. + + Args: + client_factory (IProtocolFactory): outgoing connection + expected_sni (bytes): SNI that we expect the outgoing connection to send + content (bytes): content to send back as the .well-known + Returns: + HTTPChannel: server impl + """ + # make the connection for .well-known + well_known_server = self._make_connection( + client_factory, expected_sni=expected_sni + ) + # check the .well-known request and send a response + self.assertEqual(len(well_known_server.requests), 1) + request = well_known_server.requests[0] + self.assertEqual( + request.requestHeaders.getRawHeaders(b"user-agent"), [b"test-agent"] + ) + self._send_well_known_response(request, content, headers=response_headers) + return well_known_server + + def _send_well_known_response(self, request, content, headers={}): + """Check that an incoming request looks like a valid .well-known request, and + send back the response. + """ + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/.well-known/matrix/server") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + # send back a response + for k, v in headers.items(): + request.setHeader(k, v) + request.write(content) + request.finish() + + self.reactor.pump((0.1,)) + + def test_get(self): + """ + happy-path test of a GET request with an explicit port + """ + self.reactor.lookups["testserv"] = "1.2.3.4" + test_d = self._make_get_request(b"matrix://testserv:8448/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"testserv:8448"] + ) + self.assertEqual( + request.requestHeaders.getRawHeaders(b"user-agent"), [b"test-agent"] + ) + content = request.content.read() + self.assertEqual(content, b"") + + # Deferred is still without a result + self.assertNoResult(test_d) + + # send the headers + request.responseHeaders.setRawHeaders(b"Content-Type", [b"application/json"]) + request.write("") + + self.reactor.pump((0.1,)) + + response = self.successResultOf(test_d) + + # that should give us a Response object + self.assertEqual(response.code, 200) + + # Send the body + request.write('{ "a": 1 }'.encode("ascii")) + request.finish() + + self.reactor.pump((0.1,)) + + # check it can be read + json = self.successResultOf(treq.json_content(response)) + self.assertEqual(json, {"a": 1}) + + def test_get_ip_address(self): + """ + Test the behaviour when the server name contains an explicit IP (with no port) + """ + # there will be a getaddrinfo on the IP + self.reactor.lookups["1.2.3.4"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://1.2.3.4/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"1.2.3.4"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_ipv6_address(self): + """ + Test the behaviour when the server name contains an explicit IPv6 address + (with no port) + """ + + # there will be a getaddrinfo on the IP + self.reactor.lookups["::1"] = "::1" + + test_d = self._make_get_request(b"matrix://[::1]/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "::1") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"[::1]"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_ipv6_address_with_port(self): + """ + Test the behaviour when the server name contains an explicit IPv6 address + (with explicit port) + """ + + # there will be a getaddrinfo on the IP + self.reactor.lookups["::1"] = "::1" + + test_d = self._make_get_request(b"matrix://[::1]:80/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "::1") + self.assertEqual(port, 80) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"[::1]:80"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_hostname_bad_cert(self): + """ + Test the behaviour when the certificate on the server doesn't match the hostname + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv1"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv1/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + # fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the + # .well-known request fails. + self.reactor.pump((0.4,)) + + # now there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv1" + ) + + # we should fall back to a direct connection + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv1") + + # there should be no requests + self.assertEqual(len(http_server.requests), 0) + + # ... and the request should have failed + e = self.failureResultOf(test_d, ResponseNeverReceived) + failure_reason = e.value.reasons[0] + self.assertIsInstance(failure_reason.value, VerificationError) + + def test_get_ip_address_bad_cert(self): + """ + Test the behaviour when the server name contains an explicit IP, but + the server cert doesn't cover it + """ + # there will be a getaddrinfo on the IP + self.reactor.lookups["1.2.3.5"] = "1.2.3.5" + + test_d = self._make_get_request(b"matrix://1.2.3.5/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.5") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=None) + + # there should be no requests + self.assertEqual(len(http_server.requests), 0) + + # ... and the request should have failed + e = self.failureResultOf(test_d, ResponseNeverReceived) + failure_reason = e.value.reasons[0] + self.assertIsInstance(failure_reason.value, VerificationError) + + def test_get_no_srv_no_well_known(self): + """ + Test the behaviour when the server name has no port, no SRV, and no well-known + """ + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + # fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the + # .well-known request fails. + self.reactor.pump((0.4,)) + + # now there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # we should fall back to a direct connection + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_well_known(self): + """Test the behaviour when the .well-known delegates elsewhere + """ + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + self.reactor.lookups["target-server"] = "1::f" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + content=b'{ "m.server": "target-server" }', + ) + + # there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.target-server" + ) + + # now we should get a connection to the target server + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1::f") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"target-server" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"target-server"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + self.assertEqual(self.well_known_cache[b"testserv"], b"target-server") + + # check the cache expires + self.reactor.pump((48 * 3600,)) + self.well_known_cache.expire() + self.assertNotIn(b"testserv", self.well_known_cache) + + def test_get_well_known_redirect(self): + """Test the behaviour when the server name has no port and no SRV record, but + the .well-known has a 300 redirect + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + self.reactor.lookups["target-server"] = "1::f" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + redirect_server = self._make_connection( + client_factory, expected_sni=b"testserv" + ) + + # send a 302 redirect + self.assertEqual(len(redirect_server.requests), 1) + request = redirect_server.requests[0] + request.redirect(b"https://testserv/even_better_known") + request.finish() + + self.reactor.pump((0.1,)) + + # now there should be another connection + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + well_known_server = self._make_connection( + client_factory, expected_sni=b"testserv" + ) + + self.assertEqual(len(well_known_server.requests), 1, "No request after 302") + request = well_known_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/even_better_known") + request.write(b'{ "m.server": "target-server" }') + request.finish() + + self.reactor.pump((0.1,)) + + # there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.target-server" + ) + + # now we should get a connection to the target server + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1::f") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"target-server" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"target-server"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + self.assertEqual(self.well_known_cache[b"testserv"], b"target-server") + + # check the cache expires + self.reactor.pump((48 * 3600,)) + self.well_known_cache.expire() + self.assertNotIn(b"testserv", self.well_known_cache) + + def test_get_invalid_well_known(self): + """ + Test the behaviour when the server name has an *invalid* well-known (and no SRV) + """ + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, expected_sni=b"testserv", content=b"NOT JSON" + ) + + # now there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # we should fall back to a direct connection + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop() + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_well_known_unsigned_cert(self): + """Test the behaviour when the .well-known server presents a cert + not signed by a CA + """ + + # we use the same test server as the other tests, but use an agent with + # the config left to the default, which will not trust it (since the + # presented cert is signed by a test CA) + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + self.reactor.lookups["testserv"] = "1.2.3.4" + + config = default_config("test", parse=True) + + # Build a new agent and WellKnownResolver with a different tls factory + tls_factory = FederationPolicyForHTTPS(config) + agent = MatrixFederationAgent( + reactor=self.reactor, + tls_client_options_factory=tls_factory, + user_agent=b"test-agent", # This is unused since _well_known_resolver is passed below. + ip_blacklist=IPSet(), + _srv_resolver=self.mock_resolver, + _well_known_resolver=WellKnownResolver( + self.reactor, + Agent(self.reactor, contextFactory=tls_factory), + b"test-agent", + well_known_cache=self.well_known_cache, + had_well_known_cache=self.had_well_known_cache, + ), + ) + + test_d = agent.request(b"GET", b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + http_proto = self._make_connection(client_factory, expected_sni=b"testserv") + + # there should be no requests + self.assertEqual(len(http_proto.requests), 0) + + # and there should be a SRV lookup instead + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + def test_get_hostname_srv(self): + """ + Test the behaviour when there is a single SRV record + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [Server(host=b"srvtarget", port=8443)] + ) + self.reactor.lookups["srvtarget"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # the request for a .well-known will have failed with a DNS lookup error. + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_get_well_known_srv(self): + """Test the behaviour when the .well-known redirects to a place where there + is a SRV. + """ + self.reactor.lookups["testserv"] = "1.2.3.4" + self.reactor.lookups["srvtarget"] = "5.6.7.8" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [Server(host=b"srvtarget", port=8443)] + ) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + content=b'{ "m.server": "target-server" }', + ) + + # there should be a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.target-server" + ) + + # now we should get a connection to the target of the SRV record + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "5.6.7.8") + self.assertEqual(port, 8443) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"target-server" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"target-server"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_idna_servername(self): + """test the behaviour when the server name has idna chars in""" + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service([]) + + # the resolver is always called with the IDNA hostname as a native string. + self.reactor.lookups["xn--bcher-kva.com"] = "1.2.3.4" + + # this is idna for bücher.com + test_d = self._make_get_request(b"matrix://xn--bcher-kva.com/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + # No SRV record lookup yet + self.mock_resolver.resolve_service.assert_not_called() + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + # fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the + # .well-known request fails. + self.reactor.pump((0.4,)) + + # now there should have been a SRV lookup + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.xn--bcher-kva.com" + ) + + # We should fall back to port 8448 + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 2) + (host, port, client_factory, _timeout, _bindAddress) = clients[1] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8448) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"xn--bcher-kva.com" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"xn--bcher-kva.com"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_idna_srv_target(self): + """test the behaviour when the target of a SRV record has idna chars""" + + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [Server(host=b"xn--trget-3qa.com", port=8443)] # târget.com + ) + self.reactor.lookups["xn--trget-3qa.com"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://xn--bcher-kva.com/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.xn--bcher-kva.com" + ) + + # Make sure treq is trying to connect + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients[0] + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # make a test server, and wire up the client + http_server = self._make_connection( + client_factory, expected_sni=b"xn--bcher-kva.com" + ) + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual( + request.requestHeaders.getRawHeaders(b"host"), [b"xn--bcher-kva.com"] + ) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) + + def test_well_known_cache(self): + self.reactor.lookups["testserv"] = "1.2.3.4" + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + well_known_server = self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + response_headers={b"Cache-Control": b"max-age=1000"}, + content=b'{ "m.server": "target-server" }', + ) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # close the tcp connection + well_known_server.loseConnection() + + # repeat the request: it should hit the cache + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # expire the cache + self.reactor.pump((1000.0,)) + + # now it should connect again + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + content=b'{ "m.server": "other-server" }', + ) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"other-server") + + def test_well_known_cache_with_temp_failure(self): + """Test that we refetch well-known before the cache expires, and that + it ignores transient errors. + """ + + self.reactor.lookups["testserv"] = "1.2.3.4" + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # there should be an attempt to connect on port 443 for the .well-known + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 443) + + well_known_server = self._handle_well_known_connection( + client_factory, + expected_sni=b"testserv", + response_headers={b"Cache-Control": b"max-age=1000"}, + content=b'{ "m.server": "target-server" }', + ) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # close the tcp connection + well_known_server.loseConnection() + + # Get close to the cache expiry, this will cause the resolver to do + # another lookup. + self.reactor.pump((900.0,)) + + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + # The resolver may retry a few times, so fonx all requests that come along + attempts = 0 + while self.reactor.tcpClients: + clients = self.reactor.tcpClients + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + + attempts += 1 + + # fonx the connection attempt, this will be treated as a temporary + # failure. + client_factory.clientConnectionFailed(None, Exception("nope")) + + # There's a few sleeps involved, so we have to pump the reactor a + # bit. + self.reactor.pump((1.0, 1.0)) + + # We expect to see more than one attempt as there was previously a valid + # well known. + self.assertGreater(attempts, 1) + + # Resolver should return cached value, despite the lookup failing. + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, b"target-server") + + # Expire both caches and repeat the request + self.reactor.pump((10000.0,)) + + # Repated the request, this time it should fail if the lookup fails. + fetch_d = defer.ensureDeferred( + self.well_known_resolver.get_well_known(b"testserv") + ) + + clients = self.reactor.tcpClients + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + client_factory.clientConnectionFailed(None, Exception("nope")) + self.reactor.pump((0.4,)) + + r = self.successResultOf(fetch_d) + self.assertEqual(r.delegated_server, None) + + def test_srv_fallbacks(self): + """Test that other SRV results are tried if the first one fails. + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [ + Server(host=b"target.com", port=8443), + Server(host=b"target.com", port=8444), + ] + ) + self.reactor.lookups["target.com"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # We should see an attempt to connect to the first server + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # Fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # There's a 300ms delay in HostnameEndpoint + self.reactor.pump((0.4,)) + + # Hasn't failed yet + self.assertNoResult(test_d) + + # We shouldnow see an attempt to connect to the second server + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8444) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) +``` + +## `tests/http/federation/test_matrix_federation_agent.py` — `function:MatrixFederationAgentTests.test_srv_fallbacks` (lines 1110-1165) + +```python + def test_srv_fallbacks(self): + """Test that other SRV results are tried if the first one fails. + """ + self.mock_resolver.resolve_service.side_effect = generate_resolve_service( + [ + Server(host=b"target.com", port=8443), + Server(host=b"target.com", port=8444), + ] + ) + self.reactor.lookups["target.com"] = "1.2.3.4" + + test_d = self._make_get_request(b"matrix://testserv/foo/bar") + + # Nothing happened yet + self.assertNoResult(test_d) + + self.mock_resolver.resolve_service.assert_called_once_with( + b"_matrix._tcp.testserv" + ) + + # We should see an attempt to connect to the first server + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8443) + + # Fonx the connection + client_factory.clientConnectionFailed(None, Exception("nope")) + + # There's a 300ms delay in HostnameEndpoint + self.reactor.pump((0.4,)) + + # Hasn't failed yet + self.assertNoResult(test_d) + + # We shouldnow see an attempt to connect to the second server + clients = self.reactor.tcpClients + self.assertEqual(len(clients), 1) + (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0) + self.assertEqual(host, "1.2.3.4") + self.assertEqual(port, 8444) + + # make a test server, and wire up the client + http_server = self._make_connection(client_factory, expected_sni=b"testserv") + + self.assertEqual(len(http_server.requests), 1) + request = http_server.requests[0] + self.assertEqual(request.method, b"GET") + self.assertEqual(request.path, b"/foo/bar") + self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"]) + + # finish the request + request.finish() + self.reactor.pump((0.1,)) + self.successResultOf(test_d) +``` + +## `tests/http/federation/test_matrix_federation_agent.py` — `module:@38` (lines 38-41) + +```python +from synapse.http.federation.well_known_resolver import ( + WellKnownResolver, + _cache_period_from_headers, +) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a439e49fd0f1b9d12127fa13eb25c7223b3b9523 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/task.json @@ -0,0 +1,83 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-7c3c693e688548564c9a", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-7c3c693e688548564c9a", + "project_id": "pyvul__matrix-org__synapse", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "synapse/http/client.py", + "synapse/http/federation/well_known_resolver.py", + "synapse/http/matrixfederationclient.py", + "tests/http/federation/test_matrix_federation_agent.py" + ], + "patch_units": { + "before": [ + "class:SimpleHttpClient", + "function:SimpleHttpClient.get_file", + "class:_ReadBodyToFileProtocol", + "function:_ReadBodyToFileProtocol.__init__", + "function:_ReadBodyToFileProtocol.dataReceived", + "function:readBodyToFile", + "class:WellKnownResolver", + "function:WellKnownResolver._make_well_known_request", + "module:@18", + "module:@24", + "module:@25", + "module:@29", + "class:MatrixFederationHttpClient", + "function:MatrixFederationHttpClient.get_file", + "module:@39", + "module:@45", + "class:MatrixFederationAgentTests", + "function:MatrixFederationAgentTests.test_srv_fallbacks", + "module:@38" + ], + "after": [ + "class:SimpleHttpClient", + "function:SimpleHttpClient.get_file", + "class:BodyExceededMaxSize", + "class:_ReadBodyWithMaxSizeProtocol", + "function:_ReadBodyWithMaxSizeProtocol.dataReceived", + "function:read_body_with_max_size", + "class:WellKnownResolver", + "function:WellKnownResolver._make_well_known_request", + "module:@18", + "module:@25", + "module:@30", + "module:@59", + "class:MatrixFederationHttpClient", + "function:MatrixFederationHttpClient.get_file", + "module:@39", + "module:@47", + "class:MatrixFederationAgentTests", + "function:MatrixFederationAgentTests.test_well_known_too_large", + "module:@38" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/6a6057b0bbd3fab24f36e00dd97e382100a3a1862783463c95da20a717cddba5/database", + "cache_key": "6a6057b0bbd3fab24f36e00dd97e382100a3a1862783463c95da20a717cddba5", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/c474ba133c769ef096cd279e7d588e147b0a159eb7525c7ab86120f43670199a/database", + "cache_key": "c474ba133c769ef096cd279e7d588e147b0a159eb7525c7ab86120f43670199a", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/1f09a419a22f438c449e1d6c148390d8ede1943043df7f0542a902191e72354e/database", + "cache_key": "1f09a419a22f438c449e1d6c148390d8ede1943043df7f0542a902191e72354e", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-7c3c693e688548564c9a/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-7c3c693e688548564c9a/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c3c693e688548564c9a/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..65bae870f1571568a3c15a03c52b84c444e8e9da --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/patch.diff @@ -0,0 +1,85 @@ +diff --git a/.travis.yml b/.travis.yml +index 1975b26..b7b5b14 100644 +--- a/.travis.yml ++++ b/.travis.yml +@@ -1,17 +1,30 @@ + language: python + python: + - 3.5 +-env: +- - TOX_ENV=py26 +- - TOX_ENV=py27 +- - TOX_ENV=py32 +- - TOX_ENV=py33 +- - TOX_ENV=py34 +- - TOX_ENV=py35 +- - TOX_ENV=pypy +- - TOX_ENV=pypy3 +- - JYTHON=true ++matrix: ++ fast_finish: true ++ include: ++ - python: 3.5 ++ env: TOX_ENV=py35 ++ - python: 3.4 ++ env: TOX_ENV=py34 ++ - python: 3.3 ++ env: TOX_ENV=py33 ++ - python: 3.2 ++ env: TOX_ENV=py32 ++ - python: 2.7 ++ env: TOX_ENV=py27 ++ - python: 2.6 ++ env: TOX_ENV=py26 ++ - python: pypy ++ env: TOX_ENV=pypy ++ - python: pypy3 ++ env: TOX_ENV=pypy3 ++ - python: 3.5 ++ env: $JYTHON=true + install: ++ - if [ $TOX_ENV = "py32" ]; then travis_retry pip install "virtualenv<14.0.0" "tox<1.8.0"; fi ++ - if [ $TOX_ENV = "pypy3" ]; then travis_retry pip install "virtualenv<14.0.0" "tox<1.8.0"; fi + - if [ -z "$JYTHON" ]; then pip install codecov; fi + - if [ "$TOX_ENV" ]; then travis_retry pip install "virtualenv<14.0.0" tox; fi + before_install: +@@ -22,4 +35,4 @@ script: + - if [ "$JYTHON" ]; then travis_retry jython setup.py test; fi + - if [ "$TOX_ENV" ]; then tox -e $TOX_ENV; fi + after_success: +- - codecov +\ No newline at end of file ++ - codecov +diff --git a/pyanyapi/interfaces.py b/pyanyapi/interfaces.py +index 698c637..c0914b2 100644 +--- a/pyanyapi/interfaces.py ++++ b/pyanyapi/interfaces.py +@@ -274,7 +274,7 @@ class YAMLInterface(DictInterface): + + def perform_parsing(self): + try: +- return yaml.load(self.content) ++ return yaml.safe_load(self.content) + except yaml.error.YAMLError: + raise ResponseParseError(self._error_message, self.content) + +diff --git a/tests/test_parsers.py b/tests/test_parsers.py +index 38223e2..4958b21 100644 +--- a/tests/test_parsers.py ++++ b/tests/test_parsers.py +@@ -63,6 +63,15 @@ def test_yaml_parser_error(): + parsed.test + + ++def test_yaml_parser_vulnerability(): ++ """ ++ In case of usage of yaml.load `test` value will be equal to 0. ++ """ ++ parsed = YAMLParser({'test': 'container > test'}).parse('!!python/object/apply:os.system ["exit 0"]') ++ with pytest.raises(ResponseParseError): ++ parsed.test ++ ++ + @lxml_is_supported + @pytest.mark.parametrize( + 'settings', ( diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8a6719c4a59148749d11c0a7c1e5d82f0f4106ae --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/post_context.md @@ -0,0 +1,36 @@ +# Patch-overlapping Python context after the fix + +## `pyanyapi/interfaces.py` — `class:YAMLInterface` (lines 272-279) + +```python +class YAMLInterface(DictInterface): + _error_message = 'YAML data can not be parsed.' + + def perform_parsing(self): + try: + return yaml.safe_load(self.content) + except yaml.error.YAMLError: + raise ResponseParseError(self._error_message, self.content) +``` + +## `pyanyapi/interfaces.py` — `function:YAMLInterface.perform_parsing` (lines 275-279) + +```python + def perform_parsing(self): + try: + return yaml.safe_load(self.content) + except yaml.error.YAMLError: + raise ResponseParseError(self._error_message, self.content) +``` + +## `tests/test_parsers.py` — `function:test_yaml_parser_vulnerability` (lines 66-72) + +```python +def test_yaml_parser_vulnerability(): + """ + In case of usage of yaml.load `test` value will be equal to 0. + """ + parsed = YAMLParser({'test': 'container > test'}).parse('!!python/object/apply:os.system ["exit 0"]') + with pytest.raises(ResponseParseError): + parsed.test +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..13ac16f5876d595d7d4d99be44a4919d8d38aec4 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/pre_context.md @@ -0,0 +1,33 @@ +# Patch-overlapping Python context before the fix + +## `pyanyapi/interfaces.py` — `class:YAMLInterface` (lines 272-279) + +```python +class YAMLInterface(DictInterface): + _error_message = 'YAML data can not be parsed.' + + def perform_parsing(self): + try: + return yaml.load(self.content) + except yaml.error.YAMLError: + raise ResponseParseError(self._error_message, self.content) +``` + +## `pyanyapi/interfaces.py` — `function:YAMLInterface.perform_parsing` (lines 275-279) + +```python + def perform_parsing(self): + try: + return yaml.load(self.content) + except yaml.error.YAMLError: + raise ResponseParseError(self._error_message, self.content) +``` + +## `tests/test_parsers.py` — `function:test_xml_parsed` (lines 66-76) + +```python +def test_xml_parsed(settings): + parsed = XMLParser(settings).parse(XML_CONTENT) + assert parsed.success == ['1'] + assert parsed.parse('string(//id/text())') == '32e9a4a2' +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1be507b6322f3ae734806cc59d0e09733fb8c0d4 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/task.json @@ -0,0 +1,49 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-7c7eaf17f0df49603ae4", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-7c7eaf17f0df49603ae4", + "project_id": "pyvul__stranger6667__pyanyapi", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "pyanyapi/interfaces.py", + "tests/test_parsers.py" + ], + "patch_units": { + "before": [ + "class:YAMLInterface", + "function:YAMLInterface.perform_parsing", + "function:test_xml_parsed" + ], + "after": [ + "class:YAMLInterface", + "function:YAMLInterface.perform_parsing", + "function:test_yaml_parser_vulnerability" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/15820bacdfad7cb7ef73028198e676741f9997630f1dd41eebfeda47eba2eab4/database", + "cache_key": "15820bacdfad7cb7ef73028198e676741f9997630f1dd41eebfeda47eba2eab4", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/e3060be8f4972cd628df59c01096d1dc34dad220f8dcfaba3e01acb7aea917a4/database", + "cache_key": "e3060be8f4972cd628df59c01096d1dc34dad220f8dcfaba3e01acb7aea917a4", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/8b5eba99fc5084c8b749962da98838a46839d089af243667e8bdb76e99341f0b/database", + "cache_key": "8b5eba99fc5084c8b749962da98838a46839d089af243667e8bdb76e99341f0b", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-7c7eaf17f0df49603ae4/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-7c7eaf17f0df49603ae4/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-7c7eaf17f0df49603ae4/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4b6c20ae4759ec045ca14218743ab59e74221510 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/patch.diff @@ -0,0 +1,28 @@ +diff --git a/weixin/msg.py b/weixin/msg.py +index cb4e74a..89806b0 100644 +--- a/weixin/msg.py ++++ b/weixin/msg.py +@@ -64,7 +64,8 @@ class WeixinMsg(object): + + def parse(self, content): + raw = {} +- root = etree.fromstring(content) ++ root = etree.fromstring(content, ++ parser=etree.XMLParser(resolve_entities=False)) + for child in root: + raw[child.tag] = child.text + +diff --git a/weixin/pay.py b/weixin/pay.py +index 4ab8cfb..1f8e231 100644 +--- a/weixin/pay.py ++++ b/weixin/pay.py +@@ -79,7 +79,8 @@ class WeixinPay(object): + + def to_dict(self, content): + raw = {} +- root = etree.fromstring(content.encode("utf-8")) ++ root = etree.fromstring(content.encode("utf-8"), ++ parser=etree.XMLParser(resolve_entities=False)) + for child in root: + raw[child.tag] = child.text + return raw diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..28cca58fce18fbfa08a428a43d34a6c47d1b14ec --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/post_context.md @@ -0,0 +1,538 @@ +# Patch-overlapping Python context after the fix + +## `weixin/msg.py` — `class:WeixinMsg` (lines 40-337) + +```python +class WeixinMsg(object): + + def __init__(self, token, sender=None, expires_in=0): + self.token = token + self.sender = sender + self.expires_in = expires_in + self._registry = dict() + + def validate(self, signature, timestamp, nonce): + if not self.token: + raise WeixinMsgError("weixin token is missing") + + if self.expires_in: + try: + timestamp = int(timestamp) + except ValueError: + return False + delta = time.time() - timestamp + if delta < 0 or delta > self.expires_in: + return False + values = [self.token, str(timestamp), str(nonce)] + s = ''.join(sorted(values)) + hsh = hashlib.sha1(s.encode("utf-8")).hexdigest() + return signature == hsh + + def parse(self, content): + raw = {} + root = etree.fromstring(content, + parser=etree.XMLParser(resolve_entities=False)) + for child in root: + raw[child.tag] = child.text + + formatted = self.format(raw) + msg_type = formatted['type'] + msg_parser = getattr(self, 'parse_{0}'.format(msg_type), None) + if callable(msg_parser): + parsed = msg_parser(raw) + else: + parsed = self.parse_invalid_type(raw) + + formatted.update(parsed) + return formatted + + def format(self, kwargs): + timestamp = int(kwargs['CreateTime']) + return { + 'id': kwargs.get('MsgId'), + 'timestamp': timestamp, + 'receiver': kwargs['ToUserName'], + 'sender': kwargs['FromUserName'], + 'type': kwargs['MsgType'], + 'time': datetime.fromtimestamp(timestamp), + } + + def parse_text(self, raw): + return {'content': raw['Content']} + + def parse_image(self, raw): + return {'picurl': raw['PicUrl']} + + def parse_location(self, raw): + return { + 'location_x': raw['Location_X'], + 'location_y': raw['Location_Y'], + 'scale': int(raw.get('Scale', 0)), + 'label': raw['Label'], + } + + def parse_link(self, raw): + return { + 'title': raw['Title'], + 'description': raw['Description'], + 'url': raw['url'], + } + + def parse_voice(self, raw): + return { + 'media_id': raw['MediaId'], + 'format': raw['Format'], + 'recognition': raw['Recognition'], + } + + def parse_video(self, raw): + return { + 'media_id': raw['MediaId'], + 'thumb_media_id': raw['ThumbMediaId'], + } + + def parse_shortvideo(self, raw): + return { + 'media_id': raw['MediaId'], + 'thumb_media_id': raw['ThumbMediaId'], + } + + def parse_event(self, raw): + return { + 'event': raw.get('Event'), + 'event_key': raw.get('EventKey'), + 'ticket': raw.get('Ticket'), + 'latitude': raw.get('Latitude'), + 'longitude': raw.get('Longitude'), + 'precision': raw.get('Precision'), + 'status': raw.get('status') + } + + def parse_invalid_type(self, raw): + return {} + + def reply(self, username=None, type='text', sender=None, **kwargs): + if not username: + raise RuntimeError("username is missing") + sender = sender or self.sender + if not sender: + raise RuntimeError('WEIXIN_SENDER or sender argument is missing') + + if type == 'text': + content = kwargs.get('content', '') + return text_reply(username, sender, content) + + if type == 'music': + values = {} + for k in ('title', 'description', 'music_url', 'hq_music_url'): + values[k] = kwargs[k] + return music_reply(username, sender, **values) + + if type == 'news': + items = kwargs['articles'] + return news_reply(username, sender, *items) + + if type == 'customer_service': + service_account = kwargs['service_account'] + return transfer_customer_service_reply(username, sender, + service_account) + + if type == 'image': + media_id = kwargs.get('media_id') + return image_reply(username, sender, media_id) + + if type == 'voice': + media_id = kwargs.get('media_id') + return voice_reply(username, sender, media_id) + + if type == 'video': + values = {} + for k in ('media_id', 'title', 'description'): + values[k] = kwargs[k] + return video_reply(username, sender, **values) + + def register(self, type, key=None, func=None): + if func: + key = '*' if not key else key + self._registry.setdefault(type, dict())[key] = func + return func + return self.__call__(type, key) + + def __call__(self, type, key): + def wrapper(func): + self.register(type, key, func) + return func + return wrapper + + @property + def all(self): + return self.register('*') + + def text(self, key='*'): + return self.register('text', key) + + def __getattr__(self, key): + key = key.lower() + if key in ['image', 'video', 'voice', 'shortvideo', 'location', 'link', 'event']: + return self.register(key) + if key in ['subscribe', 'unsubscribe', 'location', 'click', 'view', 'scan', \ + 'scancode_push', 'scancode_waitmsg', 'pic_sysphoto', \ + 'pic_photo_or_album', 'pic_weixin', 'location_select', \ + 'qualification_verify_success', 'qualification_verify_fail', 'naming_verify_success', \ + 'naming_verify_fail', 'annual_renew', 'verify_expired', \ + 'card_pass_check', 'user_get_card', 'user_del_card', 'user_consume_card', \ + 'user_pay_from_pay_cell', 'user_view_card', 'user_enter_session_from_card', \ + 'card_sku_remind']: + return self.register('event', key) + raise AttributeError('invalid attribute "' + key + '"') + + def django_view_func(self): + + def run(request): + if HttpResponse is None: + raise RuntimeError('django_view_func need Django be installed') + signature = request.GET.get('signature') + + timestamp = request.GET.get('timestamp') + nonce = request.GET.get('nonce') + if not self.validate(signature, timestamp, nonce): + return HttpResponseForbidden('signature failed') + if request.method == 'GET': + echostr = request.args.get('echostr', '') + return HttpResponse(echostr) + elif request.method == "POST": + try: + ret = self.parse(request.body) + except ValueError: + return HttpResponseForbidden('invalid') + + func = None + type = ret['type'] + _registry = self._registry.get(type, dict()) + if type == 'text': + if ret['content'] in _registry: + func = _registry[ret['content']] + elif type == 'event': + if ret['event'].lower() in _registry: + func = _registry[ret['event'].lower()] + + if func is None and '*' in _registry: + func = _registry['*'] + if func is None and '*' in self._registry: + func = self._registry.get('*', dict()).get('*') + + text = '' + if func is None: + text = 'failed' + + if callable(func): + text = func(**ret) + + content = '' + if isinstance(text, basestring): + if text: + content = self.reply( + username=ret['sender'], + sender=ret['receiver'], + content=text, + ) + elif isinstance(text, dict): + text.setdefault('username', ret['sender']) + text.setdefault('sender', ret['receiver']) + content = self.reply(**text) + + return HttpResponse(content, content_type='text/xml; charset=utf-8') + return HttpResponseNotAllowed(['GET', 'POST']) + return run + + def view_func(self): + if request is None: + raise RuntimeError('view_func need Flask be installed') + + signature = request.args.get('signature') + timestamp = request.args.get('timestamp') + nonce = request.args.get('nonce') + if not self.validate(signature, timestamp, nonce): + return 'signature failed', 400 + if request.method == 'GET': + echostr = request.args.get('echostr', '') + return echostr + + try: + ret = self.parse(request.data) + except ValueError: + return 'invalid', 400 + + func = None + type = ret['type'] + _registry = self._registry.get(type, dict()) + if type == 'text': + if ret['content'] in _registry: + func = _registry[ret['content']] + elif type == 'event': + if ret['event'].lower() in _registry: + func = _registry[ret['event'].lower()] + + if func is None and '*' in _registry: + func = _registry['*'] + if func is None and '*' in self._registry: + func = self._registry.get('*', dict()).get('*') + + text = '' + if func is None: + text = 'failed' + + if callable(func): + text = func(**ret) + + content = '' + if isinstance(text, basestring): + if text: + content = self.reply( + username=ret['sender'], + sender=ret['receiver'], + content=text, + ) + elif isinstance(text, dict): + text.setdefault('username', ret['sender']) + text.setdefault('sender', ret['receiver']) + content = self.reply(**text) + + return Response(content, content_type='text/xml; charset=utf-8') + + view_func.methods = ['GET', 'POST'] +``` + +## `weixin/msg.py` — `function:WeixinMsg.parse` (lines 65-81) + +```python + def parse(self, content): + raw = {} + root = etree.fromstring(content, + parser=etree.XMLParser(resolve_entities=False)) + for child in root: + raw[child.tag] = child.text + + formatted = self.format(raw) + msg_type = formatted['type'] + msg_parser = getattr(self, 'parse_{0}'.format(msg_type), None) + if callable(msg_parser): + parsed = msg_parser(raw) + else: + parsed = self.parse_invalid_type(raw) + + formatted.update(parsed) + return formatted +``` + +## `weixin/pay.py` — `class:WeixinPay` (lines 40-234) + +```python +class WeixinPay(object): + + def __init__(self, app_id, mch_id, mch_key, notify_url, key=None, cert=None): + self.app_id = app_id + self.mch_id = mch_id + self.mch_key = mch_key + self.notify_url = notify_url + self.key = key + self.cert = cert + self.sess = requests.Session() + + @property + def remote_addr(self): + if request is not None: + return request.remote_addr + return "" + + @property + def nonce_str(self): + char = string.ascii_letters + string.digits + return "".join(random.choice(char) for _ in range(32)) + + def sign(self, raw): + raw = [(k, str(raw[k]) if isinstance(raw[k], int) else raw[k]) + for k in sorted(raw.keys())] + s = "&".join("=".join(kv) for kv in raw if kv[1]) + s += "&key={0}".format(self.mch_key) + return hashlib.md5(s.encode("utf-8")).hexdigest().upper() + + def check(self, data): + sign = data.pop("sign") + return sign == self.sign(data) + + def to_xml(self, raw): + s = "" + for k, v in raw.items(): + s += "<{0}>{1}".format(k, v) + s = "{0}".format(s) + return s.encode("utf-8") + + def to_dict(self, content): + raw = {} + root = etree.fromstring(content.encode("utf-8"), + parser=etree.XMLParser(resolve_entities=False)) + for child in root: + raw[child.tag] = child.text + return raw + + def _fetch(self, url, data, use_cert=False): + data.setdefault("appid", self.app_id) + data.setdefault("mch_id", self.mch_id) + data.setdefault("nonce_str", self.nonce_str) + data.setdefault("sign", self.sign(data)) + + if use_cert: + resp = self.sess.post(url, data=self.to_xml(data), cert=(self.cert, self.key)) + else: + resp = self.sess.post(url, data=self.to_xml(data)) + content = resp.content.decode("utf-8") + if "return_code" in content: + data = Map(self.to_dict(content)) + if data.return_code == FAIL: + raise WeixinPayError(data.return_msg) + if "result_code" in content and data.result_code == FAIL: + raise WeixinPayError(data.err_code_des) + return data + return content + + def reply(self, msg, ok=True): + code = SUCCESS if ok else FAIL + return self.to_xml(dict(return_code=code, return_msg=msg)) + + def unified_order(self, **data): + """ + 统一下单 + out_trade_no、body、total_fee、trade_type必填 + app_id, mchid, nonce_str自动填写 + spbill_create_ip 在flask框架下可以自动填写, 非flask框架需要主动传入此参数 + """ + url = "https://api.mch.weixin.qq.com/pay/unifiedorder" + + # 必填参数 + if "out_trade_no" not in data: + raise WeixinPayError("缺少统一支付接口必填参数out_trade_no") + if "body" not in data: + raise WeixinPayError("缺少统一支付接口必填参数body") + if "total_fee" not in data: + raise WeixinPayError("缺少统一支付接口必填参数total_fee") + if "trade_type" not in data: + raise WeixinPayError("缺少统一支付接口必填参数trade_type") + + # 关联参数 + if data["trade_type"] == "JSAPI" and "openid" not in data: + raise WeixinPayError("trade_type为JSAPI时,openid为必填参数") + if data["trade_type"] == "NATIVE" and "product_id" not in data: + raise WeixinPayError("trade_type为NATIVE时,product_id为必填参数") + data.setdefault("notify_url", self.notify_url) + if "spbill_create_ip" not in data: + data.setdefault("spbill_create_ip", self.remote_addr) + + raw = self._fetch(url, data) + return raw + + def jsapi(self, **kwargs): + """ + 生成给JavaScript调用的数据 + 详细规则参考 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6 + """ + kwargs.setdefault("trade_type", "JSAPI") + raw = self.unified_order(**kwargs) + package = "prepay_id={0}".format(raw["prepay_id"]) + timestamp = str(int(time.time())) + nonce_str = self.nonce_str + raw = dict(appId=self.app_id, timeStamp=timestamp, + nonceStr=nonce_str, package=package, signType="MD5") + sign = self.sign(raw) + return dict(package=package, appId=self.app_id, signType="MD5", + timeStamp=timestamp, nonceStr=nonce_str, sign=sign) + + def order_query(self, **data): + """ + 订单查询 + out_trade_no, transaction_id至少填一个 + appid, mchid, nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/orderquery" + + if "out_trade_no" not in data and "transaction_id" not in data: + raise WeixinPayError("订单查询接口中,out_trade_no、transaction_id至少填一个") + + return self._fetch(url, data) + + def close_order(self, out_trade_no, **data): + """ + 关闭订单 + out_trade_no必填 + appid, mchid, nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/closeorder" + + data.setdefault("out_trade_no", out_trade_no) + + return self._fetch(url, data) + + def refund(self, **data): + """ + 申请退款 + out_trade_no、transaction_id至少填一个且 + out_refund_no、total_fee、refund_fee、op_user_id为必填参数 + appid、mchid、nonce_str不需要填入 + """ + if not self.key or not self.cert: + raise WeixinError("退款申请接口需要双向证书") + url = "https://api.mch.weixin.qq.com/secapi/pay/refund" + if "out_trade_no" not in data and "transaction_id" not in data: + raise WeixinPayError("退款申请接口中,out_trade_no、transaction_id至少填一个") + if "out_refund_no" not in data: + raise WeixinPayError("退款申请接口中,缺少必填参数out_refund_no"); + if "total_fee" not in data: + raise WeixinPayError("退款申请接口中,缺少必填参数total_fee"); + if "refund_fee" not in data: + raise WeixinPayError("退款申请接口中,缺少必填参数refund_fee"); + + return self._fetch(url, data, True) + + def refund_query(self, **data): + """ + 查询退款 + 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时, + 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 + + out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个 + appid、mchid、nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/refundquery" + if "out_refund_no" not in data and "out_trade_no" not in data \ + and "transaction_id" not in data and "refund_id" not in data: + raise WeixinPayError("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个") + + return self._fetch(url, data) + + def download_bill(self, bill_date, bill_type="ALL", **data): + """ + 下载对账单 + bill_date、bill_type为必填参数 + appid、mchid、nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/downloadbill" + data.setdefault("bill_date", bill_date) + data.setdefault("bill_type", bill_type) + + if "bill_date" not in data: + raise WeixinPayError("对账单接口中,缺少必填参数bill_date") + + return self._fetch(url, data) +``` + +## `weixin/pay.py` — `function:WeixinPay.to_dict` (lines 80-86) + +```python + def to_dict(self, content): + raw = {} + root = etree.fromstring(content.encode("utf-8"), + parser=etree.XMLParser(resolve_entities=False)) + for child in root: + raw[child.tag] = child.text + return raw +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8839432d15577ab347f4091f4bf535d0edc4cfb5 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/pre_context.md @@ -0,0 +1,534 @@ +# Patch-overlapping Python context before the fix + +## `weixin/msg.py` — `class:WeixinMsg` (lines 40-336) + +```python +class WeixinMsg(object): + + def __init__(self, token, sender=None, expires_in=0): + self.token = token + self.sender = sender + self.expires_in = expires_in + self._registry = dict() + + def validate(self, signature, timestamp, nonce): + if not self.token: + raise WeixinMsgError("weixin token is missing") + + if self.expires_in: + try: + timestamp = int(timestamp) + except ValueError: + return False + delta = time.time() - timestamp + if delta < 0 or delta > self.expires_in: + return False + values = [self.token, str(timestamp), str(nonce)] + s = ''.join(sorted(values)) + hsh = hashlib.sha1(s.encode("utf-8")).hexdigest() + return signature == hsh + + def parse(self, content): + raw = {} + root = etree.fromstring(content) + for child in root: + raw[child.tag] = child.text + + formatted = self.format(raw) + msg_type = formatted['type'] + msg_parser = getattr(self, 'parse_{0}'.format(msg_type), None) + if callable(msg_parser): + parsed = msg_parser(raw) + else: + parsed = self.parse_invalid_type(raw) + + formatted.update(parsed) + return formatted + + def format(self, kwargs): + timestamp = int(kwargs['CreateTime']) + return { + 'id': kwargs.get('MsgId'), + 'timestamp': timestamp, + 'receiver': kwargs['ToUserName'], + 'sender': kwargs['FromUserName'], + 'type': kwargs['MsgType'], + 'time': datetime.fromtimestamp(timestamp), + } + + def parse_text(self, raw): + return {'content': raw['Content']} + + def parse_image(self, raw): + return {'picurl': raw['PicUrl']} + + def parse_location(self, raw): + return { + 'location_x': raw['Location_X'], + 'location_y': raw['Location_Y'], + 'scale': int(raw.get('Scale', 0)), + 'label': raw['Label'], + } + + def parse_link(self, raw): + return { + 'title': raw['Title'], + 'description': raw['Description'], + 'url': raw['url'], + } + + def parse_voice(self, raw): + return { + 'media_id': raw['MediaId'], + 'format': raw['Format'], + 'recognition': raw['Recognition'], + } + + def parse_video(self, raw): + return { + 'media_id': raw['MediaId'], + 'thumb_media_id': raw['ThumbMediaId'], + } + + def parse_shortvideo(self, raw): + return { + 'media_id': raw['MediaId'], + 'thumb_media_id': raw['ThumbMediaId'], + } + + def parse_event(self, raw): + return { + 'event': raw.get('Event'), + 'event_key': raw.get('EventKey'), + 'ticket': raw.get('Ticket'), + 'latitude': raw.get('Latitude'), + 'longitude': raw.get('Longitude'), + 'precision': raw.get('Precision'), + 'status': raw.get('status') + } + + def parse_invalid_type(self, raw): + return {} + + def reply(self, username=None, type='text', sender=None, **kwargs): + if not username: + raise RuntimeError("username is missing") + sender = sender or self.sender + if not sender: + raise RuntimeError('WEIXIN_SENDER or sender argument is missing') + + if type == 'text': + content = kwargs.get('content', '') + return text_reply(username, sender, content) + + if type == 'music': + values = {} + for k in ('title', 'description', 'music_url', 'hq_music_url'): + values[k] = kwargs[k] + return music_reply(username, sender, **values) + + if type == 'news': + items = kwargs['articles'] + return news_reply(username, sender, *items) + + if type == 'customer_service': + service_account = kwargs['service_account'] + return transfer_customer_service_reply(username, sender, + service_account) + + if type == 'image': + media_id = kwargs.get('media_id') + return image_reply(username, sender, media_id) + + if type == 'voice': + media_id = kwargs.get('media_id') + return voice_reply(username, sender, media_id) + + if type == 'video': + values = {} + for k in ('media_id', 'title', 'description'): + values[k] = kwargs[k] + return video_reply(username, sender, **values) + + def register(self, type, key=None, func=None): + if func: + key = '*' if not key else key + self._registry.setdefault(type, dict())[key] = func + return func + return self.__call__(type, key) + + def __call__(self, type, key): + def wrapper(func): + self.register(type, key, func) + return func + return wrapper + + @property + def all(self): + return self.register('*') + + def text(self, key='*'): + return self.register('text', key) + + def __getattr__(self, key): + key = key.lower() + if key in ['image', 'video', 'voice', 'shortvideo', 'location', 'link', 'event']: + return self.register(key) + if key in ['subscribe', 'unsubscribe', 'location', 'click', 'view', 'scan', \ + 'scancode_push', 'scancode_waitmsg', 'pic_sysphoto', \ + 'pic_photo_or_album', 'pic_weixin', 'location_select', \ + 'qualification_verify_success', 'qualification_verify_fail', 'naming_verify_success', \ + 'naming_verify_fail', 'annual_renew', 'verify_expired', \ + 'card_pass_check', 'user_get_card', 'user_del_card', 'user_consume_card', \ + 'user_pay_from_pay_cell', 'user_view_card', 'user_enter_session_from_card', \ + 'card_sku_remind']: + return self.register('event', key) + raise AttributeError('invalid attribute "' + key + '"') + + def django_view_func(self): + + def run(request): + if HttpResponse is None: + raise RuntimeError('django_view_func need Django be installed') + signature = request.GET.get('signature') + + timestamp = request.GET.get('timestamp') + nonce = request.GET.get('nonce') + if not self.validate(signature, timestamp, nonce): + return HttpResponseForbidden('signature failed') + if request.method == 'GET': + echostr = request.args.get('echostr', '') + return HttpResponse(echostr) + elif request.method == "POST": + try: + ret = self.parse(request.body) + except ValueError: + return HttpResponseForbidden('invalid') + + func = None + type = ret['type'] + _registry = self._registry.get(type, dict()) + if type == 'text': + if ret['content'] in _registry: + func = _registry[ret['content']] + elif type == 'event': + if ret['event'].lower() in _registry: + func = _registry[ret['event'].lower()] + + if func is None and '*' in _registry: + func = _registry['*'] + if func is None and '*' in self._registry: + func = self._registry.get('*', dict()).get('*') + + text = '' + if func is None: + text = 'failed' + + if callable(func): + text = func(**ret) + + content = '' + if isinstance(text, basestring): + if text: + content = self.reply( + username=ret['sender'], + sender=ret['receiver'], + content=text, + ) + elif isinstance(text, dict): + text.setdefault('username', ret['sender']) + text.setdefault('sender', ret['receiver']) + content = self.reply(**text) + + return HttpResponse(content, content_type='text/xml; charset=utf-8') + return HttpResponseNotAllowed(['GET', 'POST']) + return run + + def view_func(self): + if request is None: + raise RuntimeError('view_func need Flask be installed') + + signature = request.args.get('signature') + timestamp = request.args.get('timestamp') + nonce = request.args.get('nonce') + if not self.validate(signature, timestamp, nonce): + return 'signature failed', 400 + if request.method == 'GET': + echostr = request.args.get('echostr', '') + return echostr + + try: + ret = self.parse(request.data) + except ValueError: + return 'invalid', 400 + + func = None + type = ret['type'] + _registry = self._registry.get(type, dict()) + if type == 'text': + if ret['content'] in _registry: + func = _registry[ret['content']] + elif type == 'event': + if ret['event'].lower() in _registry: + func = _registry[ret['event'].lower()] + + if func is None and '*' in _registry: + func = _registry['*'] + if func is None and '*' in self._registry: + func = self._registry.get('*', dict()).get('*') + + text = '' + if func is None: + text = 'failed' + + if callable(func): + text = func(**ret) + + content = '' + if isinstance(text, basestring): + if text: + content = self.reply( + username=ret['sender'], + sender=ret['receiver'], + content=text, + ) + elif isinstance(text, dict): + text.setdefault('username', ret['sender']) + text.setdefault('sender', ret['receiver']) + content = self.reply(**text) + + return Response(content, content_type='text/xml; charset=utf-8') + + view_func.methods = ['GET', 'POST'] +``` + +## `weixin/msg.py` — `function:WeixinMsg.parse` (lines 65-80) + +```python + def parse(self, content): + raw = {} + root = etree.fromstring(content) + for child in root: + raw[child.tag] = child.text + + formatted = self.format(raw) + msg_type = formatted['type'] + msg_parser = getattr(self, 'parse_{0}'.format(msg_type), None) + if callable(msg_parser): + parsed = msg_parser(raw) + else: + parsed = self.parse_invalid_type(raw) + + formatted.update(parsed) + return formatted +``` + +## `weixin/pay.py` — `class:WeixinPay` (lines 40-233) + +```python +class WeixinPay(object): + + def __init__(self, app_id, mch_id, mch_key, notify_url, key=None, cert=None): + self.app_id = app_id + self.mch_id = mch_id + self.mch_key = mch_key + self.notify_url = notify_url + self.key = key + self.cert = cert + self.sess = requests.Session() + + @property + def remote_addr(self): + if request is not None: + return request.remote_addr + return "" + + @property + def nonce_str(self): + char = string.ascii_letters + string.digits + return "".join(random.choice(char) for _ in range(32)) + + def sign(self, raw): + raw = [(k, str(raw[k]) if isinstance(raw[k], int) else raw[k]) + for k in sorted(raw.keys())] + s = "&".join("=".join(kv) for kv in raw if kv[1]) + s += "&key={0}".format(self.mch_key) + return hashlib.md5(s.encode("utf-8")).hexdigest().upper() + + def check(self, data): + sign = data.pop("sign") + return sign == self.sign(data) + + def to_xml(self, raw): + s = "" + for k, v in raw.items(): + s += "<{0}>{1}".format(k, v) + s = "{0}".format(s) + return s.encode("utf-8") + + def to_dict(self, content): + raw = {} + root = etree.fromstring(content.encode("utf-8")) + for child in root: + raw[child.tag] = child.text + return raw + + def _fetch(self, url, data, use_cert=False): + data.setdefault("appid", self.app_id) + data.setdefault("mch_id", self.mch_id) + data.setdefault("nonce_str", self.nonce_str) + data.setdefault("sign", self.sign(data)) + + if use_cert: + resp = self.sess.post(url, data=self.to_xml(data), cert=(self.cert, self.key)) + else: + resp = self.sess.post(url, data=self.to_xml(data)) + content = resp.content.decode("utf-8") + if "return_code" in content: + data = Map(self.to_dict(content)) + if data.return_code == FAIL: + raise WeixinPayError(data.return_msg) + if "result_code" in content and data.result_code == FAIL: + raise WeixinPayError(data.err_code_des) + return data + return content + + def reply(self, msg, ok=True): + code = SUCCESS if ok else FAIL + return self.to_xml(dict(return_code=code, return_msg=msg)) + + def unified_order(self, **data): + """ + 统一下单 + out_trade_no、body、total_fee、trade_type必填 + app_id, mchid, nonce_str自动填写 + spbill_create_ip 在flask框架下可以自动填写, 非flask框架需要主动传入此参数 + """ + url = "https://api.mch.weixin.qq.com/pay/unifiedorder" + + # 必填参数 + if "out_trade_no" not in data: + raise WeixinPayError("缺少统一支付接口必填参数out_trade_no") + if "body" not in data: + raise WeixinPayError("缺少统一支付接口必填参数body") + if "total_fee" not in data: + raise WeixinPayError("缺少统一支付接口必填参数total_fee") + if "trade_type" not in data: + raise WeixinPayError("缺少统一支付接口必填参数trade_type") + + # 关联参数 + if data["trade_type"] == "JSAPI" and "openid" not in data: + raise WeixinPayError("trade_type为JSAPI时,openid为必填参数") + if data["trade_type"] == "NATIVE" and "product_id" not in data: + raise WeixinPayError("trade_type为NATIVE时,product_id为必填参数") + data.setdefault("notify_url", self.notify_url) + if "spbill_create_ip" not in data: + data.setdefault("spbill_create_ip", self.remote_addr) + + raw = self._fetch(url, data) + return raw + + def jsapi(self, **kwargs): + """ + 生成给JavaScript调用的数据 + 详细规则参考 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6 + """ + kwargs.setdefault("trade_type", "JSAPI") + raw = self.unified_order(**kwargs) + package = "prepay_id={0}".format(raw["prepay_id"]) + timestamp = str(int(time.time())) + nonce_str = self.nonce_str + raw = dict(appId=self.app_id, timeStamp=timestamp, + nonceStr=nonce_str, package=package, signType="MD5") + sign = self.sign(raw) + return dict(package=package, appId=self.app_id, signType="MD5", + timeStamp=timestamp, nonceStr=nonce_str, sign=sign) + + def order_query(self, **data): + """ + 订单查询 + out_trade_no, transaction_id至少填一个 + appid, mchid, nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/orderquery" + + if "out_trade_no" not in data and "transaction_id" not in data: + raise WeixinPayError("订单查询接口中,out_trade_no、transaction_id至少填一个") + + return self._fetch(url, data) + + def close_order(self, out_trade_no, **data): + """ + 关闭订单 + out_trade_no必填 + appid, mchid, nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/closeorder" + + data.setdefault("out_trade_no", out_trade_no) + + return self._fetch(url, data) + + def refund(self, **data): + """ + 申请退款 + out_trade_no、transaction_id至少填一个且 + out_refund_no、total_fee、refund_fee、op_user_id为必填参数 + appid、mchid、nonce_str不需要填入 + """ + if not self.key or not self.cert: + raise WeixinError("退款申请接口需要双向证书") + url = "https://api.mch.weixin.qq.com/secapi/pay/refund" + if "out_trade_no" not in data and "transaction_id" not in data: + raise WeixinPayError("退款申请接口中,out_trade_no、transaction_id至少填一个") + if "out_refund_no" not in data: + raise WeixinPayError("退款申请接口中,缺少必填参数out_refund_no"); + if "total_fee" not in data: + raise WeixinPayError("退款申请接口中,缺少必填参数total_fee"); + if "refund_fee" not in data: + raise WeixinPayError("退款申请接口中,缺少必填参数refund_fee"); + + return self._fetch(url, data, True) + + def refund_query(self, **data): + """ + 查询退款 + 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时, + 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 + + out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个 + appid、mchid、nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/refundquery" + if "out_refund_no" not in data and "out_trade_no" not in data \ + and "transaction_id" not in data and "refund_id" not in data: + raise WeixinPayError("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个") + + return self._fetch(url, data) + + def download_bill(self, bill_date, bill_type="ALL", **data): + """ + 下载对账单 + bill_date、bill_type为必填参数 + appid、mchid、nonce_str不需要填入 + """ + url = "https://api.mch.weixin.qq.com/pay/downloadbill" + data.setdefault("bill_date", bill_date) + data.setdefault("bill_type", bill_type) + + if "bill_date" not in data: + raise WeixinPayError("对账单接口中,缺少必填参数bill_date") + + return self._fetch(url, data) +``` + +## `weixin/pay.py` — `function:WeixinPay.to_dict` (lines 80-85) + +```python + def to_dict(self, content): + raw = {} + root = etree.fromstring(content.encode("utf-8")) + for child in root: + raw[child.tag] = child.text + return raw +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..97bb543e5803625de5735684e61ce19a38ed3b22 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-810ace2bf3e4aa0f04a1", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-810ace2bf3e4aa0f04a1", + "project_id": "pyvul__zwczou__weixin-python", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "weixin/msg.py", + "weixin/pay.py" + ], + "patch_units": { + "before": [ + "class:WeixinMsg", + "function:WeixinMsg.parse", + "class:WeixinPay", + "function:WeixinPay.to_dict" + ], + "after": [ + "class:WeixinMsg", + "function:WeixinMsg.parse", + "class:WeixinPay", + "function:WeixinPay.to_dict" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/88fd491ac2223f17096e1644358fe8bfac8e522f10dde97495b9538244921b2d/database", + "cache_key": "88fd491ac2223f17096e1644358fe8bfac8e522f10dde97495b9538244921b2d", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/a087e5f4d76385ca8edc63b272ae5e9a0be31d86b1d996f2ca3e646c88d54b8a/database", + "cache_key": "a087e5f4d76385ca8edc63b272ae5e9a0be31d86b1d996f2ca3e646c88d54b8a", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/123a35fe09b8125937c943f3980787bcc75454305a8fabf03bb63a36478af1a5/database", + "cache_key": "123a35fe09b8125937c943f3980787bcc75454305a8fabf03bb63a36478af1a5", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-810ace2bf3e4aa0f04a1/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-810ace2bf3e4aa0f04a1/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-810ace2bf3e4aa0f04a1/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f652ff2eee53b44d19ba44acb1b8314540c4df79 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/patch.diff @@ -0,0 +1,38 @@ +diff --git a/nvflare/lighter/provision.py b/nvflare/lighter/provision.py +index a00009039..34a420a2b 100644 +--- a/nvflare/lighter/provision.py ++++ b/nvflare/lighter/provision.py +@@ -21,10 +21,9 @@ import shutil + import sys + import webbrowser + +-import yaml +- + from nvflare.fuel.utils.class_utils import instantiate_class + from nvflare.lighter.spec import Participant, Project, Provisioner ++from nvflare.lighter.utils import load_yaml + + + def main(): +@@ -77,7 +76,7 @@ def main(): + project_full_path = os.path.join(current_path, project_file) + print(f"Project yaml file: {project_full_path}.") + +- project_dict = yaml.load(open(project_full_path, "r"), Loader=yaml.Loader) ++ project_dict = load_yaml(project_full_path) + api_version = project_dict.get("api_version") + if api_version not in [3]: + raise ValueError(f"API version expected 3 but found {api_version}") +diff --git a/nvflare/lighter/utils.py b/nvflare/lighter/utils.py +index 561bd3e0e..05f10b595 100644 +--- a/nvflare/lighter/utils.py ++++ b/nvflare/lighter/utils.py +@@ -46,7 +46,7 @@ def sign_all(content_folder, signing_pri_key): + + + def load_yaml(file_name): +- return yaml.load(open(file_name, "r"), Loader=yaml.Loader) ++ return yaml.safe_load(open(file_name, "r")) + + + def sh_replace(src, mapping_dict): diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..1883dd3b12883968baf0d3586cf88a05d34a1d64 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/post_context.md @@ -0,0 +1,96 @@ +# Patch-overlapping Python context after the fix + +## `nvflare/lighter/provision.py` — `function:main` (lines 29-99) + +```python +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("-p", "--project_file", type=str, default="project.yml", help="file to describe FL project") + parser.add_argument("-w", "--workspace", type=str, default="workspace", help="directory used by provision") + parser.add_argument("-c", "--custom_folder", type=str, default=".", help="additional folder to load python codes") + parser.add_argument( + "-u", + "--ui_tool", + action="store_true", + help="Run provisioning UI tool to generate project.yml file", + ) + + args = parser.parse_args() + + file_path = pathlib.Path(__file__).parent.absolute() + current_path = os.getcwd() + custom_folder_path = os.path.join(current_path, args.custom_folder) + sys.path.append(custom_folder_path) + print("Path list (sys.path) for python codes loading: {}".format(sys.path)) + + # main project file + project_file = args.project_file + current_project_yml = os.path.join(current_path, "project.yml") + if len(sys.argv) == 1 and not os.path.exists(current_project_yml): + answer = input( + f"No project.yml found in current folder. Is it OK to generate one at {current_project_yml} for you? (y/N) " + ) + if answer.strip().upper() == "Y": + shutil.copyfile(os.path.join(file_path, "project.yml"), current_project_yml) + print(f"{current_project_yml} was created. Please edit it to fit your FL configuration.") + exit(0) + + if args.ui_tool: + ui_helper_path = os.path.join(file_path, "provision_helper.html") + ui_helper_url = f"file://{ui_helper_path}" + webbrowser.open_new_tab(ui_helper_url) + print( + "\n******\n" + "Now launching provisioning UI tool.\n" + "After generating project.yml in the browser and saving it to your local folder,\n" + "please re-run provision with -p option, pointing to the generated project.yml, to generate all packages.\n******\n" + ) + exit(0) + + workspace = args.workspace + workspace_full_path = os.path.join(current_path, workspace) + + project_full_path = os.path.join(current_path, project_file) + print(f"Project yaml file: {project_full_path}.") + + project_dict = load_yaml(project_full_path) + api_version = project_dict.get("api_version") + if api_version not in [3]: + raise ValueError(f"API version expected 3 but found {api_version}") + + project_name = project_dict.get("name") + project_description = project_dict.get("description", "") + participants = list() + for p in project_dict.get("participants"): + participants.append(Participant(**p)) + project = Project(name=project_name, description=project_description, participants=participants) + + builders = list() + for b in project_dict.get("builders"): + path = b.get("path") + args = b.get("args") + builders.append(instantiate_class(path, args)) + + provisioner = Provisioner(workspace_full_path, builders) + + provisioner.provision(project) +``` + +## `nvflare/lighter/provision.py` — `module:@24` (lines 24-24) + +```python +from nvflare.fuel.utils.class_utils import instantiate_class +``` + +## `nvflare/lighter/provision.py` — `module:@26` (lines 26-26) + +```python +from nvflare.lighter.utils import load_yaml +``` + +## `nvflare/lighter/utils.py` — `function:load_yaml` (lines 48-49) + +```python +def load_yaml(file_name): + return yaml.safe_load(open(file_name, "r")) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..3c9628ef4ca3ebfa1dac8c111dbfd121f8f16bb6 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/pre_context.md @@ -0,0 +1,90 @@ +# Patch-overlapping Python context before the fix + +## `nvflare/lighter/provision.py` — `function:main` (lines 30-100) + +```python +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("-p", "--project_file", type=str, default="project.yml", help="file to describe FL project") + parser.add_argument("-w", "--workspace", type=str, default="workspace", help="directory used by provision") + parser.add_argument("-c", "--custom_folder", type=str, default=".", help="additional folder to load python codes") + parser.add_argument( + "-u", + "--ui_tool", + action="store_true", + help="Run provisioning UI tool to generate project.yml file", + ) + + args = parser.parse_args() + + file_path = pathlib.Path(__file__).parent.absolute() + current_path = os.getcwd() + custom_folder_path = os.path.join(current_path, args.custom_folder) + sys.path.append(custom_folder_path) + print("Path list (sys.path) for python codes loading: {}".format(sys.path)) + + # main project file + project_file = args.project_file + current_project_yml = os.path.join(current_path, "project.yml") + if len(sys.argv) == 1 and not os.path.exists(current_project_yml): + answer = input( + f"No project.yml found in current folder. Is it OK to generate one at {current_project_yml} for you? (y/N) " + ) + if answer.strip().upper() == "Y": + shutil.copyfile(os.path.join(file_path, "project.yml"), current_project_yml) + print(f"{current_project_yml} was created. Please edit it to fit your FL configuration.") + exit(0) + + if args.ui_tool: + ui_helper_path = os.path.join(file_path, "provision_helper.html") + ui_helper_url = f"file://{ui_helper_path}" + webbrowser.open_new_tab(ui_helper_url) + print( + "\n******\n" + "Now launching provisioning UI tool.\n" + "After generating project.yml in the browser and saving it to your local folder,\n" + "please re-run provision with -p option, pointing to the generated project.yml, to generate all packages.\n******\n" + ) + exit(0) + + workspace = args.workspace + workspace_full_path = os.path.join(current_path, workspace) + + project_full_path = os.path.join(current_path, project_file) + print(f"Project yaml file: {project_full_path}.") + + project_dict = yaml.load(open(project_full_path, "r"), Loader=yaml.Loader) + api_version = project_dict.get("api_version") + if api_version not in [3]: + raise ValueError(f"API version expected 3 but found {api_version}") + + project_name = project_dict.get("name") + project_description = project_dict.get("description", "") + participants = list() + for p in project_dict.get("participants"): + participants.append(Participant(**p)) + project = Project(name=project_name, description=project_description, participants=participants) + + builders = list() + for b in project_dict.get("builders"): + path = b.get("path") + args = b.get("args") + builders.append(instantiate_class(path, args)) + + provisioner = Provisioner(workspace_full_path, builders) + + provisioner.provision(project) +``` + +## `nvflare/lighter/provision.py` — `module:@24` (lines 24-24) + +```python +import yaml +``` + +## `nvflare/lighter/utils.py` — `function:load_yaml` (lines 48-49) + +```python +def load_yaml(file_name): + return yaml.load(open(file_name, "r"), Loader=yaml.Loader) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1e561a526e3ee089372d7eb7b9f35a46a3531f36 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-812f35b535c5e549929b", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-812f35b535c5e549929b", + "project_id": "pyvul__nvidia__nvflare", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "nvflare/lighter/provision.py", + "nvflare/lighter/utils.py" + ], + "patch_units": { + "before": [ + "function:main", + "module:@24", + "function:load_yaml" + ], + "after": [ + "function:main", + "module:@24", + "module:@26", + "function:load_yaml" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/0c74f67edeac885371c5795fb5db4e46a3ae1ebe715fff561a666c7e5549f7c1/database", + "cache_key": "0c74f67edeac885371c5795fb5db4e46a3ae1ebe715fff561a666c7e5549f7c1", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/e544f3e58c71b5f2093f8bea6c589e01394fd70fcfdcc50ad73f6bf7a37344be/database", + "cache_key": "e544f3e58c71b5f2093f8bea6c589e01394fd70fcfdcc50ad73f6bf7a37344be", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/18bff336ccc01b2550b176d0d232f30be820a98efc31cdc3441453fa19e7d0a7/database", + "cache_key": "18bff336ccc01b2550b176d0d232f30be820a98efc31cdc3441453fa19e7d0a7", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-812f35b535c5e549929b/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-812f35b535c5e549929b/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-812f35b535c5e549929b/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c2236ea2523a4ca5534d5c2eb32e54af7b767d4c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/patch.diff @@ -0,0 +1,19 @@ +diff --git a/lib/ansible/playbook/__init__.py b/lib/ansible/playbook/__init__.py +index 8b69d19a0e..712cce7428 100644 +--- a/lib/ansible/playbook/__init__.py ++++ b/lib/ansible/playbook/__init__.py +@@ -447,13 +447,7 @@ class PlayBook(object): + basedir = self.inventory.basedir() + filename = "%s.retry" % os.path.basename(self.filename) + filename = filename.replace(".yml","") +- +- if not os.path.exists('/var/tmp/ansible'): +- try: +- os.makedirs('/var/tmp/ansible') +- except: +- pass +- filename = os.path.join('/var/tmp/ansible', filename) ++ filename = os.path.join(os.path.expandvars('$HOME/'), filename) + + try: + fd = open(filename, 'w') diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..aa46a6801556b3042144e748ad45d1bea51a1fa7 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/post_context.md @@ -0,0 +1,558 @@ +# Patch-overlapping Python context after the fix + +## `lib/ansible/playbook/__init__.py` — `class:PlayBook` (lines 34-557) + +```python +class PlayBook(object): + ''' + runs an ansible playbook, given as a datastructure or YAML filename. + A playbook is a deployment, config management, or automation based + set of commands to run in series. + + multiple plays/tasks do not execute simultaneously, but tasks in each + pattern do execute in parallel (according to the number of forks + requested) among the hosts they address + ''' + + # ***************************************************** + + def __init__(self, + playbook = None, + host_list = C.DEFAULT_HOST_LIST, + module_path = None, + forks = C.DEFAULT_FORKS, + timeout = C.DEFAULT_TIMEOUT, + remote_user = C.DEFAULT_REMOTE_USER, + remote_pass = C.DEFAULT_REMOTE_PASS, + sudo_pass = C.DEFAULT_SUDO_PASS, + remote_port = None, + transport = C.DEFAULT_TRANSPORT, + private_key_file = C.DEFAULT_PRIVATE_KEY_FILE, + callbacks = None, + runner_callbacks = None, + stats = None, + sudo = False, + sudo_user = C.DEFAULT_SUDO_USER, + extra_vars = None, + only_tags = None, + subset = C.DEFAULT_SUBSET, + inventory = None, + check = False, + diff = False, + any_errors_fatal = False): + + """ + playbook: path to a playbook file + host_list: path to a file like /etc/ansible/hosts + module_path: path to ansible modules, like /usr/share/ansible/ + forks: desired level of paralellism + timeout: connection timeout + remote_user: run as this user if not specified in a particular play + remote_pass: use this remote password (for all plays) vs using SSH keys + sudo_pass: if sudo==True, and a password is required, this is the sudo password + remote_port: default remote port to use if not specified with the host or play + transport: how to connect to hosts that don't specify a transport (local, paramiko, etc) + callbacks output callbacks for the playbook + runner_callbacks: more callbacks, this time for the runner API + stats: holds aggregrate data about events occuring to each host + sudo: if not specified per play, requests all plays use sudo mode + inventory: can be specified instead of host_list to use a pre-existing inventory object + check: don't change anything, just try to detect some potential changes + """ + + self.SETUP_CACHE = SETUP_CACHE + + if playbook is None or callbacks is None or runner_callbacks is None or stats is None: + raise Exception('missing required arguments') + + if extra_vars is None: + extra_vars = {} + if only_tags is None: + only_tags = [ 'all' ] + + self.check = check + self.diff = diff + self.module_path = module_path + self.forks = forks + self.timeout = timeout + self.remote_user = remote_user + self.remote_pass = remote_pass + self.remote_port = remote_port + self.transport = transport + self.callbacks = callbacks + self.runner_callbacks = runner_callbacks + self.stats = stats + self.sudo = sudo + self.sudo_pass = sudo_pass + self.sudo_user = sudo_user + self.extra_vars = extra_vars + self.global_vars = {} + self.private_key_file = private_key_file + self.only_tags = only_tags + self.any_errors_fatal = any_errors_fatal + + self.callbacks.playbook = self + self.runner_callbacks.playbook = self + + if inventory is None: + self.inventory = ansible.inventory.Inventory(host_list) + self.inventory.subset(subset) + else: + self.inventory = inventory + + self.basedir = os.path.dirname(playbook) or '.' + vars = {} + if self.inventory.basedir() is not None: + vars['inventory_dir'] = self.inventory.basedir() + self.filename = playbook + (self.playbook, self.play_basedirs) = self._load_playbook_from_file(playbook, vars) + + # ***************************************************** + + def _load_playbook_from_file(self, path, vars={}): + ''' + run top level error checking on playbooks and allow them to include other playbooks. + ''' + + playbook_data = utils.parse_yaml_from_file(path) + accumulated_plays = [] + play_basedirs = [] + + if type(playbook_data) != list: + raise errors.AnsibleError("parse error: playbooks must be formatted as a YAML list") + + basedir = os.path.dirname(path) or '.' + utils.plugins.push_basedir(basedir) + for play in playbook_data: + if type(play) != dict: + raise errors.AnsibleError("parse error: each play in a playbook must be a YAML dictionary (hash), recieved: %s" % play) + + if 'include' in play: + # a playbook (list of plays) decided to include some other list of plays + # from another file. The result is a flat list of plays in the end. + + tokens = shlex.split(play['include']) + + incvars = vars.copy() + if 'vars' in play: + if isinstance(play['vars'], dict): + incvars.update(play['vars']) + elif isinstance(play['vars'], list): + for v in play['vars']: + incvars.update(v) + + # allow key=value parameters to be specified on the include line + # to set variables + + for t in tokens[1:]: + + (k,v) = t.split("=", 1) + incvars[k] = template(basedir, v, incvars) + + included_path = utils.path_dwim(basedir, template(basedir, tokens[0], incvars)) + (plays, basedirs) = self._load_playbook_from_file(included_path, incvars) + for p in plays: + # support for parameterized play includes works by passing + # those variables along to the subservient play + if 'vars' not in p: + p['vars'] = {} + if isinstance(p['vars'], dict): + p['vars'].update(incvars) + elif isinstance(p['vars'], list): + # nobody should really do this, but handle vars: a=1 b=2 + p['vars'].extend([dict(k=v) for k,v in incvars.iteritems()]) + + accumulated_plays.extend(plays) + play_basedirs.extend(basedirs) + + else: + + # this is a normal (non-included play) + accumulated_plays.append(play) + play_basedirs.append(basedir) + + return (accumulated_plays, play_basedirs) + + # ***************************************************** + + def run(self): + ''' run all patterns in the playbook ''' + plays = [] + matched_tags_all = set() + unmatched_tags_all = set() + + # loop through all patterns and run them + self.callbacks.on_start() + for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): + play = Play(self, play_ds, play_basedir) + assert play is not None + + matched_tags, unmatched_tags = play.compare_tags(self.only_tags) + matched_tags_all = matched_tags_all | matched_tags + unmatched_tags_all = unmatched_tags_all | unmatched_tags + + # if we have matched_tags, the play must be run. + # if the play contains no tasks, assume we just want to gather facts + # in this case there are actually 3 meta tasks (handler flushes) not 0 + # tasks, so that's why there's a check against 3 + if (len(matched_tags) > 0 or len(play.tasks()) == 3): + plays.append(play) + + # if the playbook is invoked with --tags that don't exist at all in the playbooks + # then we need to raise an error so that the user can correct the arguments. + unknown_tags = set(self.only_tags) - (matched_tags_all | unmatched_tags_all) + unknown_tags.discard('all') + + if len(unknown_tags) > 0: + unmatched_tags_all.discard('all') + msg = 'tag(s) not found in playbook: %s. possible values: %s' + unknown = ','.join(sorted(unknown_tags)) + unmatched = ','.join(sorted(unmatched_tags_all)) + raise errors.AnsibleError(msg % (unknown, unmatched)) + + for play in plays: + ansible.callbacks.set_play(self.callbacks, play) + ansible.callbacks.set_play(self.runner_callbacks, play) + if not self._run_play(play): + break + ansible.callbacks.set_play(self.callbacks, None) + ansible.callbacks.set_play(self.runner_callbacks, None) + + # summarize the results + results = {} + for host in self.stats.processed.keys(): + results[host] = self.stats.summarize(host) + return results + + # ***************************************************** + + def _async_poll(self, poller, async_seconds, async_poll_interval): + ''' launch an async job, if poll_interval is set, wait for completion ''' + + results = poller.wait(async_seconds, async_poll_interval) + + # mark any hosts that are still listed as started as failed + # since these likely got killed by async_wrapper + for host in poller.hosts_to_poll: + reason = { 'failed' : 1, 'rc' : None, 'msg' : 'timed out' } + self.runner_callbacks.on_failed(host, reason) + results['contacted'][host] = reason + + return results + + # ***************************************************** + + def _list_available_hosts(self, *args): + ''' returns a list of hosts that haven't failed and aren't dark ''' + + return [ h for h in self.inventory.list_hosts(*args) if (h not in self.stats.failures) and (h not in self.stats.dark)] + + # ***************************************************** + + def _run_task_internal(self, task): + ''' run a particular module step in a playbook ''' + + hosts = self._list_available_hosts() + self.inventory.restrict_to(hosts) + + runner = ansible.runner.Runner( + pattern=task.play.hosts, inventory=self.inventory, module_name=task.module_name, + module_args=task.module_args, forks=self.forks, + remote_pass=self.remote_pass, module_path=self.module_path, + timeout=self.timeout, remote_user=task.play.remote_user, + remote_port=task.play.remote_port, module_vars=task.module_vars, + private_key_file=self.private_key_file, + setup_cache=self.SETUP_CACHE, basedir=task.play.basedir, + conditional=task.only_if, callbacks=self.runner_callbacks, + sudo=task.sudo, sudo_user=task.sudo_user, + transport=task.transport, sudo_pass=task.sudo_pass, is_playbook=True, + check=self.check, diff=self.diff, environment=task.environment, complex_args=task.args + ) + + if task.async_seconds == 0: + results = runner.run() + else: + results, poller = runner.run_async(task.async_seconds) + self.stats.compute(results) + if task.async_poll_interval > 0: + # if not polling, playbook requested fire and forget, so don't poll + results = self._async_poll(poller, task.async_seconds, task.async_poll_interval) + + contacted = results.get('contacted',{}) + dark = results.get('dark', {}) + + self.inventory.lift_restriction() + + if len(contacted.keys()) == 0 and len(dark.keys()) == 0: + return None + + return results + + # ***************************************************** + + def _run_task(self, play, task, is_handler): + ''' run a single task in the playbook and recursively run any subtasks. ''' + + ansible.callbacks.set_task(self.callbacks, task) + ansible.callbacks.set_task(self.runner_callbacks, task) + + self.callbacks.on_task_start(template(play.basedir, task.name, task.module_vars, lookup_fatal=False), is_handler) + if hasattr(self.callbacks, 'skip_task') and self.callbacks.skip_task: + ansible.callbacks.set_task(self.callbacks, None) + ansible.callbacks.set_task(self.runner_callbacks, None) + return True + + # load up an appropriate ansible runner to run the task in parallel + results = self._run_task_internal(task) + + # if no hosts are matched, carry on + hosts_remaining = True + if results is None: + hosts_remaining = False + results = {} + + contacted = results.get('contacted', {}) + self.stats.compute(results, ignore_errors=task.ignore_errors) + + # add facts to the global setup cache + for host, result in contacted.iteritems(): + facts = result.get('ansible_facts', {}) + self.SETUP_CACHE[host].update(facts) + # extra vars need to always trump - so update again following the facts + self.SETUP_CACHE[host].update(self.extra_vars) + if task.register: + if 'stdout' in result: + result['stdout_lines'] = result['stdout'].splitlines() + self.SETUP_CACHE[host][task.register] = result + + # also have to register some failed, but ignored, tasks + if task.ignore_errors and task.register: + failed = results.get('failed', {}) + for host, result in failed.iteritems(): + if 'stdout' in result: + result['stdout_lines'] = result['stdout'].splitlines() + self.SETUP_CACHE[host][task.register] = result + + # flag which notify handlers need to be run + if len(task.notify) > 0: + for host, results in results.get('contacted',{}).iteritems(): + if results.get('changed', False): + for handler_name in task.notify: + self._flag_handler(play, template(play.basedir, handler_name, task.module_vars), host) + + ansible.callbacks.set_task(self.callbacks, None) + ansible.callbacks.set_task(self.runner_callbacks, None) + return hosts_remaining + + # ***************************************************** + + def _flag_handler(self, play, handler_name, host): + ''' + if a task has any notify elements, flag handlers for run + at end of execution cycle for hosts that have indicated + changes have been made + ''' + + found = False + for x in play.handlers(): + if handler_name == template(play.basedir, x.name, x.module_vars): + found = True + self.callbacks.on_notify(host, x.name) + x.notified_by.append(host) + if not found: + raise errors.AnsibleError("change handler (%s) is not defined" % handler_name) + + # ***************************************************** + + def _do_setup_step(self, play): + ''' get facts from the remote system ''' + + host_list = self._list_available_hosts(play.hosts) + + if play.gather_facts is False: + return {} + elif play.gather_facts is None: + host_list = [h for h in host_list if h not in self.SETUP_CACHE or 'module_setup' not in self.SETUP_CACHE[h]] + if len(host_list) == 0: + return {} + + self.callbacks.on_setup() + self.inventory.restrict_to(host_list) + + ansible.callbacks.set_task(self.callbacks, None) + ansible.callbacks.set_task(self.runner_callbacks, None) + + # push any variables down to the system + setup_results = ansible.runner.Runner( + pattern=play.hosts, module_name='setup', module_args={}, inventory=self.inventory, + forks=self.forks, module_path=self.module_path, timeout=self.timeout, remote_user=play.remote_user, + remote_pass=self.remote_pass, remote_port=play.remote_port, private_key_file=self.private_key_file, + setup_cache=self.SETUP_CACHE, callbacks=self.runner_callbacks, sudo=play.sudo, sudo_user=play.sudo_user, + transport=play.transport, sudo_pass=self.sudo_pass, is_playbook=True, module_vars=play.vars, + check=self.check, diff=self.diff + ).run() + self.stats.compute(setup_results, setup=True) + + self.inventory.lift_restriction() + + # now for each result, load into the setup cache so we can + # let runner template out future commands + setup_ok = setup_results.get('contacted', {}) + for (host, result) in setup_ok.iteritems(): + self.SETUP_CACHE[host].update({'module_setup': True}) + self.SETUP_CACHE[host].update(result.get('ansible_facts', {})) + return setup_results + + # ***************************************************** + + + def generate_retry_inventory(self, replay_hosts): + ''' + called by /usr/bin/ansible when a playbook run fails. It generates a inventory + that allows re-running on ONLY the failed hosts. This may duplicate some + variable information in group_vars/host_vars but that is ok, and expected. + ''' + + buf = StringIO.StringIO() + for x in replay_hosts: + buf.write("%s\n" % x) + basedir = self.inventory.basedir() + filename = "%s.retry" % os.path.basename(self.filename) + filename = filename.replace(".yml","") + filename = os.path.join(os.path.expandvars('$HOME/'), filename) + + try: + fd = open(filename, 'w') + fd.write(buf.getvalue()) + fd.close() + return filename + except: + pass + return None + + # ***************************************************** + + def _run_play(self, play): + ''' run a list of tasks for a given pattern, in order ''' + + self.callbacks.on_play_start(play.name) + # if no hosts matches this play, drop out + if not self.inventory.list_hosts(play.hosts): + self.callbacks.on_no_hosts_matched() + return True + + # get facts from system + self._do_setup_step(play) + + # now with that data, handle contentional variable file imports! + + all_hosts = self._list_available_hosts(play.hosts) + play.update_vars_files(all_hosts) + + serialized_batch = [] + if play.serial <= 0: + serialized_batch = [all_hosts] + else: + # do N forks all the way through before moving to next + while len(all_hosts) > 0: + play_hosts = [] + for x in range(play.serial): + if len(all_hosts) > 0: + play_hosts.append(all_hosts.pop()) + serialized_batch.append(play_hosts) + + for on_hosts in serialized_batch: + + self.inventory.also_restrict_to(on_hosts) + + for task in play.tasks(): + + if task.meta is not None: + + # meta tasks are an internalism and are not valid for end-user playbook usage + # here a meta task is a placeholder that signals handlers should be run + + if task.meta == 'flush_handlers': + for handler in play.handlers(): + if len(handler.notified_by) > 0: + self.inventory.restrict_to(handler.notified_by) + self._run_task(play, handler, True) + self.inventory.lift_restriction() + new_list = handler.notified_by[:] + for host in handler.notified_by: + if host in on_hosts: + while host in new_list: + new_list.remove(host) + handler.notified_by = new_list + + continue + + hosts_count = len(self._list_available_hosts(play.hosts)) + + # only run the task if the requested tags match + should_run = False + for x in self.only_tags: + + for y in task.tags: + if (x==y): + should_run = True + break + + if should_run: + if not self._run_task(play, task, False): + # whether no hosts matched is fatal or not depends if it was on the initial step. + # if we got exactly no hosts on the first step (setup!) then the host group + # just didn't match anything and that's ok + return False + + host_list = self._list_available_hosts(play.hosts) + + if task.any_errors_fatal and len(host_list) < hosts_count: + host_list = None + + # if no hosts remain, drop out + if not host_list: + self.callbacks.on_no_hosts_remaining() + return False + + # run notify actions + #for handler in play.handlers(): + # if len(handler.notified_by) > 0: + # self.inventory.restrict_to(handler.notified_by) + # self._run_task(play, handler, True) + # self.inventory.lift_restriction() + # handler.notified_by = [] + # handler.notified_by = [] + + self.inventory.lift_also_restriction() + + return True +``` + +## `lib/ansible/playbook/__init__.py` — `function:PlayBook.generate_retry_inventory` (lines 437-459) + +```python + def generate_retry_inventory(self, replay_hosts): + ''' + called by /usr/bin/ansible when a playbook run fails. It generates a inventory + that allows re-running on ONLY the failed hosts. This may duplicate some + variable information in group_vars/host_vars but that is ok, and expected. + ''' + + buf = StringIO.StringIO() + for x in replay_hosts: + buf.write("%s\n" % x) + basedir = self.inventory.basedir() + filename = "%s.retry" % os.path.basename(self.filename) + filename = filename.replace(".yml","") + filename = os.path.join(os.path.expandvars('$HOME/'), filename) + + try: + fd = open(filename, 'w') + fd.write(buf.getvalue()) + fd.close() + return filename + except: + pass + return None +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..38963d8d6fb4a4362c440655db03b13b4a795463 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/pre_context.md @@ -0,0 +1,570 @@ +# Patch-overlapping Python context before the fix + +## `lib/ansible/playbook/__init__.py` — `class:PlayBook` (lines 34-563) + +```python +class PlayBook(object): + ''' + runs an ansible playbook, given as a datastructure or YAML filename. + A playbook is a deployment, config management, or automation based + set of commands to run in series. + + multiple plays/tasks do not execute simultaneously, but tasks in each + pattern do execute in parallel (according to the number of forks + requested) among the hosts they address + ''' + + # ***************************************************** + + def __init__(self, + playbook = None, + host_list = C.DEFAULT_HOST_LIST, + module_path = None, + forks = C.DEFAULT_FORKS, + timeout = C.DEFAULT_TIMEOUT, + remote_user = C.DEFAULT_REMOTE_USER, + remote_pass = C.DEFAULT_REMOTE_PASS, + sudo_pass = C.DEFAULT_SUDO_PASS, + remote_port = None, + transport = C.DEFAULT_TRANSPORT, + private_key_file = C.DEFAULT_PRIVATE_KEY_FILE, + callbacks = None, + runner_callbacks = None, + stats = None, + sudo = False, + sudo_user = C.DEFAULT_SUDO_USER, + extra_vars = None, + only_tags = None, + subset = C.DEFAULT_SUBSET, + inventory = None, + check = False, + diff = False, + any_errors_fatal = False): + + """ + playbook: path to a playbook file + host_list: path to a file like /etc/ansible/hosts + module_path: path to ansible modules, like /usr/share/ansible/ + forks: desired level of paralellism + timeout: connection timeout + remote_user: run as this user if not specified in a particular play + remote_pass: use this remote password (for all plays) vs using SSH keys + sudo_pass: if sudo==True, and a password is required, this is the sudo password + remote_port: default remote port to use if not specified with the host or play + transport: how to connect to hosts that don't specify a transport (local, paramiko, etc) + callbacks output callbacks for the playbook + runner_callbacks: more callbacks, this time for the runner API + stats: holds aggregrate data about events occuring to each host + sudo: if not specified per play, requests all plays use sudo mode + inventory: can be specified instead of host_list to use a pre-existing inventory object + check: don't change anything, just try to detect some potential changes + """ + + self.SETUP_CACHE = SETUP_CACHE + + if playbook is None or callbacks is None or runner_callbacks is None or stats is None: + raise Exception('missing required arguments') + + if extra_vars is None: + extra_vars = {} + if only_tags is None: + only_tags = [ 'all' ] + + self.check = check + self.diff = diff + self.module_path = module_path + self.forks = forks + self.timeout = timeout + self.remote_user = remote_user + self.remote_pass = remote_pass + self.remote_port = remote_port + self.transport = transport + self.callbacks = callbacks + self.runner_callbacks = runner_callbacks + self.stats = stats + self.sudo = sudo + self.sudo_pass = sudo_pass + self.sudo_user = sudo_user + self.extra_vars = extra_vars + self.global_vars = {} + self.private_key_file = private_key_file + self.only_tags = only_tags + self.any_errors_fatal = any_errors_fatal + + self.callbacks.playbook = self + self.runner_callbacks.playbook = self + + if inventory is None: + self.inventory = ansible.inventory.Inventory(host_list) + self.inventory.subset(subset) + else: + self.inventory = inventory + + self.basedir = os.path.dirname(playbook) or '.' + vars = {} + if self.inventory.basedir() is not None: + vars['inventory_dir'] = self.inventory.basedir() + self.filename = playbook + (self.playbook, self.play_basedirs) = self._load_playbook_from_file(playbook, vars) + + # ***************************************************** + + def _load_playbook_from_file(self, path, vars={}): + ''' + run top level error checking on playbooks and allow them to include other playbooks. + ''' + + playbook_data = utils.parse_yaml_from_file(path) + accumulated_plays = [] + play_basedirs = [] + + if type(playbook_data) != list: + raise errors.AnsibleError("parse error: playbooks must be formatted as a YAML list") + + basedir = os.path.dirname(path) or '.' + utils.plugins.push_basedir(basedir) + for play in playbook_data: + if type(play) != dict: + raise errors.AnsibleError("parse error: each play in a playbook must be a YAML dictionary (hash), recieved: %s" % play) + + if 'include' in play: + # a playbook (list of plays) decided to include some other list of plays + # from another file. The result is a flat list of plays in the end. + + tokens = shlex.split(play['include']) + + incvars = vars.copy() + if 'vars' in play: + if isinstance(play['vars'], dict): + incvars.update(play['vars']) + elif isinstance(play['vars'], list): + for v in play['vars']: + incvars.update(v) + + # allow key=value parameters to be specified on the include line + # to set variables + + for t in tokens[1:]: + + (k,v) = t.split("=", 1) + incvars[k] = template(basedir, v, incvars) + + included_path = utils.path_dwim(basedir, template(basedir, tokens[0], incvars)) + (plays, basedirs) = self._load_playbook_from_file(included_path, incvars) + for p in plays: + # support for parameterized play includes works by passing + # those variables along to the subservient play + if 'vars' not in p: + p['vars'] = {} + if isinstance(p['vars'], dict): + p['vars'].update(incvars) + elif isinstance(p['vars'], list): + # nobody should really do this, but handle vars: a=1 b=2 + p['vars'].extend([dict(k=v) for k,v in incvars.iteritems()]) + + accumulated_plays.extend(plays) + play_basedirs.extend(basedirs) + + else: + + # this is a normal (non-included play) + accumulated_plays.append(play) + play_basedirs.append(basedir) + + return (accumulated_plays, play_basedirs) + + # ***************************************************** + + def run(self): + ''' run all patterns in the playbook ''' + plays = [] + matched_tags_all = set() + unmatched_tags_all = set() + + # loop through all patterns and run them + self.callbacks.on_start() + for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): + play = Play(self, play_ds, play_basedir) + assert play is not None + + matched_tags, unmatched_tags = play.compare_tags(self.only_tags) + matched_tags_all = matched_tags_all | matched_tags + unmatched_tags_all = unmatched_tags_all | unmatched_tags + + # if we have matched_tags, the play must be run. + # if the play contains no tasks, assume we just want to gather facts + # in this case there are actually 3 meta tasks (handler flushes) not 0 + # tasks, so that's why there's a check against 3 + if (len(matched_tags) > 0 or len(play.tasks()) == 3): + plays.append(play) + + # if the playbook is invoked with --tags that don't exist at all in the playbooks + # then we need to raise an error so that the user can correct the arguments. + unknown_tags = set(self.only_tags) - (matched_tags_all | unmatched_tags_all) + unknown_tags.discard('all') + + if len(unknown_tags) > 0: + unmatched_tags_all.discard('all') + msg = 'tag(s) not found in playbook: %s. possible values: %s' + unknown = ','.join(sorted(unknown_tags)) + unmatched = ','.join(sorted(unmatched_tags_all)) + raise errors.AnsibleError(msg % (unknown, unmatched)) + + for play in plays: + ansible.callbacks.set_play(self.callbacks, play) + ansible.callbacks.set_play(self.runner_callbacks, play) + if not self._run_play(play): + break + ansible.callbacks.set_play(self.callbacks, None) + ansible.callbacks.set_play(self.runner_callbacks, None) + + # summarize the results + results = {} + for host in self.stats.processed.keys(): + results[host] = self.stats.summarize(host) + return results + + # ***************************************************** + + def _async_poll(self, poller, async_seconds, async_poll_interval): + ''' launch an async job, if poll_interval is set, wait for completion ''' + + results = poller.wait(async_seconds, async_poll_interval) + + # mark any hosts that are still listed as started as failed + # since these likely got killed by async_wrapper + for host in poller.hosts_to_poll: + reason = { 'failed' : 1, 'rc' : None, 'msg' : 'timed out' } + self.runner_callbacks.on_failed(host, reason) + results['contacted'][host] = reason + + return results + + # ***************************************************** + + def _list_available_hosts(self, *args): + ''' returns a list of hosts that haven't failed and aren't dark ''' + + return [ h for h in self.inventory.list_hosts(*args) if (h not in self.stats.failures) and (h not in self.stats.dark)] + + # ***************************************************** + + def _run_task_internal(self, task): + ''' run a particular module step in a playbook ''' + + hosts = self._list_available_hosts() + self.inventory.restrict_to(hosts) + + runner = ansible.runner.Runner( + pattern=task.play.hosts, inventory=self.inventory, module_name=task.module_name, + module_args=task.module_args, forks=self.forks, + remote_pass=self.remote_pass, module_path=self.module_path, + timeout=self.timeout, remote_user=task.play.remote_user, + remote_port=task.play.remote_port, module_vars=task.module_vars, + private_key_file=self.private_key_file, + setup_cache=self.SETUP_CACHE, basedir=task.play.basedir, + conditional=task.only_if, callbacks=self.runner_callbacks, + sudo=task.sudo, sudo_user=task.sudo_user, + transport=task.transport, sudo_pass=task.sudo_pass, is_playbook=True, + check=self.check, diff=self.diff, environment=task.environment, complex_args=task.args + ) + + if task.async_seconds == 0: + results = runner.run() + else: + results, poller = runner.run_async(task.async_seconds) + self.stats.compute(results) + if task.async_poll_interval > 0: + # if not polling, playbook requested fire and forget, so don't poll + results = self._async_poll(poller, task.async_seconds, task.async_poll_interval) + + contacted = results.get('contacted',{}) + dark = results.get('dark', {}) + + self.inventory.lift_restriction() + + if len(contacted.keys()) == 0 and len(dark.keys()) == 0: + return None + + return results + + # ***************************************************** + + def _run_task(self, play, task, is_handler): + ''' run a single task in the playbook and recursively run any subtasks. ''' + + ansible.callbacks.set_task(self.callbacks, task) + ansible.callbacks.set_task(self.runner_callbacks, task) + + self.callbacks.on_task_start(template(play.basedir, task.name, task.module_vars, lookup_fatal=False), is_handler) + if hasattr(self.callbacks, 'skip_task') and self.callbacks.skip_task: + ansible.callbacks.set_task(self.callbacks, None) + ansible.callbacks.set_task(self.runner_callbacks, None) + return True + + # load up an appropriate ansible runner to run the task in parallel + results = self._run_task_internal(task) + + # if no hosts are matched, carry on + hosts_remaining = True + if results is None: + hosts_remaining = False + results = {} + + contacted = results.get('contacted', {}) + self.stats.compute(results, ignore_errors=task.ignore_errors) + + # add facts to the global setup cache + for host, result in contacted.iteritems(): + facts = result.get('ansible_facts', {}) + self.SETUP_CACHE[host].update(facts) + # extra vars need to always trump - so update again following the facts + self.SETUP_CACHE[host].update(self.extra_vars) + if task.register: + if 'stdout' in result: + result['stdout_lines'] = result['stdout'].splitlines() + self.SETUP_CACHE[host][task.register] = result + + # also have to register some failed, but ignored, tasks + if task.ignore_errors and task.register: + failed = results.get('failed', {}) + for host, result in failed.iteritems(): + if 'stdout' in result: + result['stdout_lines'] = result['stdout'].splitlines() + self.SETUP_CACHE[host][task.register] = result + + # flag which notify handlers need to be run + if len(task.notify) > 0: + for host, results in results.get('contacted',{}).iteritems(): + if results.get('changed', False): + for handler_name in task.notify: + self._flag_handler(play, template(play.basedir, handler_name, task.module_vars), host) + + ansible.callbacks.set_task(self.callbacks, None) + ansible.callbacks.set_task(self.runner_callbacks, None) + return hosts_remaining + + # ***************************************************** + + def _flag_handler(self, play, handler_name, host): + ''' + if a task has any notify elements, flag handlers for run + at end of execution cycle for hosts that have indicated + changes have been made + ''' + + found = False + for x in play.handlers(): + if handler_name == template(play.basedir, x.name, x.module_vars): + found = True + self.callbacks.on_notify(host, x.name) + x.notified_by.append(host) + if not found: + raise errors.AnsibleError("change handler (%s) is not defined" % handler_name) + + # ***************************************************** + + def _do_setup_step(self, play): + ''' get facts from the remote system ''' + + host_list = self._list_available_hosts(play.hosts) + + if play.gather_facts is False: + return {} + elif play.gather_facts is None: + host_list = [h for h in host_list if h not in self.SETUP_CACHE or 'module_setup' not in self.SETUP_CACHE[h]] + if len(host_list) == 0: + return {} + + self.callbacks.on_setup() + self.inventory.restrict_to(host_list) + + ansible.callbacks.set_task(self.callbacks, None) + ansible.callbacks.set_task(self.runner_callbacks, None) + + # push any variables down to the system + setup_results = ansible.runner.Runner( + pattern=play.hosts, module_name='setup', module_args={}, inventory=self.inventory, + forks=self.forks, module_path=self.module_path, timeout=self.timeout, remote_user=play.remote_user, + remote_pass=self.remote_pass, remote_port=play.remote_port, private_key_file=self.private_key_file, + setup_cache=self.SETUP_CACHE, callbacks=self.runner_callbacks, sudo=play.sudo, sudo_user=play.sudo_user, + transport=play.transport, sudo_pass=self.sudo_pass, is_playbook=True, module_vars=play.vars, + check=self.check, diff=self.diff + ).run() + self.stats.compute(setup_results, setup=True) + + self.inventory.lift_restriction() + + # now for each result, load into the setup cache so we can + # let runner template out future commands + setup_ok = setup_results.get('contacted', {}) + for (host, result) in setup_ok.iteritems(): + self.SETUP_CACHE[host].update({'module_setup': True}) + self.SETUP_CACHE[host].update(result.get('ansible_facts', {})) + return setup_results + + # ***************************************************** + + + def generate_retry_inventory(self, replay_hosts): + ''' + called by /usr/bin/ansible when a playbook run fails. It generates a inventory + that allows re-running on ONLY the failed hosts. This may duplicate some + variable information in group_vars/host_vars but that is ok, and expected. + ''' + + buf = StringIO.StringIO() + for x in replay_hosts: + buf.write("%s\n" % x) + basedir = self.inventory.basedir() + filename = "%s.retry" % os.path.basename(self.filename) + filename = filename.replace(".yml","") + + if not os.path.exists('/var/tmp/ansible'): + try: + os.makedirs('/var/tmp/ansible') + except: + pass + filename = os.path.join('/var/tmp/ansible', filename) + + try: + fd = open(filename, 'w') + fd.write(buf.getvalue()) + fd.close() + return filename + except: + pass + return None + + # ***************************************************** + + def _run_play(self, play): + ''' run a list of tasks for a given pattern, in order ''' + + self.callbacks.on_play_start(play.name) + # if no hosts matches this play, drop out + if not self.inventory.list_hosts(play.hosts): + self.callbacks.on_no_hosts_matched() + return True + + # get facts from system + self._do_setup_step(play) + + # now with that data, handle contentional variable file imports! + + all_hosts = self._list_available_hosts(play.hosts) + play.update_vars_files(all_hosts) + + serialized_batch = [] + if play.serial <= 0: + serialized_batch = [all_hosts] + else: + # do N forks all the way through before moving to next + while len(all_hosts) > 0: + play_hosts = [] + for x in range(play.serial): + if len(all_hosts) > 0: + play_hosts.append(all_hosts.pop()) + serialized_batch.append(play_hosts) + + for on_hosts in serialized_batch: + + self.inventory.also_restrict_to(on_hosts) + + for task in play.tasks(): + + if task.meta is not None: + + # meta tasks are an internalism and are not valid for end-user playbook usage + # here a meta task is a placeholder that signals handlers should be run + + if task.meta == 'flush_handlers': + for handler in play.handlers(): + if len(handler.notified_by) > 0: + self.inventory.restrict_to(handler.notified_by) + self._run_task(play, handler, True) + self.inventory.lift_restriction() + new_list = handler.notified_by[:] + for host in handler.notified_by: + if host in on_hosts: + while host in new_list: + new_list.remove(host) + handler.notified_by = new_list + + continue + + hosts_count = len(self._list_available_hosts(play.hosts)) + + # only run the task if the requested tags match + should_run = False + for x in self.only_tags: + + for y in task.tags: + if (x==y): + should_run = True + break + + if should_run: + if not self._run_task(play, task, False): + # whether no hosts matched is fatal or not depends if it was on the initial step. + # if we got exactly no hosts on the first step (setup!) then the host group + # just didn't match anything and that's ok + return False + + host_list = self._list_available_hosts(play.hosts) + + if task.any_errors_fatal and len(host_list) < hosts_count: + host_list = None + + # if no hosts remain, drop out + if not host_list: + self.callbacks.on_no_hosts_remaining() + return False + + # run notify actions + #for handler in play.handlers(): + # if len(handler.notified_by) > 0: + # self.inventory.restrict_to(handler.notified_by) + # self._run_task(play, handler, True) + # self.inventory.lift_restriction() + # handler.notified_by = [] + # handler.notified_by = [] + + self.inventory.lift_also_restriction() + + return True +``` + +## `lib/ansible/playbook/__init__.py` — `function:PlayBook.generate_retry_inventory` (lines 437-465) + +```python + def generate_retry_inventory(self, replay_hosts): + ''' + called by /usr/bin/ansible when a playbook run fails. It generates a inventory + that allows re-running on ONLY the failed hosts. This may duplicate some + variable information in group_vars/host_vars but that is ok, and expected. + ''' + + buf = StringIO.StringIO() + for x in replay_hosts: + buf.write("%s\n" % x) + basedir = self.inventory.basedir() + filename = "%s.retry" % os.path.basename(self.filename) + filename = filename.replace(".yml","") + + if not os.path.exists('/var/tmp/ansible'): + try: + os.makedirs('/var/tmp/ansible') + except: + pass + filename = os.path.join('/var/tmp/ansible', filename) + + try: + fd = open(filename, 'w') + fd.write(buf.getvalue()) + fd.close() + return filename + except: + pass + return None +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/task.json new file mode 100644 index 0000000000000000000000000000000000000000..90a55c66bdc7d3a981e967f9fc238b7e8cf6c525 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-8297e406660c92268ba5", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-8297e406660c92268ba5", + "project_id": "pyvul__ansible__ansible", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "lib/ansible/playbook/__init__.py" + ], + "patch_units": { + "before": [ + "class:PlayBook", + "function:PlayBook.generate_retry_inventory" + ], + "after": [ + "class:PlayBook", + "function:PlayBook.generate_retry_inventory" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/8835f0be96caf32557cbd8b197d1de683ee844fc5c212541e104e56fd57e97dc/database", + "cache_key": "8835f0be96caf32557cbd8b197d1de683ee844fc5c212541e104e56fd57e97dc", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/198ce26be62a9436b8c93c4cdb0709eb344b0bbf7df38bb5b2efaa75d0630f62/database", + "cache_key": "198ce26be62a9436b8c93c4cdb0709eb344b0bbf7df38bb5b2efaa75d0630f62", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/0036cb822aa8ee3f626108ddc4ec6c098537ac1d2b9ab726b5f447bab9d79275/database", + "cache_key": "0036cb822aa8ee3f626108ddc4ec6c098537ac1d2b9ab726b5f447bab9d79275", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-8297e406660c92268ba5/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-8297e406660c92268ba5/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8297e406660c92268ba5/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3414a57d5a08d1d7818bac03faf6f2d93ad8e899 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/patch.diff @@ -0,0 +1,38 @@ +diff --git a/mangadex_downloader/cli/validator.py b/mangadex_downloader/cli/validator.py +index dd3f636..deb4f81 100644 +--- a/mangadex_downloader/cli/validator.py ++++ b/mangadex_downloader/cli/validator.py +@@ -31,15 +31,16 @@ def _validate(url): + raise argparse.ArgumentTypeError(str(e)) + return _url + +-def validate_url(url): +- if os.path.exists(url): +- with open(url, 'r') as opener: +- content = opener.read() +- else: +- content = url ++def _try_read(path): ++ if not os.path.exists(path): ++ return None ++ ++ with open(path, 'r') as o: ++ return o.read() + ++def validate_url(url): + urls = [] +- for _url in content.splitlines(): ++ for _url in url.splitlines(): + if not _url: + continue + +@@ -245,7 +246,8 @@ def validate(parser, args): + elif not os.path.exists(file_path): + parser.error(f"File \"{file_path}\" is not exist") + else: +- file_path = urls ++ file_content = _try_read(urls) ++ file_path = file_content if file_content is not None else urls + try: + args.URL = validate_url(file_path) + except argparse.ArgumentTypeError as e: diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..80d0cc6ab5e263d6adc98e010757a65cacca9a5c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/post_context.md @@ -0,0 +1,237 @@ +# Patch-overlapping Python context after the fix + +## `mangadex_downloader/cli/validator.py` — `function:_try_read` (lines 34-39) + +```python +def _try_read(path): + if not os.path.exists(path): + return None + + with open(path, 'r') as o: + return o.read() +``` + +## `mangadex_downloader/cli/validator.py` — `function:validate_url` (lines 41-49) + +```python +def validate_url(url): + urls = [] + for _url in url.splitlines(): + if not _url: + continue + + urls.append((_validate(_url), _url)) + + return urls +``` + +## `mangadex_downloader/cli/validator.py` — `function:validate` (lines 200-405) + +```python +def validate(parser, args): + urls = args.URL + + if ( + not args.search and + not args.fetch_library_manga and + not args.fetch_library_list and + not args.fetch_library_follows_list and + not args.random and + not args.fetch_group + ): + # Parsing file path + if args.file: + result = urls.split(':') + file = result[1:] + file_path = "" + err_file = False + + try: + file_path += file.pop(0) + except IndexError: + err_file = True + + if not file_path: + err_file = True + + if err_file: + parser.error("Syntax error: file path argument is empty") + + # Because ":" was removed during .split() + # add it again + for f in file: + file_path += ':' + f + + # web URL location support for "file:{location}" syntax + if file_path.startswith('http://') or file_path.startswith('https://'): + r = Net.requests.get(file_path) + try: + r.raise_for_status() + except requests.HTTPError: + raise MangaDexException(f"Failed to connect '{file_path}', status code = {r.status_code}") + + file_path = r.text + + # Because this is specified syntax for batch downloading + # If file doesn't exist, raise error + elif not os.path.exists(file_path): + parser.error(f"File \"{file_path}\" is not exist") + else: + file_content = _try_read(urls) + file_path = file_content if file_content is not None else urls + try: + args.URL = validate_url(file_path) + except argparse.ArgumentTypeError as e: + parser.error(str(e)) + return + + kwargs = { + 'parser': parser + } + + limit_items = None + if args.random: + def iter_random_manga(): + ids = [] + while True: + _, raw_cr = get_key_value(urls, sep=":") + content_ratings = split_comma_separated(raw_cr, single_value_to_list=True) + if not content_ratings[0]: + # Fallback to default values + content_ratings = [i.value for i in ContentRating] + else: + # Verify it + try: + content_ratings = [ContentRating(i).value for i in content_ratings] + except ValueError as e: + raise MangaDexException(e) + + params = { + 'includes[]': ['author', 'artist', 'cover_art'], + "contentRating[]": content_ratings + } + r = Net.mangadex.get(f'{base_url}/manga/random', params=params) + data = r.json()['data'] + manga = Manga(data=data) + + if manga.id not in ids: + # Make sure it's not duplicated manga + ids.append(manga.id) + yield manga + + continue + + iterator = iter_random_manga() + text = f"Found random manga" + on_empty_err = f"Unknown Error" # This should never happened + on_preview = preview_cover_manga + limit_items = 5 + elif args.fetch_group: + # Getting group id + _, group_id = get_key_value(urls, sep=':') + if not group_id: + parser.error("group id or url are required") + + group_id = __validate(group_id) + group = Group(group_id) + + iterator = search(None, args.unsafe, group=group.id) + text = f'List manga from group "{group.name}"' + on_empty_err = f'Group "{group.name}" has no uploaded mangas' + on_preview = preview_cover_manga + elif args.search: + filter_kwargs = {} + filters = args.search_filter or [] + for f in filters: + key, value = get_key_value(f) + try: + value_filter_kwargs = filter_kwargs[key] + except KeyError: + filter_kwargs[key] = split_comma_separated(value) + else: + # Found duplicate filter with different value + if isinstance(value_filter_kwargs, str): + new_values = [value_filter_kwargs] + else: + new_values = value_filter_kwargs + + values = split_comma_separated(value, single_value_to_list=True) + new_values.extend(values) + + filter_kwargs[key] = new_values + + iterator = search(urls, args.unsafe, **filter_kwargs) + text = f"Search results for \"{urls}\"" + on_empty_err = f"Search results \"{urls}\" are empty" + on_preview = preview_cover_manga + elif args.fetch_library_manga: + result = urls.split(':') + + # Try to get filter status + try: + status = result[1] + except IndexError: + status = None + + try: + iterator = get_manga_from_user_library(status, args.unsafe) + except MangaDexException as e: + parser.error(str(e)) + + user = Net.mangadex.user + text = f"Manga library from user \"{user.name}\"" + on_empty_err = f"User \"{user.name}\" has no saved mangas" + on_preview = preview_cover_manga + elif args.fetch_library_list: + # Try to get user (if available) + _, user = get_key_value(urls, sep=':') + + user_id = None + if user: + try: + user_id = __validate(user) + except InvalidURL as e: + parser.error(f"\"{user}\" is not a valid user") + + try: + if user: + iterator = get_list_from_user(user_id) + else: + iterator = get_list_from_user_library() + except MangaDexException as e: + parser.error(str(e)) + + try: + user = iterator.user + except AttributeError: + # Logged in user + user = Net.mangadex.user + + text = f"MangaDex List library from user \"{user.name}\"" + on_empty_err = f"User \"{user.name}\" has no saved lists" + on_preview = lambda x: preview_list(args, x) + elif args.fetch_library_follows_list: + try: + iterator = get_followed_list_from_user_library() + except MangaDexException as e: + parser.error(str(e)) + + user = Net.mangadex.user + text = f"MangaDex followed List from user \"{user.name}\"" + on_empty_err = f"User \"{user.name}\" has no followed lists" + on_preview = lambda x: preview_list(args, x) + + kwargs.update({ + 'iterator': iterator, + 'text': text, + 'on_empty_err': on_empty_err, + 'on_preview': on_preview + }) + + if limit_items: + kwargs.update(limit=limit_items) + + result = _create_prompt_choices(**kwargs) + + args.URL = validate_url(result.id) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..ba38a508797cba1f69380b3d59dd864245f486ef --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/pre_context.md @@ -0,0 +1,231 @@ +# Patch-overlapping Python context before the fix + +## `mangadex_downloader/cli/validator.py` — `function:validate_url` (lines 34-48) + +```python +def validate_url(url): + if os.path.exists(url): + with open(url, 'r') as opener: + content = opener.read() + else: + content = url + + urls = [] + for _url in content.splitlines(): + if not _url: + continue + + urls.append((_validate(_url), _url)) + + return urls +``` + +## `mangadex_downloader/cli/validator.py` — `function:validate` (lines 199-403) + +```python +def validate(parser, args): + urls = args.URL + + if ( + not args.search and + not args.fetch_library_manga and + not args.fetch_library_list and + not args.fetch_library_follows_list and + not args.random and + not args.fetch_group + ): + # Parsing file path + if args.file: + result = urls.split(':') + file = result[1:] + file_path = "" + err_file = False + + try: + file_path += file.pop(0) + except IndexError: + err_file = True + + if not file_path: + err_file = True + + if err_file: + parser.error("Syntax error: file path argument is empty") + + # Because ":" was removed during .split() + # add it again + for f in file: + file_path += ':' + f + + # web URL location support for "file:{location}" syntax + if file_path.startswith('http://') or file_path.startswith('https://'): + r = Net.requests.get(file_path) + try: + r.raise_for_status() + except requests.HTTPError: + raise MangaDexException(f"Failed to connect '{file_path}', status code = {r.status_code}") + + file_path = r.text + + # Because this is specified syntax for batch downloading + # If file doesn't exist, raise error + elif not os.path.exists(file_path): + parser.error(f"File \"{file_path}\" is not exist") + else: + file_path = urls + try: + args.URL = validate_url(file_path) + except argparse.ArgumentTypeError as e: + parser.error(str(e)) + return + + kwargs = { + 'parser': parser + } + + limit_items = None + if args.random: + def iter_random_manga(): + ids = [] + while True: + _, raw_cr = get_key_value(urls, sep=":") + content_ratings = split_comma_separated(raw_cr, single_value_to_list=True) + if not content_ratings[0]: + # Fallback to default values + content_ratings = [i.value for i in ContentRating] + else: + # Verify it + try: + content_ratings = [ContentRating(i).value for i in content_ratings] + except ValueError as e: + raise MangaDexException(e) + + params = { + 'includes[]': ['author', 'artist', 'cover_art'], + "contentRating[]": content_ratings + } + r = Net.mangadex.get(f'{base_url}/manga/random', params=params) + data = r.json()['data'] + manga = Manga(data=data) + + if manga.id not in ids: + # Make sure it's not duplicated manga + ids.append(manga.id) + yield manga + + continue + + iterator = iter_random_manga() + text = f"Found random manga" + on_empty_err = f"Unknown Error" # This should never happened + on_preview = preview_cover_manga + limit_items = 5 + elif args.fetch_group: + # Getting group id + _, group_id = get_key_value(urls, sep=':') + if not group_id: + parser.error("group id or url are required") + + group_id = __validate(group_id) + group = Group(group_id) + + iterator = search(None, args.unsafe, group=group.id) + text = f'List manga from group "{group.name}"' + on_empty_err = f'Group "{group.name}" has no uploaded mangas' + on_preview = preview_cover_manga + elif args.search: + filter_kwargs = {} + filters = args.search_filter or [] + for f in filters: + key, value = get_key_value(f) + try: + value_filter_kwargs = filter_kwargs[key] + except KeyError: + filter_kwargs[key] = split_comma_separated(value) + else: + # Found duplicate filter with different value + if isinstance(value_filter_kwargs, str): + new_values = [value_filter_kwargs] + else: + new_values = value_filter_kwargs + + values = split_comma_separated(value, single_value_to_list=True) + new_values.extend(values) + + filter_kwargs[key] = new_values + + iterator = search(urls, args.unsafe, **filter_kwargs) + text = f"Search results for \"{urls}\"" + on_empty_err = f"Search results \"{urls}\" are empty" + on_preview = preview_cover_manga + elif args.fetch_library_manga: + result = urls.split(':') + + # Try to get filter status + try: + status = result[1] + except IndexError: + status = None + + try: + iterator = get_manga_from_user_library(status, args.unsafe) + except MangaDexException as e: + parser.error(str(e)) + + user = Net.mangadex.user + text = f"Manga library from user \"{user.name}\"" + on_empty_err = f"User \"{user.name}\" has no saved mangas" + on_preview = preview_cover_manga + elif args.fetch_library_list: + # Try to get user (if available) + _, user = get_key_value(urls, sep=':') + + user_id = None + if user: + try: + user_id = __validate(user) + except InvalidURL as e: + parser.error(f"\"{user}\" is not a valid user") + + try: + if user: + iterator = get_list_from_user(user_id) + else: + iterator = get_list_from_user_library() + except MangaDexException as e: + parser.error(str(e)) + + try: + user = iterator.user + except AttributeError: + # Logged in user + user = Net.mangadex.user + + text = f"MangaDex List library from user \"{user.name}\"" + on_empty_err = f"User \"{user.name}\" has no saved lists" + on_preview = lambda x: preview_list(args, x) + elif args.fetch_library_follows_list: + try: + iterator = get_followed_list_from_user_library() + except MangaDexException as e: + parser.error(str(e)) + + user = Net.mangadex.user + text = f"MangaDex followed List from user \"{user.name}\"" + on_empty_err = f"User \"{user.name}\" has no followed lists" + on_preview = lambda x: preview_list(args, x) + + kwargs.update({ + 'iterator': iterator, + 'text': text, + 'on_empty_err': on_empty_err, + 'on_preview': on_preview + }) + + if limit_items: + kwargs.update(limit=limit_items) + + result = _create_prompt_choices(**kwargs) + + args.URL = validate_url(result.id) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/task.json new file mode 100644 index 0000000000000000000000000000000000000000..703f9193d831a32212b081a286a1c46feba5ffb2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/task.json @@ -0,0 +1,47 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-89a9ff0f9cf4f2f4cc91", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-89a9ff0f9cf4f2f4cc91", + "project_id": "pyvul__mansuf__mangadex-downloader", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "mangadex_downloader/cli/validator.py" + ], + "patch_units": { + "before": [ + "function:validate_url", + "function:validate" + ], + "after": [ + "function:_try_read", + "function:validate_url", + "function:validate" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/23d707c0bd3bf71758a5f368228f179b47efb72e4c3965ad8014ad75f68d5ce9/database", + "cache_key": "23d707c0bd3bf71758a5f368228f179b47efb72e4c3965ad8014ad75f68d5ce9", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/72ab075a870b759a5b5a1bd7c7d2ab3ea3a28685cd9b0907fb700b4721240bfd/database", + "cache_key": "72ab075a870b759a5b5a1bd7c7d2ab3ea3a28685cd9b0907fb700b4721240bfd", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/8cac6f7f21266f2feefffb54c343d94c004b24e3c805fe078e2334be72f8a58c/database", + "cache_key": "8cac6f7f21266f2feefffb54c343d94c004b24e3c805fe078e2334be72f8a58c", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-89a9ff0f9cf4f2f4cc91/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-89a9ff0f9cf4f2f4cc91/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-89a9ff0f9cf4f2f4cc91/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..18bffbc46f77b1eeea2cf09201b687e901b7cd1e --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/patch.diff @@ -0,0 +1,106 @@ +diff --git a/xhu.py b/xhu.py +index a28c5a8..b999957 100644 +--- a/xhu.py ++++ b/xhu.py +@@ -29,6 +29,7 @@ import pathlib + import typing + + import flask ++import werkzeug.exceptions + + app = flask.Flask("xmpp-http-upload") + app.config.from_envvar("XMPP_HTTP_UPLOAD_CONFIG") +@@ -39,16 +40,11 @@ if app.config['ENABLE_CORS']: + CORS(app) + + +-def sanitized_join(path: str, root: pathlib.Path) -> pathlib.Path: +- result = (root / path).absolute() +- if not str(result).startswith(str(root) + "/"): +- raise ValueError("resulting path is outside root") +- return result +- +- +-def get_paths(base_path: pathlib.Path): +- data_file = pathlib.Path(str(base_path) + ".data") +- metadata_file = pathlib.Path(str(base_path) + ".meta") ++def get_paths(root: str, sub_path: str) \ ++ -> typing.Tuple[pathlib.Path, pathlib.Path]: ++ base_path = flask.safe_join(root, sub_path) ++ data_file = pathlib.Path(base_path + ".data") ++ metadata_file = pathlib.Path(base_path + ".meta") + + return data_file, metadata_file + +@@ -58,15 +54,10 @@ def load_metadata(metadata_file): + return json.load(f) + + +-def get_info(path: str, root: pathlib.Path) -> typing.Tuple[ ++def get_info(path: str) -> typing.Tuple[ + pathlib.Path, + dict]: +- dest_path = sanitized_join( +- path, +- pathlib.Path(app.config["DATA_ROOT"]), +- ) +- +- data_file, metadata_file = get_paths(dest_path) ++ data_file, metadata_file = get_paths(app.config["DATA_ROOT"], path) + + return data_file, load_metadata(metadata_file) + +@@ -104,11 +95,8 @@ def stream_file(src, dest, nbytes): + @app.route("/", methods=["PUT"]) + def put_file(path): + try: +- dest_path = sanitized_join( +- path, +- pathlib.Path(app.config["DATA_ROOT"]), +- ) +- except ValueError: ++ data_file, metadata_file = get_paths(app.config["DATA_ROOT"], path) ++ except werkzeug.exceptions.NotFound: + return flask.Response( + "Not Found", + 404, +@@ -134,8 +122,7 @@ def put_file(path): + "application/octet-stream", + ) + +- dest_path.parent.mkdir(parents=True, exist_ok=True, mode=0o770) +- data_file, metadata_file = get_paths(dest_path) ++ data_file.parent.mkdir(parents=True, exist_ok=True, mode=0o770) + + try: + with write_file(data_file) as fout: +@@ -189,13 +176,10 @@ def generate_headers(response_headers, metadata_headers): + @app.route("/", methods=["HEAD"]) + def head_file(path): + try: +- data_file, metadata = get_info( +- path, +- pathlib.Path(app.config["DATA_ROOT"]) +- ) ++ data_file, metadata = get_info(path) + + stat = data_file.stat() +- except (OSError, ValueError): ++ except (OSError, werkzeug.exceptions.NotFound): + return flask.Response( + "Not Found", + 404, +@@ -214,11 +198,8 @@ def head_file(path): + @app.route("/", methods=["GET"]) + def get_file(path): + try: +- data_file, metadata = get_info( +- path, +- pathlib.Path(app.config["DATA_ROOT"]) +- ) +- except (OSError, ValueError): ++ data_file, metadata = get_info(path) ++ except (OSError, werkzeug.exceptions.NotFound): + return flask.Response( + "Not Found", + 404, diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6b0e311caeeebdd46b4ff00884fe65be8b87a52b --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/post_context.md @@ -0,0 +1,144 @@ +# Patch-overlapping Python context after the fix + +## `xhu.py` — `function:get_paths` (lines 43-49) + +```python +def get_paths(root: str, sub_path: str) \ + -> typing.Tuple[pathlib.Path, pathlib.Path]: + base_path = flask.safe_join(root, sub_path) + data_file = pathlib.Path(base_path + ".data") + metadata_file = pathlib.Path(base_path + ".meta") + + return data_file, metadata_file +``` + +## `xhu.py` — `function:get_info` (lines 57-62) + +```python +def get_info(path: str) -> typing.Tuple[ + pathlib.Path, + dict]: + data_file, metadata_file = get_paths(app.config["DATA_ROOT"], path) + + return data_file, load_metadata(metadata_file) +``` + +## `xhu.py` — `function:put_file` (lines 95-157) + +```python +def put_file(path): + try: + data_file, metadata_file = get_paths(app.config["DATA_ROOT"], path) + except werkzeug.exceptions.NotFound: + return flask.Response( + "Not Found", + 404, + mimetype="text/plain", + ) + + verification_key = flask.request.args.get("v", "") + length = int(flask.request.headers.get("Content-Length", 0)) + hmac_input = "{} {}".format(path, length).encode("utf-8") + key = app.config["SECRET_KEY"] + mac = hmac.new(key, hmac_input, hashlib.sha256) + digest = mac.hexdigest() + + if not hmac.compare_digest(digest, verification_key): + return flask.Response( + "Invalid verification key", + 403, + mimetype="text/plain", + ) + + content_type = flask.request.headers.get( + "Content-Type", + "application/octet-stream", + ) + + data_file.parent.mkdir(parents=True, exist_ok=True, mode=0o770) + + try: + with write_file(data_file) as fout: + stream_file(flask.request.stream, fout, length) + + with metadata_file.open("x") as f: + json.dump( + { + "headers": {"Content-Type": content_type}, + }, + f, + ) + except EOFError: + return flask.Response( + "Bad Request", + 400, + mimetype="text/plain", + ) + except OSError as exc: + if exc.errno == errno.EEXIST: + return flask.Response( + "Conflict", + 409, + mimetype="text/plain", + ) + raise + + return flask.Response( + "Created", + 201, + mimetype="text/plain", + ) +``` + +## `xhu.py` — `function:head_file` (lines 176-195) + +```python +def head_file(path): + try: + data_file, metadata = get_info(path) + + stat = data_file.stat() + except (OSError, werkzeug.exceptions.NotFound): + return flask.Response( + "Not Found", + 404, + mimetype="text/plain", + ) + + response = flask.Response() + response.headers["Content-Length"] = str(stat.st_size) + generate_headers( + response.headers, + metadata["headers"], + ) + return response +``` + +## `xhu.py` — `function:get_file` (lines 198-216) + +```python +def get_file(path): + try: + data_file, metadata = get_info(path) + except (OSError, werkzeug.exceptions.NotFound): + return flask.Response( + "Not Found", + 404, + mimetype="text/plain", + ) + + response = flask.make_response(flask.send_file( + str(data_file), + )) + generate_headers( + response.headers, + metadata["headers"], + ) + return response +``` + +## `xhu.py` — `module:@32` (lines 32-32) + +```python +import werkzeug.exceptions +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..5a9b7b66b9ea40ceeb686247d2d6f6e68471f502 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/pre_context.md @@ -0,0 +1,161 @@ +# Patch-overlapping Python context before the fix + +## `xhu.py` — `function:sanitized_join` (lines 42-46) + +```python +def sanitized_join(path: str, root: pathlib.Path) -> pathlib.Path: + result = (root / path).absolute() + if not str(result).startswith(str(root) + "/"): + raise ValueError("resulting path is outside root") + return result +``` + +## `xhu.py` — `function:get_paths` (lines 49-53) + +```python +def get_paths(base_path: pathlib.Path): + data_file = pathlib.Path(str(base_path) + ".data") + metadata_file = pathlib.Path(str(base_path) + ".meta") + + return data_file, metadata_file +``` + +## `xhu.py` — `function:get_info` (lines 61-71) + +```python +def get_info(path: str, root: pathlib.Path) -> typing.Tuple[ + pathlib.Path, + dict]: + dest_path = sanitized_join( + path, + pathlib.Path(app.config["DATA_ROOT"]), + ) + + data_file, metadata_file = get_paths(dest_path) + + return data_file, load_metadata(metadata_file) +``` + +## `xhu.py` — `function:put_file` (lines 104-170) + +```python +def put_file(path): + try: + dest_path = sanitized_join( + path, + pathlib.Path(app.config["DATA_ROOT"]), + ) + except ValueError: + return flask.Response( + "Not Found", + 404, + mimetype="text/plain", + ) + + verification_key = flask.request.args.get("v", "") + length = int(flask.request.headers.get("Content-Length", 0)) + hmac_input = "{} {}".format(path, length).encode("utf-8") + key = app.config["SECRET_KEY"] + mac = hmac.new(key, hmac_input, hashlib.sha256) + digest = mac.hexdigest() + + if not hmac.compare_digest(digest, verification_key): + return flask.Response( + "Invalid verification key", + 403, + mimetype="text/plain", + ) + + content_type = flask.request.headers.get( + "Content-Type", + "application/octet-stream", + ) + + dest_path.parent.mkdir(parents=True, exist_ok=True, mode=0o770) + data_file, metadata_file = get_paths(dest_path) + + try: + with write_file(data_file) as fout: + stream_file(flask.request.stream, fout, length) + + with metadata_file.open("x") as f: + json.dump( + { + "headers": {"Content-Type": content_type}, + }, + f, + ) + except EOFError: + return flask.Response( + "Bad Request", + 400, + mimetype="text/plain", + ) + except OSError as exc: + if exc.errno == errno.EEXIST: + return flask.Response( + "Conflict", + 409, + mimetype="text/plain", + ) + raise + + return flask.Response( + "Created", + 201, + mimetype="text/plain", + ) +``` + +## `xhu.py` — `function:head_file` (lines 189-211) + +```python +def head_file(path): + try: + data_file, metadata = get_info( + path, + pathlib.Path(app.config["DATA_ROOT"]) + ) + + stat = data_file.stat() + except (OSError, ValueError): + return flask.Response( + "Not Found", + 404, + mimetype="text/plain", + ) + + response = flask.Response() + response.headers["Content-Length"] = str(stat.st_size) + generate_headers( + response.headers, + metadata["headers"], + ) + return response +``` + +## `xhu.py` — `function:get_file` (lines 214-235) + +```python +def get_file(path): + try: + data_file, metadata = get_info( + path, + pathlib.Path(app.config["DATA_ROOT"]) + ) + except (OSError, ValueError): + return flask.Response( + "Not Found", + 404, + mimetype="text/plain", + ) + + response = flask.make_response(flask.send_file( + str(data_file), + )) + generate_headers( + response.headers, + metadata["headers"], + ) + return response +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4c41f85b4ca4da58c75b5ddf8826f87716be4071 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/task.json @@ -0,0 +1,54 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-8e39d07d2ff863a3f19e", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-8e39d07d2ff863a3f19e", + "project_id": "pyvul__horazont__xmpp-http-upload", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "xhu.py" + ], + "patch_units": { + "before": [ + "function:sanitized_join", + "function:get_paths", + "function:get_info", + "function:put_file", + "function:head_file", + "function:get_file" + ], + "after": [ + "function:get_paths", + "function:get_info", + "function:put_file", + "function:head_file", + "function:get_file", + "module:@32" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/e48d67cb6f945ecc194f637a91ce5d91546bb1e5206ba6454416191ddbb86340/database", + "cache_key": "e48d67cb6f945ecc194f637a91ce5d91546bb1e5206ba6454416191ddbb86340", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/ce8e1f9ebc30cd6470368e164816964313855b2829eefd057631fd289739a386/database", + "cache_key": "ce8e1f9ebc30cd6470368e164816964313855b2829eefd057631fd289739a386", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/4b2e3749d34589d1825d172fe2b6a490d358a73d19dbdea5dfc095c61103ca1f/database", + "cache_key": "4b2e3749d34589d1825d172fe2b6a490d358a73d19dbdea5dfc095c61103ca1f", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-8e39d07d2ff863a3f19e/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-8e39d07d2ff863a3f19e/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8e39d07d2ff863a3f19e/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..60549f6aee76e6cf2d7df97e68f5d81d31d3d3ae --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/patch.diff @@ -0,0 +1,81 @@ +diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py +index 4d075b3..4c85606 100644 +--- a/starlette/staticfiles.py ++++ b/starlette/staticfiles.py +@@ -169,7 +169,7 @@ class StaticFiles: + else: + full_path = os.path.realpath(joined_path) + directory = os.path.realpath(directory) +- if os.path.commonprefix([full_path, directory]) != directory: ++ if os.path.commonpath([full_path, directory]) != directory: + # Don't allow misbehaving clients to break out of the static files + # directory. + continue +diff --git a/tests/test_staticfiles.py b/tests/test_staticfiles.py +index eb6c73f..23d0b57 100644 +--- a/tests/test_staticfiles.py ++++ b/tests/test_staticfiles.py +@@ -1,8 +1,8 @@ + import os +-import pathlib + import stat + import tempfile + import time ++from pathlib import Path + + import anyio + import pytest +@@ -28,13 +28,12 @@ def test_staticfiles(tmpdir, test_client_factory): + assert response.text == "" + + +-def test_staticfiles_with_pathlib(tmpdir, test_client_factory): +- base_dir = pathlib.Path(tmpdir) +- path = base_dir / "example.txt" ++def test_staticfiles_with_pathlib(tmp_path: Path, test_client_factory): ++ path = tmp_path / "example.txt" + with open(path, "w") as file: + file.write("") + +- app = StaticFiles(directory=base_dir) ++ app = StaticFiles(directory=tmp_path) + client = test_client_factory(app) + response = client.get("/example.txt") + assert response.status_code == 200 +@@ -516,3 +515,36 @@ def test_staticfiles_disallows_path_traversal_with_symlinks(tmpdir): + + assert exc_info.value.status_code == 404 + assert exc_info.value.detail == "Not Found" ++ ++ ++def test_staticfiles_avoids_path_traversal(tmp_path: Path): ++ statics_path = tmp_path / "static" ++ statics_disallow_path = tmp_path / "static_disallow" ++ ++ statics_path.mkdir() ++ statics_disallow_path.mkdir() ++ ++ static_index_file = statics_path / "index.html" ++ statics_disallow_path_index_file = statics_disallow_path / "index.html" ++ static_file = tmp_path / "static1.txt" ++ ++ static_index_file.write_text("

Hello

") ++ statics_disallow_path_index_file.write_text("

Private

") ++ static_file.write_text("Private") ++ ++ app = StaticFiles(directory=statics_path) ++ ++ # We can't test this with 'httpx', so we test the app directly here. ++ path = app.get_path({"path": "/../static1.txt"}) ++ with pytest.raises(HTTPException) as exc_info: ++ anyio.run(app.get_response, path, {"method": "GET"}) ++ ++ assert exc_info.value.status_code == 404 ++ assert exc_info.value.detail == "Not Found" ++ ++ path = app.get_path({"path": "/../static_disallow/index.html"}) ++ with pytest.raises(HTTPException) as exc_info: ++ anyio.run(app.get_response, path, {"method": "GET"}) ++ ++ assert exc_info.value.status_code == 404 ++ assert exc_info.value.detail == "Not Found" diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..c25e7b2eae90a7d037a35c20e295235639620241 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/post_context.md @@ -0,0 +1,302 @@ +# Patch-overlapping Python context after the fix + +## `starlette/staticfiles.py` — `class:StaticFiles` (lines 38-246) + +```python +class StaticFiles: + def __init__( + self, + *, + directory: typing.Optional[PathLike] = None, + packages: typing.Optional[ + typing.List[typing.Union[str, typing.Tuple[str, str]]] + ] = None, + html: bool = False, + check_dir: bool = True, + follow_symlink: bool = False, + ) -> None: + self.directory = directory + self.packages = packages + self.all_directories = self.get_directories(directory, packages) + self.html = html + self.config_checked = False + self.follow_symlink = follow_symlink + if check_dir and directory is not None and not os.path.isdir(directory): + raise RuntimeError(f"Directory '{directory}' does not exist") + + def get_directories( + self, + directory: typing.Optional[PathLike] = None, + packages: typing.Optional[ + typing.List[typing.Union[str, typing.Tuple[str, str]]] + ] = None, + ) -> typing.List[PathLike]: + """ + Given `directory` and `packages` arguments, return a list of all the + directories that should be used for serving static files from. + """ + directories = [] + if directory is not None: + directories.append(directory) + + for package in packages or []: + if isinstance(package, tuple): + package, statics_dir = package + else: + statics_dir = "statics" + spec = importlib.util.find_spec(package) + assert spec is not None, f"Package {package!r} could not be found." + assert spec.origin is not None, f"Package {package!r} could not be found." + package_directory = os.path.normpath( + os.path.join(spec.origin, "..", statics_dir) + ) + assert os.path.isdir( + package_directory + ), f"Directory '{statics_dir!r}' in package {package!r} could not be found." + directories.append(package_directory) + + return directories + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + """ + The ASGI entry point. + """ + assert scope["type"] == "http" + + if not self.config_checked: + await self.check_config() + self.config_checked = True + + path = self.get_path(scope) + response = await self.get_response(path, scope) + await response(scope, receive, send) + + def get_path(self, scope: Scope) -> str: + """ + Given the ASGI scope, return the `path` string to serve up, + with OS specific path separators, and any '..', '.' components removed. + """ + return os.path.normpath(os.path.join(*scope["path"].split("/"))) + + async def get_response(self, path: str, scope: Scope) -> Response: + """ + Returns an HTTP response, given the incoming path, method and request headers. + """ + if scope["method"] not in ("GET", "HEAD"): + raise HTTPException(status_code=405) + + try: + full_path, stat_result = await anyio.to_thread.run_sync( + self.lookup_path, path + ) + except PermissionError: + raise HTTPException(status_code=401) + except OSError: + raise + + if stat_result and stat.S_ISREG(stat_result.st_mode): + # We have a static file to serve. + return self.file_response(full_path, stat_result, scope) + + elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html: + # We're in HTML mode, and have got a directory URL. + # Check if we have 'index.html' file to serve. + index_path = os.path.join(path, "index.html") + full_path, stat_result = await anyio.to_thread.run_sync( + self.lookup_path, index_path + ) + if stat_result is not None and stat.S_ISREG(stat_result.st_mode): + if not scope["path"].endswith("/"): + # Directory URLs should redirect to always end in "/". + url = URL(scope=scope) + url = url.replace(path=url.path + "/") + return RedirectResponse(url=url) + return self.file_response(full_path, stat_result, scope) + + if self.html: + # Check for '404.html' if we're in HTML mode. + full_path, stat_result = await anyio.to_thread.run_sync( + self.lookup_path, "404.html" + ) + if stat_result and stat.S_ISREG(stat_result.st_mode): + return FileResponse( + full_path, + stat_result=stat_result, + method=scope["method"], + status_code=404, + ) + raise HTTPException(status_code=404) + + def lookup_path( + self, path: str + ) -> typing.Tuple[str, typing.Optional[os.stat_result]]: + for directory in self.all_directories: + joined_path = os.path.join(directory, path) + if self.follow_symlink: + full_path = os.path.abspath(joined_path) + else: + full_path = os.path.realpath(joined_path) + directory = os.path.realpath(directory) + if os.path.commonpath([full_path, directory]) != directory: + # Don't allow misbehaving clients to break out of the static files + # directory. + continue + try: + return full_path, os.stat(full_path) + except (FileNotFoundError, NotADirectoryError): + continue + return "", None + + def file_response( + self, + full_path: PathLike, + stat_result: os.stat_result, + scope: Scope, + status_code: int = 200, + ) -> Response: + method = scope["method"] + request_headers = Headers(scope=scope) + + response = FileResponse( + full_path, status_code=status_code, stat_result=stat_result, method=method + ) + if self.is_not_modified(response.headers, request_headers): + return NotModifiedResponse(response.headers) + return response + + async def check_config(self) -> None: + """ + Perform a one-off configuration check that StaticFiles is actually + pointed at a directory, so that we can raise loud errors rather than + just returning 404 responses. + """ + if self.directory is None: + return + + try: + stat_result = await anyio.to_thread.run_sync(os.stat, self.directory) + except FileNotFoundError: + raise RuntimeError( + f"StaticFiles directory '{self.directory}' does not exist." + ) + if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)): + raise RuntimeError( + f"StaticFiles path '{self.directory}' is not a directory." + ) + + def is_not_modified( + self, response_headers: Headers, request_headers: Headers + ) -> bool: + """ + Given the request and response headers, return `True` if an HTTP + "Not Modified" response could be returned instead. + """ + try: + if_none_match = request_headers["if-none-match"] + etag = response_headers["etag"] + if if_none_match == etag: + return True + except KeyError: + pass + + try: + if_modified_since = parsedate(request_headers["if-modified-since"]) + last_modified = parsedate(response_headers["last-modified"]) + if ( + if_modified_since is not None + and last_modified is not None + and if_modified_since >= last_modified + ): + return True + except KeyError: + pass + + return False +``` + +## `starlette/staticfiles.py` — `function:StaticFiles.lookup_path` (lines 162-180) + +```python + def lookup_path( + self, path: str + ) -> typing.Tuple[str, typing.Optional[os.stat_result]]: + for directory in self.all_directories: + joined_path = os.path.join(directory, path) + if self.follow_symlink: + full_path = os.path.abspath(joined_path) + else: + full_path = os.path.realpath(joined_path) + directory = os.path.realpath(directory) + if os.path.commonpath([full_path, directory]) != directory: + # Don't allow misbehaving clients to break out of the static files + # directory. + continue + try: + return full_path, os.stat(full_path) + except (FileNotFoundError, NotADirectoryError): + continue + return "", None +``` + +## `tests/test_staticfiles.py` — `function:test_staticfiles_with_pathlib` (lines 31-40) + +```python +def test_staticfiles_with_pathlib(tmp_path: Path, test_client_factory): + path = tmp_path / "example.txt" + with open(path, "w") as file: + file.write("") + + app = StaticFiles(directory=tmp_path) + client = test_client_factory(app) + response = client.get("/example.txt") + assert response.status_code == 200 + assert response.text == "" +``` + +## `tests/test_staticfiles.py` — `function:test_staticfiles_avoids_path_traversal` (lines 520-550) + +```python +def test_staticfiles_avoids_path_traversal(tmp_path: Path): + statics_path = tmp_path / "static" + statics_disallow_path = tmp_path / "static_disallow" + + statics_path.mkdir() + statics_disallow_path.mkdir() + + static_index_file = statics_path / "index.html" + statics_disallow_path_index_file = statics_disallow_path / "index.html" + static_file = tmp_path / "static1.txt" + + static_index_file.write_text("

Hello

") + statics_disallow_path_index_file.write_text("

Private

") + static_file.write_text("Private") + + app = StaticFiles(directory=statics_path) + + # We can't test this with 'httpx', so we test the app directly here. + path = app.get_path({"path": "/../static1.txt"}) + with pytest.raises(HTTPException) as exc_info: + anyio.run(app.get_response, path, {"method": "GET"}) + + assert exc_info.value.status_code == 404 + assert exc_info.value.detail == "Not Found" + + path = app.get_path({"path": "/../static_disallow/index.html"}) + with pytest.raises(HTTPException) as exc_info: + anyio.run(app.get_response, path, {"method": "GET"}) + + assert exc_info.value.status_code == 404 + assert exc_info.value.detail == "Not Found" +``` + +## `tests/test_staticfiles.py` — `module:@2` (lines 2-2) + +```python +import stat +``` + +## `tests/test_staticfiles.py` — `module:@5` (lines 5-5) + +```python +from pathlib import Path +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..c9ecaddfc785b5e7638f9e2d5b8256509fbf59da --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/pre_context.md @@ -0,0 +1,261 @@ +# Patch-overlapping Python context before the fix + +## `starlette/staticfiles.py` — `class:StaticFiles` (lines 38-246) + +```python +class StaticFiles: + def __init__( + self, + *, + directory: typing.Optional[PathLike] = None, + packages: typing.Optional[ + typing.List[typing.Union[str, typing.Tuple[str, str]]] + ] = None, + html: bool = False, + check_dir: bool = True, + follow_symlink: bool = False, + ) -> None: + self.directory = directory + self.packages = packages + self.all_directories = self.get_directories(directory, packages) + self.html = html + self.config_checked = False + self.follow_symlink = follow_symlink + if check_dir and directory is not None and not os.path.isdir(directory): + raise RuntimeError(f"Directory '{directory}' does not exist") + + def get_directories( + self, + directory: typing.Optional[PathLike] = None, + packages: typing.Optional[ + typing.List[typing.Union[str, typing.Tuple[str, str]]] + ] = None, + ) -> typing.List[PathLike]: + """ + Given `directory` and `packages` arguments, return a list of all the + directories that should be used for serving static files from. + """ + directories = [] + if directory is not None: + directories.append(directory) + + for package in packages or []: + if isinstance(package, tuple): + package, statics_dir = package + else: + statics_dir = "statics" + spec = importlib.util.find_spec(package) + assert spec is not None, f"Package {package!r} could not be found." + assert spec.origin is not None, f"Package {package!r} could not be found." + package_directory = os.path.normpath( + os.path.join(spec.origin, "..", statics_dir) + ) + assert os.path.isdir( + package_directory + ), f"Directory '{statics_dir!r}' in package {package!r} could not be found." + directories.append(package_directory) + + return directories + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + """ + The ASGI entry point. + """ + assert scope["type"] == "http" + + if not self.config_checked: + await self.check_config() + self.config_checked = True + + path = self.get_path(scope) + response = await self.get_response(path, scope) + await response(scope, receive, send) + + def get_path(self, scope: Scope) -> str: + """ + Given the ASGI scope, return the `path` string to serve up, + with OS specific path separators, and any '..', '.' components removed. + """ + return os.path.normpath(os.path.join(*scope["path"].split("/"))) + + async def get_response(self, path: str, scope: Scope) -> Response: + """ + Returns an HTTP response, given the incoming path, method and request headers. + """ + if scope["method"] not in ("GET", "HEAD"): + raise HTTPException(status_code=405) + + try: + full_path, stat_result = await anyio.to_thread.run_sync( + self.lookup_path, path + ) + except PermissionError: + raise HTTPException(status_code=401) + except OSError: + raise + + if stat_result and stat.S_ISREG(stat_result.st_mode): + # We have a static file to serve. + return self.file_response(full_path, stat_result, scope) + + elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html: + # We're in HTML mode, and have got a directory URL. + # Check if we have 'index.html' file to serve. + index_path = os.path.join(path, "index.html") + full_path, stat_result = await anyio.to_thread.run_sync( + self.lookup_path, index_path + ) + if stat_result is not None and stat.S_ISREG(stat_result.st_mode): + if not scope["path"].endswith("/"): + # Directory URLs should redirect to always end in "/". + url = URL(scope=scope) + url = url.replace(path=url.path + "/") + return RedirectResponse(url=url) + return self.file_response(full_path, stat_result, scope) + + if self.html: + # Check for '404.html' if we're in HTML mode. + full_path, stat_result = await anyio.to_thread.run_sync( + self.lookup_path, "404.html" + ) + if stat_result and stat.S_ISREG(stat_result.st_mode): + return FileResponse( + full_path, + stat_result=stat_result, + method=scope["method"], + status_code=404, + ) + raise HTTPException(status_code=404) + + def lookup_path( + self, path: str + ) -> typing.Tuple[str, typing.Optional[os.stat_result]]: + for directory in self.all_directories: + joined_path = os.path.join(directory, path) + if self.follow_symlink: + full_path = os.path.abspath(joined_path) + else: + full_path = os.path.realpath(joined_path) + directory = os.path.realpath(directory) + if os.path.commonprefix([full_path, directory]) != directory: + # Don't allow misbehaving clients to break out of the static files + # directory. + continue + try: + return full_path, os.stat(full_path) + except (FileNotFoundError, NotADirectoryError): + continue + return "", None + + def file_response( + self, + full_path: PathLike, + stat_result: os.stat_result, + scope: Scope, + status_code: int = 200, + ) -> Response: + method = scope["method"] + request_headers = Headers(scope=scope) + + response = FileResponse( + full_path, status_code=status_code, stat_result=stat_result, method=method + ) + if self.is_not_modified(response.headers, request_headers): + return NotModifiedResponse(response.headers) + return response + + async def check_config(self) -> None: + """ + Perform a one-off configuration check that StaticFiles is actually + pointed at a directory, so that we can raise loud errors rather than + just returning 404 responses. + """ + if self.directory is None: + return + + try: + stat_result = await anyio.to_thread.run_sync(os.stat, self.directory) + except FileNotFoundError: + raise RuntimeError( + f"StaticFiles directory '{self.directory}' does not exist." + ) + if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)): + raise RuntimeError( + f"StaticFiles path '{self.directory}' is not a directory." + ) + + def is_not_modified( + self, response_headers: Headers, request_headers: Headers + ) -> bool: + """ + Given the request and response headers, return `True` if an HTTP + "Not Modified" response could be returned instead. + """ + try: + if_none_match = request_headers["if-none-match"] + etag = response_headers["etag"] + if if_none_match == etag: + return True + except KeyError: + pass + + try: + if_modified_since = parsedate(request_headers["if-modified-since"]) + last_modified = parsedate(response_headers["last-modified"]) + if ( + if_modified_since is not None + and last_modified is not None + and if_modified_since >= last_modified + ): + return True + except KeyError: + pass + + return False +``` + +## `starlette/staticfiles.py` — `function:StaticFiles.lookup_path` (lines 162-180) + +```python + def lookup_path( + self, path: str + ) -> typing.Tuple[str, typing.Optional[os.stat_result]]: + for directory in self.all_directories: + joined_path = os.path.join(directory, path) + if self.follow_symlink: + full_path = os.path.abspath(joined_path) + else: + full_path = os.path.realpath(joined_path) + directory = os.path.realpath(directory) + if os.path.commonprefix([full_path, directory]) != directory: + # Don't allow misbehaving clients to break out of the static files + # directory. + continue + try: + return full_path, os.stat(full_path) + except (FileNotFoundError, NotADirectoryError): + continue + return "", None +``` + +## `tests/test_staticfiles.py` — `function:test_staticfiles_with_pathlib` (lines 31-41) + +```python +def test_staticfiles_with_pathlib(tmpdir, test_client_factory): + base_dir = pathlib.Path(tmpdir) + path = base_dir / "example.txt" + with open(path, "w") as file: + file.write("") + + app = StaticFiles(directory=base_dir) + client = test_client_factory(app) + response = client.get("/example.txt") + assert response.status_code == 200 + assert response.text == "" +``` + +## `tests/test_staticfiles.py` — `module:@2` (lines 2-2) + +```python +import pathlib +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3ede49235e77b2d0b67dfded00ef3adb90daf043 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/task.json @@ -0,0 +1,53 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-8f3613497f18d5cf2684", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-8f3613497f18d5cf2684", + "project_id": "pyvul__encode__starlette", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "starlette/staticfiles.py", + "tests/test_staticfiles.py" + ], + "patch_units": { + "before": [ + "class:StaticFiles", + "function:StaticFiles.lookup_path", + "function:test_staticfiles_with_pathlib", + "module:@2" + ], + "after": [ + "class:StaticFiles", + "function:StaticFiles.lookup_path", + "function:test_staticfiles_with_pathlib", + "function:test_staticfiles_avoids_path_traversal", + "module:@2", + "module:@5" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/2040f9b1d063e5a202c5dc64eae077c30f07265d91a025ae95b5749568177f2f/database", + "cache_key": "2040f9b1d063e5a202c5dc64eae077c30f07265d91a025ae95b5749568177f2f", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/8e255e0691d5d6320b8e846805b3b191e0d6dbf1a1f16a5fcd1248a8f1cc60c6/database", + "cache_key": "8e255e0691d5d6320b8e846805b3b191e0d6dbf1a1f16a5fcd1248a8f1cc60c6", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/5dc381aa01b5c44c58d8c88b04b6880a594679bc983a6ff1203b0603ef5042c8/database", + "cache_key": "5dc381aa01b5c44c58d8c88b04b6880a594679bc983a6ff1203b0603ef5042c8", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-8f3613497f18d5cf2684/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-8f3613497f18d5cf2684/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-8f3613497f18d5cf2684/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5f409dffc3f73a480aba595295857125d26bde4f --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/patch.diff @@ -0,0 +1,36 @@ +diff --git a/sydent/util/emailutils.py b/sydent/util/emailutils.py +index 2ae5fdc..7b3b92c 100644 +--- a/sydent/util/emailutils.py ++++ b/sydent/util/emailutils.py +@@ -55,12 +55,13 @@ def sendEmail(sydent, templateName, mailTo, substitutions): + allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) + allSubstitutions[k+"_forurl"] = urllib.quote(v) + +- mailString = open(mailTemplateFile).read() % allSubstitutions +- rawFrom = email.utils.parseaddr(mailFrom)[1] +- rawTo = email.utils.parseaddr(mailTo)[1] +- if rawFrom == '' or rawTo == '': ++ mailString = open(mailTemplateFile).read().decode('utf8') % allSubstitutions ++ parsedFrom = email.utils.parseaddr(mailFrom)[1] ++ parsedTo = email.utils.parseaddr(mailTo)[1] ++ if parsedFrom == '' or parsedTo == '': + logger.info("Couldn't parse from / to address %s / %s", mailFrom, mailTo) + raise EmailAddressException() ++ + mailServer = sydent.cfg.get('email', 'email.smtphost') + mailPort = sydent.cfg.get('email', 'email.smtpport') + mailUsername = sydent.cfg.get('email', 'email.smtpusername') +@@ -77,7 +78,12 @@ def sendEmail(sydent, templateName, mailTo, substitutions): + smtp = smtplib.SMTP(mailServer, mailPort, myHostname) + if mailUsername != '': + smtp.login(mailUsername, mailPassword) +- smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8')) ++ ++ # We're using the parsing above to do basic validation, but instead of ++ # failing it may munge the address it returns. So we should *not* use ++ # that parsed address, as it may not match any validation done ++ # elsewhere. ++ smtp.sendmail(mailFrom, mailTo, mailString.encode('utf-8')) + smtp.quit() + except Exception as origException: + twisted.python.log.err() diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..112200701f6433ce0af7d1e23235aa7ecfef8d2c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/post_context.md @@ -0,0 +1,65 @@ +# Patch-overlapping Python context after the fix + +## `sydent/util/emailutils.py` — `function:sendEmail` (lines 34-92) + +```python +def sendEmail(sydent, templateName, mailTo, substitutions): + mailFrom = sydent.cfg.get('email', 'email.from') + mailTemplateFile = sydent.cfg.get('email', templateName) + + myHostname = sydent.cfg.get('email', 'email.hostname') + if myHostname == '': + myHostname = socket.getfqdn() + midRandom = "".join([random.choice(string.ascii_letters) for _ in range(16)]) + messageid = "<%d%s@%s>" % (time_msec(), midRandom, myHostname) + + allSubstitutions = {} + allSubstitutions.update(substitutions) + allSubstitutions.update({ + 'messageid': messageid, + 'date': email.utils.formatdate(localtime=False), + 'to': mailTo, + 'from': mailFrom, + }) + + for k,v in allSubstitutions.items(): + allSubstitutions[k] = v.decode('utf8') + allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) + allSubstitutions[k+"_forurl"] = urllib.quote(v) + + mailString = open(mailTemplateFile).read().decode('utf8') % allSubstitutions + parsedFrom = email.utils.parseaddr(mailFrom)[1] + parsedTo = email.utils.parseaddr(mailTo)[1] + if parsedFrom == '' or parsedTo == '': + logger.info("Couldn't parse from / to address %s / %s", mailFrom, mailTo) + raise EmailAddressException() + + mailServer = sydent.cfg.get('email', 'email.smtphost') + mailPort = sydent.cfg.get('email', 'email.smtpport') + mailUsername = sydent.cfg.get('email', 'email.smtpusername') + mailPassword = sydent.cfg.get('email', 'email.smtppassword') + mailTLSMode = sydent.cfg.get('email', 'email.tlsmode') + logger.info("Sending mail to %s with mail server: %s" % (mailTo, mailServer,)) + try: + if mailTLSMode == 'SSL' or mailTLSMode == 'TLS': + smtp = smtplib.SMTP_SSL(mailServer, mailPort, myHostname) + elif mailTLSMode == 'STARTTLS': + smtp = smtplib.SMTP(mailServer, mailPort, myHostname) + smtp.starttls() + else: + smtp = smtplib.SMTP(mailServer, mailPort, myHostname) + if mailUsername != '': + smtp.login(mailUsername, mailPassword) + + # We're using the parsing above to do basic validation, but instead of + # failing it may munge the address it returns. So we should *not* use + # that parsed address, as it may not match any validation done + # elsewhere. + smtp.sendmail(mailFrom, mailTo, mailString.encode('utf-8')) + smtp.quit() + except Exception as origException: + twisted.python.log.err() + ese = EmailSendException() + ese.cause = origException + raise ese +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..9c2f631364c115b1515e27b556121aa344961fc9 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/pre_context.md @@ -0,0 +1,59 @@ +# Patch-overlapping Python context before the fix + +## `sydent/util/emailutils.py` — `function:sendEmail` (lines 34-86) + +```python +def sendEmail(sydent, templateName, mailTo, substitutions): + mailFrom = sydent.cfg.get('email', 'email.from') + mailTemplateFile = sydent.cfg.get('email', templateName) + + myHostname = sydent.cfg.get('email', 'email.hostname') + if myHostname == '': + myHostname = socket.getfqdn() + midRandom = "".join([random.choice(string.ascii_letters) for _ in range(16)]) + messageid = "<%d%s@%s>" % (time_msec(), midRandom, myHostname) + + allSubstitutions = {} + allSubstitutions.update(substitutions) + allSubstitutions.update({ + 'messageid': messageid, + 'date': email.utils.formatdate(localtime=False), + 'to': mailTo, + 'from': mailFrom, + }) + + for k,v in allSubstitutions.items(): + allSubstitutions[k] = v.decode('utf8') + allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) + allSubstitutions[k+"_forurl"] = urllib.quote(v) + + mailString = open(mailTemplateFile).read() % allSubstitutions + rawFrom = email.utils.parseaddr(mailFrom)[1] + rawTo = email.utils.parseaddr(mailTo)[1] + if rawFrom == '' or rawTo == '': + logger.info("Couldn't parse from / to address %s / %s", mailFrom, mailTo) + raise EmailAddressException() + mailServer = sydent.cfg.get('email', 'email.smtphost') + mailPort = sydent.cfg.get('email', 'email.smtpport') + mailUsername = sydent.cfg.get('email', 'email.smtpusername') + mailPassword = sydent.cfg.get('email', 'email.smtppassword') + mailTLSMode = sydent.cfg.get('email', 'email.tlsmode') + logger.info("Sending mail to %s with mail server: %s" % (mailTo, mailServer,)) + try: + if mailTLSMode == 'SSL' or mailTLSMode == 'TLS': + smtp = smtplib.SMTP_SSL(mailServer, mailPort, myHostname) + elif mailTLSMode == 'STARTTLS': + smtp = smtplib.SMTP(mailServer, mailPort, myHostname) + smtp.starttls() + else: + smtp = smtplib.SMTP(mailServer, mailPort, myHostname) + if mailUsername != '': + smtp.login(mailUsername, mailPassword) + smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8')) + smtp.quit() + except Exception as origException: + twisted.python.log.err() + ese = EmailSendException() + ese.cause = origException + raise ese +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d72a76326bb3f9ea8e42e3e5779efa7963cceb64 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/task.json @@ -0,0 +1,44 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-98fc634e79976d5b5241", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-98fc634e79976d5b5241", + "project_id": "pyvul__matrix-org__sydent", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "sydent/util/emailutils.py" + ], + "patch_units": { + "before": [ + "function:sendEmail" + ], + "after": [ + "function:sendEmail" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/74853a0a5cc1bdb05d7407120da143aafed5c4da0b64d6c66fc57f71f46f8b69/database", + "cache_key": "74853a0a5cc1bdb05d7407120da143aafed5c4da0b64d6c66fc57f71f46f8b69", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/424226b73490b89caaa7eef634852ca8334341eb353db9cfb4353d69e4e849f5/database", + "cache_key": "424226b73490b89caaa7eef634852ca8334341eb353db9cfb4353d69e4e849f5", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/4dbdf874b1136047637b4f285717d9c0cdcb95b18b366f0039e4cca7927b00a7/database", + "cache_key": "4dbdf874b1136047637b4f285717d9c0cdcb95b18b366f0039e4cca7927b00a7", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-98fc634e79976d5b5241/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-98fc634e79976d5b5241/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-98fc634e79976d5b5241/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..98ea80e0d905643cf4b1d4ea34e02b0fa18ebd64 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/patch.diff @@ -0,0 +1,37 @@ +diff --git a/CHANGES.rst b/CHANGES.rst +index 87033da6..70dbab9d 100644 +--- a/CHANGES.rst ++++ b/CHANGES.rst +@@ -20,6 +20,8 @@ Unreleased + (:issue:`1510`) + - The debugger detects cycles in chained exceptions and does not time + out in that case. (:issue:`1536`) ++- When running the development server in Docker, the debugger security ++ pin is now unique per container. + + + Version 0.15.2 +diff --git a/src/werkzeug/debug/__init__.py b/src/werkzeug/debug/__init__.py +index c5e4d2d5..9195c79a 100644 +--- a/src/werkzeug/debug/__init__.py ++++ b/src/werkzeug/debug/__init__.py +@@ -67,6 +67,19 @@ def get_machine_id(): + return rv + + def _generate(): ++ # docker containers share the same machine id, get the ++ # container id instead ++ try: ++ with open("/proc/self/cgroup") as f: ++ value = f.readline() ++ except IOError: ++ pass ++ else: ++ value = value.strip().partition("/docker/")[2] ++ ++ if value: ++ return value ++ + # Potential sources of secret information on linux. The machine-id + # is stable across boots, the boot id is not + for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id": diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..39d1ba519abb22abe491591e439038357a3a9b83 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/post_context.md @@ -0,0 +1,148 @@ +# Patch-overlapping Python context after the fix + +## `src/werkzeug/debug/__init__.py` — `function:get_machine_id` (lines 63-135) + +```python +def get_machine_id(): + global _machine_id + rv = _machine_id + if rv is not None: + return rv + + def _generate(): + # docker containers share the same machine id, get the + # container id instead + try: + with open("/proc/self/cgroup") as f: + value = f.readline() + except IOError: + pass + else: + value = value.strip().partition("/docker/")[2] + + if value: + return value + + # Potential sources of secret information on linux. The machine-id + # is stable across boots, the boot id is not + for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id": + try: + with open(filename, "rb") as f: + return f.readline().strip() + except IOError: + continue + + # On OS X we can use the computer's serial number assuming that + # ioreg exists and can spit out that information. + try: + # Also catch import errors: subprocess may not be available, e.g. + # Google App Engine + # See https://github.com/pallets/werkzeug/issues/925 + from subprocess import Popen, PIPE + + dump = Popen( + ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE + ).communicate()[0] + match = re.search(b'"serial-number" = <([^>]+)', dump) + if match is not None: + return match.group(1) + except (OSError, ImportError): + pass + + # On Windows we can use winreg to get the machine guid + wr = None + try: + import winreg as wr + except ImportError: + try: + import _winreg as wr + except ImportError: + pass + if wr is not None: + try: + with wr.OpenKey( + wr.HKEY_LOCAL_MACHINE, + "SOFTWARE\\Microsoft\\Cryptography", + 0, + wr.KEY_READ | wr.KEY_WOW64_64KEY, + ) as rk: + machineGuid, wrType = wr.QueryValueEx(rk, "MachineGuid") + if wrType == wr.REG_SZ: + return machineGuid.encode("utf-8") + else: + return machineGuid + except WindowsError: + pass + + _machine_id = rv = _generate() + return rv +``` + +## `src/werkzeug/debug/__init__.py` — `function:get_machine_id._generate` (lines 69-132) + +```python + def _generate(): + # docker containers share the same machine id, get the + # container id instead + try: + with open("/proc/self/cgroup") as f: + value = f.readline() + except IOError: + pass + else: + value = value.strip().partition("/docker/")[2] + + if value: + return value + + # Potential sources of secret information on linux. The machine-id + # is stable across boots, the boot id is not + for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id": + try: + with open(filename, "rb") as f: + return f.readline().strip() + except IOError: + continue + + # On OS X we can use the computer's serial number assuming that + # ioreg exists and can spit out that information. + try: + # Also catch import errors: subprocess may not be available, e.g. + # Google App Engine + # See https://github.com/pallets/werkzeug/issues/925 + from subprocess import Popen, PIPE + + dump = Popen( + ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE + ).communicate()[0] + match = re.search(b'"serial-number" = <([^>]+)', dump) + if match is not None: + return match.group(1) + except (OSError, ImportError): + pass + + # On Windows we can use winreg to get the machine guid + wr = None + try: + import winreg as wr + except ImportError: + try: + import _winreg as wr + except ImportError: + pass + if wr is not None: + try: + with wr.OpenKey( + wr.HKEY_LOCAL_MACHINE, + "SOFTWARE\\Microsoft\\Cryptography", + 0, + wr.KEY_READ | wr.KEY_WOW64_64KEY, + ) as rk: + machineGuid, wrType = wr.QueryValueEx(rk, "MachineGuid") + if wrType == wr.REG_SZ: + return machineGuid.encode("utf-8") + else: + return machineGuid + except WindowsError: + pass +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..b9f2e6b49829d0232c1018b81d73ed01d3814bad --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/pre_context.md @@ -0,0 +1,122 @@ +# Patch-overlapping Python context before the fix + +## `src/werkzeug/debug/__init__.py` — `function:get_machine_id` (lines 63-122) + +```python +def get_machine_id(): + global _machine_id + rv = _machine_id + if rv is not None: + return rv + + def _generate(): + # Potential sources of secret information on linux. The machine-id + # is stable across boots, the boot id is not + for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id": + try: + with open(filename, "rb") as f: + return f.readline().strip() + except IOError: + continue + + # On OS X we can use the computer's serial number assuming that + # ioreg exists and can spit out that information. + try: + # Also catch import errors: subprocess may not be available, e.g. + # Google App Engine + # See https://github.com/pallets/werkzeug/issues/925 + from subprocess import Popen, PIPE + + dump = Popen( + ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE + ).communicate()[0] + match = re.search(b'"serial-number" = <([^>]+)', dump) + if match is not None: + return match.group(1) + except (OSError, ImportError): + pass + + # On Windows we can use winreg to get the machine guid + wr = None + try: + import winreg as wr + except ImportError: + try: + import _winreg as wr + except ImportError: + pass + if wr is not None: + try: + with wr.OpenKey( + wr.HKEY_LOCAL_MACHINE, + "SOFTWARE\\Microsoft\\Cryptography", + 0, + wr.KEY_READ | wr.KEY_WOW64_64KEY, + ) as rk: + machineGuid, wrType = wr.QueryValueEx(rk, "MachineGuid") + if wrType == wr.REG_SZ: + return machineGuid.encode("utf-8") + else: + return machineGuid + except WindowsError: + pass + + _machine_id = rv = _generate() + return rv +``` + +## `src/werkzeug/debug/__init__.py` — `function:get_machine_id._generate` (lines 69-119) + +```python + def _generate(): + # Potential sources of secret information on linux. The machine-id + # is stable across boots, the boot id is not + for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id": + try: + with open(filename, "rb") as f: + return f.readline().strip() + except IOError: + continue + + # On OS X we can use the computer's serial number assuming that + # ioreg exists and can spit out that information. + try: + # Also catch import errors: subprocess may not be available, e.g. + # Google App Engine + # See https://github.com/pallets/werkzeug/issues/925 + from subprocess import Popen, PIPE + + dump = Popen( + ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE + ).communicate()[0] + match = re.search(b'"serial-number" = <([^>]+)', dump) + if match is not None: + return match.group(1) + except (OSError, ImportError): + pass + + # On Windows we can use winreg to get the machine guid + wr = None + try: + import winreg as wr + except ImportError: + try: + import _winreg as wr + except ImportError: + pass + if wr is not None: + try: + with wr.OpenKey( + wr.HKEY_LOCAL_MACHINE, + "SOFTWARE\\Microsoft\\Cryptography", + 0, + wr.KEY_READ | wr.KEY_WOW64_64KEY, + ) as rk: + machineGuid, wrType = wr.QueryValueEx(rk, "MachineGuid") + if wrType == wr.REG_SZ: + return machineGuid.encode("utf-8") + else: + return machineGuid + except WindowsError: + pass +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/task.json new file mode 100644 index 0000000000000000000000000000000000000000..94c609992f92876890046c14153c63ada68a7f44 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-9ba7c665889bf20611cb", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-9ba7c665889bf20611cb", + "project_id": "pyvul__pallets__werkzeug", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "src/werkzeug/debug/__init__.py" + ], + "patch_units": { + "before": [ + "function:get_machine_id", + "function:get_machine_id._generate" + ], + "after": [ + "function:get_machine_id", + "function:get_machine_id._generate" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/1449aa7784d4b07783fb1111d8f463b4becf78d2d00db67c65372c6aa04a4dce/database", + "cache_key": "1449aa7784d4b07783fb1111d8f463b4becf78d2d00db67c65372c6aa04a4dce", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/daa3e26f3f0e57abcda47df3745854184055e3581777c278ead5ae827f162a04/database", + "cache_key": "daa3e26f3f0e57abcda47df3745854184055e3581777c278ead5ae827f162a04", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/3b16ec96e9babf04d3f58ff58b33e90365d1f69ec05039dd4984d0784ee5a51d/database", + "cache_key": "3b16ec96e9babf04d3f58ff58b33e90365d1f69ec05039dd4984d0784ee5a51d", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-9ba7c665889bf20611cb/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-9ba7c665889bf20611cb/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9ba7c665889bf20611cb/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7f1d52366f9fb9e2b9fc1d54c41f30310a220b5d --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/patch.diff @@ -0,0 +1,40 @@ +diff --git a/dpaste/views.py b/dpaste/views.py +index 2e5fdff..123c12d 100644 +--- a/dpaste/views.py ++++ b/dpaste/views.py +@@ -13,6 +13,7 @@ from django.http import ( + from django.shortcuts import get_object_or_404, render + from django.urls import reverse + from django.utils import timezone ++from django.utils.html import escape + from django.utils.cache import add_never_cache_headers, patch_cache_control + from django.utils.translation import gettext + from django.views.generic import FormView +@@ -290,8 +291,7 @@ class APIView(View): + # A lexer is given, check if its valid at all + if lexer and lexer not in highlight.LEXER_KEYS: + return HttpResponseBadRequest( +- 'Invalid lexer "%s" given. Valid lexers are: %s' +- % (lexer, ", ".join(highlight.LEXER_KEYS)) ++ f'Invalid lexer choice "{escape(lexer)}" given. Valid lexer values are: {", ".join(highlight.LEXER_KEYS)}' + ) + + # No lexer is given, but we have a filename, try to get the lexer +@@ -308,9 +308,7 @@ class APIView(View): + expire_options = [str(i) for i in dict(config.EXPIRE_CHOICES)] + if expires not in expire_options: + return HttpResponseBadRequest( +- 'Invalid expire choice "{}" given. Valid values are: {}'.format( +- expires, ", ".join(expire_options) +- ) ++ f'Invalid expire choice "{escape(expires)}" given. Valid expire values are: {", ".join(expire_options)}' + ) + expires, expire_type = get_expire_values(expires) + else: +@@ -352,4 +350,4 @@ def handler500(request, template_name="dpaste/500.html"): + context.update(config.extra_template_context) + response = render(request, template_name, context, status=500) + add_never_cache_headers(response) +- return response ++ return response +\ No newline at end of file diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8397c6748c28c6f6d929a8069e780c4fddedd8b8 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/post_context.md @@ -0,0 +1,179 @@ +# Patch-overlapping Python context after the fix + +## `dpaste/views.py` — `class:APIView` (lines 240-331) + +```python +class APIView(View): + """ + API View + """ + + def _format_default(self, s): + """ + The default response is the snippet URL wrapped in quotes. + """ + base_url = config.get_base_url(request=self.request) + return f'"{base_url}{s.get_absolute_url()}"' + + def _format_url(self, s): + """ + The `url` format returns the snippet URL, + no quotes, but a linebreak at the end. + """ + base_url = config.get_base_url(request=self.request) + return f"{base_url}{s.get_absolute_url()}\n" + + def _format_json(self, s): + """ + The `json` format export. + """ + base_url = config.get_base_url(request=self.request) + return json.dumps( + { + "url": f"{base_url}{s.get_absolute_url()}", + "content": s.content, + "lexer": s.lexer, + } + ) + + def post(self, request, *args, **kwargs): + content = request.POST.get("content", "") + lexer = request.POST.get("lexer", highlight.LEXER_DEFAULT).strip() + filename = request.POST.get("filename", "").strip() + expires = request.POST.get("expires", "").strip() + response_format = request.POST.get("format", "default").strip() + + if not content.strip(): + return HttpResponseBadRequest("No content given") + + # We need at least a lexer or a filename + if not lexer and not filename: + return HttpResponseBadRequest( + "No lexer or filename given. Unable to " + "determine a highlight. Valid lexers are: %s" + % ", ".join(highlight.LEXER_KEYS) + ) + + # A lexer is given, check if its valid at all + if lexer and lexer not in highlight.LEXER_KEYS: + return HttpResponseBadRequest( + f'Invalid lexer choice "{escape(lexer)}" given. Valid lexer values are: {", ".join(highlight.LEXER_KEYS)}' + ) + + # No lexer is given, but we have a filename, try to get the lexer + # out of it. In case Pygments cannot determine the lexer of the + # filename, we fallback to 'plain' code. + if not lexer and filename: + try: + lexer_cls = get_lexer_for_filename(filename) + lexer = lexer_cls.aliases[0] + except (ClassNotFound, IndexError): + lexer = config.PLAIN_CODE_SYMBOL + + if expires: + expire_options = [str(i) for i in dict(config.EXPIRE_CHOICES)] + if expires not in expire_options: + return HttpResponseBadRequest( + f'Invalid expire choice "{escape(expires)}" given. Valid expire values are: {", ".join(expire_options)}' + ) + expires, expire_type = get_expire_values(expires) + else: + expires = datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24) + expire_type = Snippet.EXPIRE_TIME + + snippet = Snippet.objects.create( + content=content, + lexer=lexer, + expires=expires, + expire_type=expire_type, + ) + + # Custom formatter for the API response + formatter = getattr(self, f"_format_{response_format}", None) + if callable(formatter): + return HttpResponse(formatter(snippet)) + + # Otherwise use the default one. + return HttpResponse(self._format_default(snippet)) +``` + +## `dpaste/views.py` — `function:APIView.post` (lines 273-331) + +```python + def post(self, request, *args, **kwargs): + content = request.POST.get("content", "") + lexer = request.POST.get("lexer", highlight.LEXER_DEFAULT).strip() + filename = request.POST.get("filename", "").strip() + expires = request.POST.get("expires", "").strip() + response_format = request.POST.get("format", "default").strip() + + if not content.strip(): + return HttpResponseBadRequest("No content given") + + # We need at least a lexer or a filename + if not lexer and not filename: + return HttpResponseBadRequest( + "No lexer or filename given. Unable to " + "determine a highlight. Valid lexers are: %s" + % ", ".join(highlight.LEXER_KEYS) + ) + + # A lexer is given, check if its valid at all + if lexer and lexer not in highlight.LEXER_KEYS: + return HttpResponseBadRequest( + f'Invalid lexer choice "{escape(lexer)}" given. Valid lexer values are: {", ".join(highlight.LEXER_KEYS)}' + ) + + # No lexer is given, but we have a filename, try to get the lexer + # out of it. In case Pygments cannot determine the lexer of the + # filename, we fallback to 'plain' code. + if not lexer and filename: + try: + lexer_cls = get_lexer_for_filename(filename) + lexer = lexer_cls.aliases[0] + except (ClassNotFound, IndexError): + lexer = config.PLAIN_CODE_SYMBOL + + if expires: + expire_options = [str(i) for i in dict(config.EXPIRE_CHOICES)] + if expires not in expire_options: + return HttpResponseBadRequest( + f'Invalid expire choice "{escape(expires)}" given. Valid expire values are: {", ".join(expire_options)}' + ) + expires, expire_type = get_expire_values(expires) + else: + expires = datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24) + expire_type = Snippet.EXPIRE_TIME + + snippet = Snippet.objects.create( + content=content, + lexer=lexer, + expires=expires, + expire_type=expire_type, + ) + + # Custom formatter for the API response + formatter = getattr(self, f"_format_{response_format}", None) + if callable(formatter): + return HttpResponse(formatter(snippet)) + + # Otherwise use the default one. + return HttpResponse(self._format_default(snippet)) +``` + +## `dpaste/views.py` — `function:handler500` (lines 348-353) + +```python +def handler500(request, template_name="dpaste/500.html"): + context = {} + context.update(config.extra_template_context) + response = render(request, template_name, context, status=500) + add_never_cache_headers(response) + return response +``` + +## `dpaste/views.py` — `module:@16` (lines 16-16) + +```python +from django.utils.html import escape +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..ae51ceb38d0ad8b3b15fc4f79041fada4090a5e6 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/pre_context.md @@ -0,0 +1,185 @@ +# Patch-overlapping Python context before the fix + +## `dpaste/views.py` — `class:APIView` (lines 239-333) + +```python +class APIView(View): + """ + API View + """ + + def _format_default(self, s): + """ + The default response is the snippet URL wrapped in quotes. + """ + base_url = config.get_base_url(request=self.request) + return f'"{base_url}{s.get_absolute_url()}"' + + def _format_url(self, s): + """ + The `url` format returns the snippet URL, + no quotes, but a linebreak at the end. + """ + base_url = config.get_base_url(request=self.request) + return f"{base_url}{s.get_absolute_url()}\n" + + def _format_json(self, s): + """ + The `json` format export. + """ + base_url = config.get_base_url(request=self.request) + return json.dumps( + { + "url": f"{base_url}{s.get_absolute_url()}", + "content": s.content, + "lexer": s.lexer, + } + ) + + def post(self, request, *args, **kwargs): + content = request.POST.get("content", "") + lexer = request.POST.get("lexer", highlight.LEXER_DEFAULT).strip() + filename = request.POST.get("filename", "").strip() + expires = request.POST.get("expires", "").strip() + response_format = request.POST.get("format", "default").strip() + + if not content.strip(): + return HttpResponseBadRequest("No content given") + + # We need at least a lexer or a filename + if not lexer and not filename: + return HttpResponseBadRequest( + "No lexer or filename given. Unable to " + "determine a highlight. Valid lexers are: %s" + % ", ".join(highlight.LEXER_KEYS) + ) + + # A lexer is given, check if its valid at all + if lexer and lexer not in highlight.LEXER_KEYS: + return HttpResponseBadRequest( + 'Invalid lexer "%s" given. Valid lexers are: %s' + % (lexer, ", ".join(highlight.LEXER_KEYS)) + ) + + # No lexer is given, but we have a filename, try to get the lexer + # out of it. In case Pygments cannot determine the lexer of the + # filename, we fallback to 'plain' code. + if not lexer and filename: + try: + lexer_cls = get_lexer_for_filename(filename) + lexer = lexer_cls.aliases[0] + except (ClassNotFound, IndexError): + lexer = config.PLAIN_CODE_SYMBOL + + if expires: + expire_options = [str(i) for i in dict(config.EXPIRE_CHOICES)] + if expires not in expire_options: + return HttpResponseBadRequest( + 'Invalid expire choice "{}" given. Valid values are: {}'.format( + expires, ", ".join(expire_options) + ) + ) + expires, expire_type = get_expire_values(expires) + else: + expires = datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24) + expire_type = Snippet.EXPIRE_TIME + + snippet = Snippet.objects.create( + content=content, + lexer=lexer, + expires=expires, + expire_type=expire_type, + ) + + # Custom formatter for the API response + formatter = getattr(self, f"_format_{response_format}", None) + if callable(formatter): + return HttpResponse(formatter(snippet)) + + # Otherwise use the default one. + return HttpResponse(self._format_default(snippet)) +``` + +## `dpaste/views.py` — `function:APIView.post` (lines 272-333) + +```python + def post(self, request, *args, **kwargs): + content = request.POST.get("content", "") + lexer = request.POST.get("lexer", highlight.LEXER_DEFAULT).strip() + filename = request.POST.get("filename", "").strip() + expires = request.POST.get("expires", "").strip() + response_format = request.POST.get("format", "default").strip() + + if not content.strip(): + return HttpResponseBadRequest("No content given") + + # We need at least a lexer or a filename + if not lexer and not filename: + return HttpResponseBadRequest( + "No lexer or filename given. Unable to " + "determine a highlight. Valid lexers are: %s" + % ", ".join(highlight.LEXER_KEYS) + ) + + # A lexer is given, check if its valid at all + if lexer and lexer not in highlight.LEXER_KEYS: + return HttpResponseBadRequest( + 'Invalid lexer "%s" given. Valid lexers are: %s' + % (lexer, ", ".join(highlight.LEXER_KEYS)) + ) + + # No lexer is given, but we have a filename, try to get the lexer + # out of it. In case Pygments cannot determine the lexer of the + # filename, we fallback to 'plain' code. + if not lexer and filename: + try: + lexer_cls = get_lexer_for_filename(filename) + lexer = lexer_cls.aliases[0] + except (ClassNotFound, IndexError): + lexer = config.PLAIN_CODE_SYMBOL + + if expires: + expire_options = [str(i) for i in dict(config.EXPIRE_CHOICES)] + if expires not in expire_options: + return HttpResponseBadRequest( + 'Invalid expire choice "{}" given. Valid values are: {}'.format( + expires, ", ".join(expire_options) + ) + ) + expires, expire_type = get_expire_values(expires) + else: + expires = datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24) + expire_type = Snippet.EXPIRE_TIME + + snippet = Snippet.objects.create( + content=content, + lexer=lexer, + expires=expires, + expire_type=expire_type, + ) + + # Custom formatter for the API response + formatter = getattr(self, f"_format_{response_format}", None) + if callable(formatter): + return HttpResponse(formatter(snippet)) + + # Otherwise use the default one. + return HttpResponse(self._format_default(snippet)) +``` + +## `dpaste/views.py` — `function:handler500` (lines 350-355) + +```python +def handler500(request, template_name="dpaste/500.html"): + context = {} + context.update(config.extra_template_context) + response = render(request, template_name, context, status=500) + add_never_cache_headers(response) + return response +``` + +## `dpaste/views.py` — `module:@16` (lines 16-16) + +```python +from django.utils.cache import add_never_cache_headers, patch_cache_control +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/task.json new file mode 100644 index 0000000000000000000000000000000000000000..06221095a74b57f8ebdf57f8c0dcc1fbae34209d --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-9c089aba2c203455d420", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-9c089aba2c203455d420", + "project_id": "pyvul__darrenofficial__dpaste", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "dpaste/views.py" + ], + "patch_units": { + "before": [ + "class:APIView", + "function:APIView.post", + "function:handler500", + "module:@16" + ], + "after": [ + "class:APIView", + "function:APIView.post", + "function:handler500", + "module:@16" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/ab0891c1386d00c493bbb711ddba06d4e0960e3138869a8a1c16284d49eb3ca5/database", + "cache_key": "ab0891c1386d00c493bbb711ddba06d4e0960e3138869a8a1c16284d49eb3ca5", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/2e4a635bdf21b94f1c7683aeaefaa41132d4b1be900bccc03d85b5aa850cb742/database", + "cache_key": "2e4a635bdf21b94f1c7683aeaefaa41132d4b1be900bccc03d85b5aa850cb742", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/f49f3e663a246fec0f5c3319cf6c172a46de4f23c52307743cf641728d43078a/database", + "cache_key": "f49f3e663a246fec0f5c3319cf6c172a46de4f23c52307743cf641728d43078a", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-9c089aba2c203455d420/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-9c089aba2c203455d420/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9c089aba2c203455d420/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c4fe81a02334c1d6a3f777bc270187b60c00f191 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/patch.diff @@ -0,0 +1,22 @@ +diff --git a/ihatemoney/models.py b/ihatemoney/models.py +index fe7b519..5691c75 100644 +--- a/ihatemoney/models.py ++++ b/ihatemoney/models.py +@@ -380,7 +380,7 @@ class Person(db.Model): + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) +- .filter(Project.id == project.id) ++ .filter(Person.project_id == project.id) + .one() + ) + +@@ -389,7 +389,7 @@ class Person(db.Model): + project = g.project + return ( + Person.query.filter(Person.id == id) +- .filter(Project.id == project.id) ++ .filter(Person.project_id == project.id) + .one() + ) + diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8220d248cf82fd985a99d12396fcd1e2ad469142 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/post_context.md @@ -0,0 +1,107 @@ +# Patch-overlapping Python context after the fix + +## `ihatemoney/models.py` — `class:Person` (lines 378-433) + +```python +class Person(db.Model): + class PersonQuery(BaseQuery): + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) + .filter(Person.project_id == project.id) + .one() + ) + + def get(self, id, project=None): + if not project: + project = g.project + return ( + Person.query.filter(Person.id == id) + .filter(Person.project_id == project.id) + .one() + ) + + query_class = PersonQuery + + # Direct SQLAlchemy-Continuum to track changes to this model + __versioned__ = {} + + __table_args__ = {"sqlite_autoincrement": True} + + id = db.Column(db.Integer, primary_key=True) + project_id = db.Column(db.String(64), db.ForeignKey("project.id")) + bills = db.relationship("Bill", backref="payer") + + name = db.Column(db.UnicodeText) + weight = db.Column(db.Float, default=1) + activated = db.Column(db.Boolean, default=True) + + @property + def _to_serialize(self): + return { + "id": self.id, + "name": self.name, + "weight": self.weight, + "activated": self.activated, + } + + def has_bills(self): + """return if the user do have bills or not""" + bills_as_ower_number = ( + db.session.query(billowers) + .filter(billowers.columns.get("person_id") == self.id) + .count() + ) + return bills_as_ower_number != 0 or len(self.bills) != 0 + + def __str__(self): + return self.name + + def __repr__(self): + return f"" +``` + +## `ihatemoney/models.py` — `class:Person.PersonQuery` (lines 379-394) + +```python + class PersonQuery(BaseQuery): + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) + .filter(Person.project_id == project.id) + .one() + ) + + def get(self, id, project=None): + if not project: + project = g.project + return ( + Person.query.filter(Person.id == id) + .filter(Person.project_id == project.id) + .one() + ) +``` + +## `ihatemoney/models.py` — `function:Person.PersonQuery.get_by_name` (lines 380-385) + +```python + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) + .filter(Person.project_id == project.id) + .one() + ) +``` + +## `ihatemoney/models.py` — `function:Person.PersonQuery.get` (lines 387-394) + +```python + def get(self, id, project=None): + if not project: + project = g.project + return ( + Person.query.filter(Person.id == id) + .filter(Person.project_id == project.id) + .one() + ) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..20959cd1fedd87d17788567e1bbb3cceabd85e6a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/pre_context.md @@ -0,0 +1,107 @@ +# Patch-overlapping Python context before the fix + +## `ihatemoney/models.py` — `class:Person` (lines 378-433) + +```python +class Person(db.Model): + class PersonQuery(BaseQuery): + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) + .filter(Project.id == project.id) + .one() + ) + + def get(self, id, project=None): + if not project: + project = g.project + return ( + Person.query.filter(Person.id == id) + .filter(Project.id == project.id) + .one() + ) + + query_class = PersonQuery + + # Direct SQLAlchemy-Continuum to track changes to this model + __versioned__ = {} + + __table_args__ = {"sqlite_autoincrement": True} + + id = db.Column(db.Integer, primary_key=True) + project_id = db.Column(db.String(64), db.ForeignKey("project.id")) + bills = db.relationship("Bill", backref="payer") + + name = db.Column(db.UnicodeText) + weight = db.Column(db.Float, default=1) + activated = db.Column(db.Boolean, default=True) + + @property + def _to_serialize(self): + return { + "id": self.id, + "name": self.name, + "weight": self.weight, + "activated": self.activated, + } + + def has_bills(self): + """return if the user do have bills or not""" + bills_as_ower_number = ( + db.session.query(billowers) + .filter(billowers.columns.get("person_id") == self.id) + .count() + ) + return bills_as_ower_number != 0 or len(self.bills) != 0 + + def __str__(self): + return self.name + + def __repr__(self): + return f"" +``` + +## `ihatemoney/models.py` — `class:Person.PersonQuery` (lines 379-394) + +```python + class PersonQuery(BaseQuery): + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) + .filter(Project.id == project.id) + .one() + ) + + def get(self, id, project=None): + if not project: + project = g.project + return ( + Person.query.filter(Person.id == id) + .filter(Project.id == project.id) + .one() + ) +``` + +## `ihatemoney/models.py` — `function:Person.PersonQuery.get_by_name` (lines 380-385) + +```python + def get_by_name(self, name, project): + return ( + Person.query.filter(Person.name == name) + .filter(Project.id == project.id) + .one() + ) +``` + +## `ihatemoney/models.py` — `function:Person.PersonQuery.get` (lines 387-394) + +```python + def get(self, id, project=None): + if not project: + project = g.project + return ( + Person.query.filter(Person.id == id) + .filter(Project.id == project.id) + .one() + ) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/task.json new file mode 100644 index 0000000000000000000000000000000000000000..67517faa40e0cf3e69bdf0e3a2d0e833b26b198d --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-9dcb85347ac437354c6f", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-9dcb85347ac437354c6f", + "project_id": "pyvul__spiral-project__ihatemoney", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "ihatemoney/models.py" + ], + "patch_units": { + "before": [ + "class:Person", + "class:Person.PersonQuery", + "function:Person.PersonQuery.get_by_name", + "function:Person.PersonQuery.get" + ], + "after": [ + "class:Person", + "class:Person.PersonQuery", + "function:Person.PersonQuery.get_by_name", + "function:Person.PersonQuery.get" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/f4e621bc66ecb6cf8d794115e8783eea997e1f3cfe851195d5e84276de6e0794/database", + "cache_key": "f4e621bc66ecb6cf8d794115e8783eea997e1f3cfe851195d5e84276de6e0794", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/03264965946d82ef188b86242c3273ce6f2d80cad4ae65d91d941d6cc908d53f/database", + "cache_key": "03264965946d82ef188b86242c3273ce6f2d80cad4ae65d91d941d6cc908d53f", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/67adc1490f6bfb9d8b441f24b1db2dfb93e91d1bbed6aeed4d7cb4097a86343f/database", + "cache_key": "67adc1490f6bfb9d8b441f24b1db2dfb93e91d1bbed6aeed4d7cb4097a86343f", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-9dcb85347ac437354c6f/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-9dcb85347ac437354c6f/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-9dcb85347ac437354c6f/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cc6417839a30aeb25bc43281c8878f2066cbc73c --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/patch.diff @@ -0,0 +1,57 @@ +diff --git a/README.md b/README.md +index e4eddf7d..18f11d88 100644 +--- a/README.md ++++ b/README.md +@@ -107,6 +107,12 @@ Professional support for Rdiffweb is available by contacting [IKUS Soft](https:/ + + # Changelog + ++## 2.4.8 (2022-09-23) ++ ++This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately. ++ ++* Clean-up invalid path on error page ++ + ## 2.4.7 (2002-09-21) + + This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately. +diff --git a/rdiffweb/controller/tests/test_page_error.py b/rdiffweb/controller/tests/test_page_error.py +index 1b40b265..de38b956 100644 +--- a/rdiffweb/controller/tests/test_page_error.py ++++ b/rdiffweb/controller/tests/test_page_error.py +@@ -49,3 +49,20 @@ class ErrorPageTest(rdiffweb.test.WebCase): + self.assertInBody('Traceback (most recent call last):') + else: + self.assertNotInBody('Traceback (most recent call last):') ++ ++ def test_not_found(self): ++ # When user browser an invalid path. ++ self.getPage( ++ '/This%20website%20has%20been%20hacked%20and%20the%20confidential%20data%20of%20all%20users%20have%20been%20compromised%20and%20leaked%20to%20public' ++ ) ++ # Then an error page is return ++ self.assertStatus("404 Not Found") ++ # Then page doesn't make reference to the path. ++ if self.expect_stacktrace: ++ self.assertInBody( ++ 'This website has been hacked and the confidential data of all users have been compromised and leaked to public' ++ ) ++ else: ++ self.assertNotInBody( ++ 'This website has been hacked and the confidential data of all users have been compromised and leaked to public' ++ ) +diff --git a/rdiffweb/rdw_app.py b/rdiffweb/rdw_app.py +index 137e92e0..79b6c71b 100644 +--- a/rdiffweb/rdw_app.py ++++ b/rdiffweb/rdw_app.py +@@ -245,6 +245,10 @@ class RdiffwebApp(Application): + 'error page: %s %s\n%s' % (kwargs.get('status', ''), kwargs.get('message', ''), kwargs.get('traceback', '')) + ) + ++ # Replace message by generic one for 404. Default implementation leak path info. ++ if kwargs.get('status', '') == '404 Not Found': ++ kwargs['message'] = 'Nothing matches the given URI' ++ + # Check expected response type. + mtype = cherrypy.tools.accept.callable(['text/html', 'text/plain']) # @UndefinedVariable + if mtype == 'text/plain': diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..85ca5dd5b74cefb9aae9b4fc23c30ded3994dcb7 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/post_context.md @@ -0,0 +1,258 @@ +# Patch-overlapping Python context after the fix + +## `rdiffweb/controller/tests/test_page_error.py` — `class:ErrorPageTest` (lines 29-68) + +```python +class ErrorPageTest(rdiffweb.test.WebCase): + + login = True + + def test_error_page(self): + # Given a webserver started with production environment + # When error page is return + self.getPage('/invalid/') + # Then page doesn't contain a stack trace + self.assertStatus("404 Not Found") + self.assertInBody("Oops!") + if self.expect_stacktrace: + self.assertInBody('Traceback (most recent call last):') + else: + self.assertNotInBody('Traceback (most recent call last):') + + def test_not_found(self): + # When user browser an invalid path. + self.getPage( + '/This%20website%20has%20been%20hacked%20and%20the%20confidential%20data%20of%20all%20users%20have%20been%20compromised%20and%20leaked%20to%20public' + ) + # Then an error page is return + self.assertStatus("404 Not Found") + # Then page doesn't make reference to the path. + if self.expect_stacktrace: + self.assertInBody( + 'This website has been hacked and the confidential data of all users have been compromised and leaked to public' + ) + else: + self.assertNotInBody( + 'This website has been hacked and the confidential data of all users have been compromised and leaked to public' + ) +``` + +## `rdiffweb/controller/tests/test_page_error.py` — `function:ErrorPageTest.test_not_found` (lines 53-68) + +```python + def test_not_found(self): + # When user browser an invalid path. + self.getPage( + '/This%20website%20has%20been%20hacked%20and%20the%20confidential%20data%20of%20all%20users%20have%20been%20compromised%20and%20leaked%20to%20public' + ) + # Then an error page is return + self.assertStatus("404 Not Found") + # Then page doesn't make reference to the path. + if self.expect_stacktrace: + self.assertInBody( + 'This website has been hacked and the confidential data of all users have been compromised and leaked to public' + ) + else: + self.assertNotInBody( + 'This website has been hacked and the confidential data of all users have been compromised and leaked to public' + ) +``` + +## `rdiffweb/rdw_app.py` — `class:RdiffwebApp` (lines 107-270) + +```python +class RdiffwebApp(Application): + """This class represent the application context.""" + + _favicon = Option('favicon') + + _header_logo = Option('header_logo') + + _tempdir = Option('tempdir') + + _session_dir = Option('session_dir') + + @classmethod + def parse_args(cls, args=None, config_file_contents=None): + return parse_args(args, config_file_contents) + + def __init__(self, cfg): + self.cfg = cfg + cherrypy.config.update( + { + 'environment': 'development' if cfg.debug else cfg.environment, + # Configure LDAP plugin + 'ldap.uri': cfg.ldap_uri, + 'ldap.base_dn': cfg.ldap_base_dn, + 'ldap.bind_dn': cfg.ldap_bind_dn, + 'ldap.bind_password': cfg.ldap_bind_password, + 'ldap.scope': cfg.ldap_scope, + 'ldap.tls': cfg.ldap_tls, + 'ldap.username_attribute': cfg.ldap_username_attribute, + 'ldap.required_group': cfg.ldap_required_group, + 'ldap.group_attribute': cfg.ldap_group_attribute, + 'ldap.group_attribute_is_dn': cfg.ldap_group_attribute_is_dn, + 'ldap.version': cfg.ldap_version, + 'ldap.network_timeout': cfg.ldap_network_timeout, + 'ldap.timeout': cfg.ldap_timeout, + 'ldap.encoding': cfg.ldap_encoding, + # Configure SMTP plugin + 'smtp.server': cfg.email_host, + 'smtp.username': cfg.email_username, + 'smtp.password': cfg.email_password, + 'smtp.email_from': cfg.email_sender + and '%s <%s>' + % ( + cfg.header_name, + cfg.email_sender, + ), + 'smtp.encryption': cfg.email_encryption, + # Configure remove_older plugin + 'remove_older.execution_time': self.cfg.remove_older_time, + # Configure notification plugin + 'notification.execution_time': self.cfg.email_notification_time, + 'notification.send_changed': self.cfg.email_send_changed_notification, + # Configure quota plugin + 'quota.set_quota_cmd': self.cfg.quota_set_cmd, + 'quota.get_quota_cmd': self.cfg.quota_get_cmd, + 'quota.get_usage_cmd': self.cfg.quota_used_cmd, + } + ) + + # Initialise the template engine. + self.templates = rdw_templating.TemplateManager() + + # Pick the right implementation for storage + session_storage_class = cherrypy.lib.sessions.RamSession + rate_limit_storage_class = rdiffweb.tools.ratelimit.RamRateLimit + if self._session_dir: + session_storage_class = cherrypy.lib.sessions.FileSession + rate_limit_storage_class = rdiffweb.tools.ratelimit.FileRateLimit + + config = { + '/': { + # To work around the new behaviour in CherryPy >= 5.5.0, force usage of + # ISO-8859-1 encoding for URL. This avoid any conversion of the + # URL into UTF-8. + 'request.uri_encoding': 'ISO-8859-1', + 'tools.auth_basic.realm': 'rdiffweb', + 'tools.auth_basic.checkpassword': self._checkpassword, + 'tools.auth_form.on': True, + 'tools.currentuser.on': True, + 'tools.currentuser.userobj': lambda username: self.store.get_user(username), + 'tools.i18n.on': True, + 'tools.i18n.default': 'en_US', + 'tools.i18n.mo_dir': pkg_resources.resource_filename('rdiffweb', 'locales'), # @UndefinedVariable + 'tools.i18n.domain': 'messages', + 'tools.encode.on': True, + 'tools.encode.encoding': 'utf-8', + 'tools.gzip.on': True, + 'error_page.default': self.error_page, + 'tools.sessions.on': True, + 'tools.sessions.debug': cfg.debug, + 'tools.sessions.storage_class': session_storage_class, + 'tools.sessions.storage_path': self._session_dir, + 'tools.sessions.httponly': True, + 'tools.ratelimit.debug': cfg.debug, + 'tools.ratelimit.delay': 60, + 'tools.ratelimit.anonymous_limit': cfg.rate_limit, + 'tools.ratelimit.storage_class': rate_limit_storage_class, + 'tools.ratelimit.storage_path': self._session_dir, + }, + } + + # Initialize the application + Application.__init__(self, root=Root(), config=config) + + # Register favicon.ico + self.root.favicon_ico = static(self._favicon) + + # Register header_logo + if self._header_logo: + self.root.header_logo = static(self._header_logo) + + # Define TEMP env + if self._tempdir: + os.environ["TMPDIR"] = self._tempdir + + # create user manager + self.store = Store(self) + self.store.create_admin_user() + + @property + def currentuser(self): + """ + Proxy property to get current user from cherrypy request object. + Return a UserObject when logged in or None. + """ + return getattr(cherrypy.serving.request, 'currentuser', None) + + def _checkpassword(self, realm, username, password): + """ + Check basic authentication. + """ + return self.store.login(username, password) is not None + + def error_page(self, **kwargs): + """ + Default error page shown to the user when an unexpected error occur. + """ + # Log exception. + logger.error( + 'error page: %s %s\n%s' % (kwargs.get('status', ''), kwargs.get('message', ''), kwargs.get('traceback', '')) + ) + + # Replace message by generic one for 404. Default implementation leak path info. + if kwargs.get('status', '') == '404 Not Found': + kwargs['message'] = 'Nothing matches the given URI' + + # Check expected response type. + mtype = cherrypy.tools.accept.callable(['text/html', 'text/plain']) # @UndefinedVariable + if mtype == 'text/plain': + return kwargs.get('message') + + # Try to build a nice error page. + try: + page = Controller() + return page._compile_template('error_page_default.html', **kwargs) + except Exception: + # If failing, send the raw error message. + return kwargs.get('message') + + @property + def version(self): + """ + Get the current running version (using package info). + """ + return rdiffweb.__version__ +``` + +## `rdiffweb/rdw_app.py` — `function:RdiffwebApp.error_page` (lines 239-263) + +```python + def error_page(self, **kwargs): + """ + Default error page shown to the user when an unexpected error occur. + """ + # Log exception. + logger.error( + 'error page: %s %s\n%s' % (kwargs.get('status', ''), kwargs.get('message', ''), kwargs.get('traceback', '')) + ) + + # Replace message by generic one for 404. Default implementation leak path info. + if kwargs.get('status', '') == '404 Not Found': + kwargs['message'] = 'Nothing matches the given URI' + + # Check expected response type. + mtype = cherrypy.tools.accept.callable(['text/html', 'text/plain']) # @UndefinedVariable + if mtype == 'text/plain': + return kwargs.get('message') + + # Try to build a nice error page. + try: + page = Controller() + return page._compile_template('error_page_default.html', **kwargs) + except Exception: + # If failing, send the raw error message. + return kwargs.get('message') +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6c8fca237f3a110c824ef68fdc97fccafd18585a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/pre_context.md @@ -0,0 +1,192 @@ +# Patch-overlapping Python context before the fix + +## `rdiffweb/rdw_app.py` — `class:RdiffwebApp` (lines 107-266) + +```python +class RdiffwebApp(Application): + """This class represent the application context.""" + + _favicon = Option('favicon') + + _header_logo = Option('header_logo') + + _tempdir = Option('tempdir') + + _session_dir = Option('session_dir') + + @classmethod + def parse_args(cls, args=None, config_file_contents=None): + return parse_args(args, config_file_contents) + + def __init__(self, cfg): + self.cfg = cfg + cherrypy.config.update( + { + 'environment': 'development' if cfg.debug else cfg.environment, + # Configure LDAP plugin + 'ldap.uri': cfg.ldap_uri, + 'ldap.base_dn': cfg.ldap_base_dn, + 'ldap.bind_dn': cfg.ldap_bind_dn, + 'ldap.bind_password': cfg.ldap_bind_password, + 'ldap.scope': cfg.ldap_scope, + 'ldap.tls': cfg.ldap_tls, + 'ldap.username_attribute': cfg.ldap_username_attribute, + 'ldap.required_group': cfg.ldap_required_group, + 'ldap.group_attribute': cfg.ldap_group_attribute, + 'ldap.group_attribute_is_dn': cfg.ldap_group_attribute_is_dn, + 'ldap.version': cfg.ldap_version, + 'ldap.network_timeout': cfg.ldap_network_timeout, + 'ldap.timeout': cfg.ldap_timeout, + 'ldap.encoding': cfg.ldap_encoding, + # Configure SMTP plugin + 'smtp.server': cfg.email_host, + 'smtp.username': cfg.email_username, + 'smtp.password': cfg.email_password, + 'smtp.email_from': cfg.email_sender + and '%s <%s>' + % ( + cfg.header_name, + cfg.email_sender, + ), + 'smtp.encryption': cfg.email_encryption, + # Configure remove_older plugin + 'remove_older.execution_time': self.cfg.remove_older_time, + # Configure notification plugin + 'notification.execution_time': self.cfg.email_notification_time, + 'notification.send_changed': self.cfg.email_send_changed_notification, + # Configure quota plugin + 'quota.set_quota_cmd': self.cfg.quota_set_cmd, + 'quota.get_quota_cmd': self.cfg.quota_get_cmd, + 'quota.get_usage_cmd': self.cfg.quota_used_cmd, + } + ) + + # Initialise the template engine. + self.templates = rdw_templating.TemplateManager() + + # Pick the right implementation for storage + session_storage_class = cherrypy.lib.sessions.RamSession + rate_limit_storage_class = rdiffweb.tools.ratelimit.RamRateLimit + if self._session_dir: + session_storage_class = cherrypy.lib.sessions.FileSession + rate_limit_storage_class = rdiffweb.tools.ratelimit.FileRateLimit + + config = { + '/': { + # To work around the new behaviour in CherryPy >= 5.5.0, force usage of + # ISO-8859-1 encoding for URL. This avoid any conversion of the + # URL into UTF-8. + 'request.uri_encoding': 'ISO-8859-1', + 'tools.auth_basic.realm': 'rdiffweb', + 'tools.auth_basic.checkpassword': self._checkpassword, + 'tools.auth_form.on': True, + 'tools.currentuser.on': True, + 'tools.currentuser.userobj': lambda username: self.store.get_user(username), + 'tools.i18n.on': True, + 'tools.i18n.default': 'en_US', + 'tools.i18n.mo_dir': pkg_resources.resource_filename('rdiffweb', 'locales'), # @UndefinedVariable + 'tools.i18n.domain': 'messages', + 'tools.encode.on': True, + 'tools.encode.encoding': 'utf-8', + 'tools.gzip.on': True, + 'error_page.default': self.error_page, + 'tools.sessions.on': True, + 'tools.sessions.debug': cfg.debug, + 'tools.sessions.storage_class': session_storage_class, + 'tools.sessions.storage_path': self._session_dir, + 'tools.sessions.httponly': True, + 'tools.ratelimit.debug': cfg.debug, + 'tools.ratelimit.delay': 60, + 'tools.ratelimit.anonymous_limit': cfg.rate_limit, + 'tools.ratelimit.storage_class': rate_limit_storage_class, + 'tools.ratelimit.storage_path': self._session_dir, + }, + } + + # Initialize the application + Application.__init__(self, root=Root(), config=config) + + # Register favicon.ico + self.root.favicon_ico = static(self._favicon) + + # Register header_logo + if self._header_logo: + self.root.header_logo = static(self._header_logo) + + # Define TEMP env + if self._tempdir: + os.environ["TMPDIR"] = self._tempdir + + # create user manager + self.store = Store(self) + self.store.create_admin_user() + + @property + def currentuser(self): + """ + Proxy property to get current user from cherrypy request object. + Return a UserObject when logged in or None. + """ + return getattr(cherrypy.serving.request, 'currentuser', None) + + def _checkpassword(self, realm, username, password): + """ + Check basic authentication. + """ + return self.store.login(username, password) is not None + + def error_page(self, **kwargs): + """ + Default error page shown to the user when an unexpected error occur. + """ + # Log exception. + logger.error( + 'error page: %s %s\n%s' % (kwargs.get('status', ''), kwargs.get('message', ''), kwargs.get('traceback', '')) + ) + + # Check expected response type. + mtype = cherrypy.tools.accept.callable(['text/html', 'text/plain']) # @UndefinedVariable + if mtype == 'text/plain': + return kwargs.get('message') + + # Try to build a nice error page. + try: + page = Controller() + return page._compile_template('error_page_default.html', **kwargs) + except Exception: + # If failing, send the raw error message. + return kwargs.get('message') + + @property + def version(self): + """ + Get the current running version (using package info). + """ + return rdiffweb.__version__ +``` + +## `rdiffweb/rdw_app.py` — `function:RdiffwebApp.error_page` (lines 239-259) + +```python + def error_page(self, **kwargs): + """ + Default error page shown to the user when an unexpected error occur. + """ + # Log exception. + logger.error( + 'error page: %s %s\n%s' % (kwargs.get('status', ''), kwargs.get('message', ''), kwargs.get('traceback', '')) + ) + + # Check expected response type. + mtype = cherrypy.tools.accept.callable(['text/html', 'text/plain']) # @UndefinedVariable + if mtype == 'text/plain': + return kwargs.get('message') + + # Try to build a nice error page. + try: + page = Controller() + return page._compile_template('error_page_default.html', **kwargs) + except Exception: + # If failing, send the raw error message. + return kwargs.get('message') +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cd70f40ec7b7d9bd0bf898a550ee225ea9c04fcb --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/task.json @@ -0,0 +1,49 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-a2d122cb9e3a61ddca7a", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-a2d122cb9e3a61ddca7a", + "project_id": "pyvul__ikus060__rdiffweb", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "rdiffweb/controller/tests/test_page_error.py", + "rdiffweb/rdw_app.py" + ], + "patch_units": { + "before": [ + "class:RdiffwebApp", + "function:RdiffwebApp.error_page" + ], + "after": [ + "class:ErrorPageTest", + "function:ErrorPageTest.test_not_found", + "class:RdiffwebApp", + "function:RdiffwebApp.error_page" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/1bbc0f2eaf459286bf8717e1c2803731fc8f5db7e9045d6a7c32950d5b173bfb/database", + "cache_key": "1bbc0f2eaf459286bf8717e1c2803731fc8f5db7e9045d6a7c32950d5b173bfb", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/720cf9e9f37e2c47361fd1b637852c71f850fff353553108d449a11a9503c15e/database", + "cache_key": "720cf9e9f37e2c47361fd1b637852c71f850fff353553108d449a11a9503c15e", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/1b8f80f5c99bf916a656f03c56b87928f4c2202ce53851102eff56ffb3a1c99d/database", + "cache_key": "1b8f80f5c99bf916a656f03c56b87928f4c2202ce53851102eff56ffb3a1c99d", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-a2d122cb9e3a61ddca7a/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-a2d122cb9e3a61ddca7a/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a2d122cb9e3a61ddca7a/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a7394fc0240955ba9c121120cc537f6958cd8feb --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/patch.diff @@ -0,0 +1,88 @@ +diff --git a/Tests/images/ossfuzz-4836216264589312.pcx b/Tests/images/ossfuzz-4836216264589312.pcx +new file mode 100644 +index 0000000000000000000000000000000000000000..fdde9716a0cbd84900f9499c2f8c6d13067d456a +GIT binary patch +literal 129 +wcmd;LP+(+WP*4Ej|6rg11t1QLjY`90z%&y`Cj@}_2tCMbm "7.0.0" + +- def test_overrun(self): +- """For overrun completeness, test as: +- valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c +- """ +- for file in [ ++ @pytest.mark.parametrize("path", [ + "fli_overrun.bin", + "sgi_overrun.bin", + "sgi_overrun_expandrow.bin", + "sgi_overrun_expandrow2.bin", + "pcx_overrun.bin", + "pcx_overrun2.bin", ++ "ossfuzz-4836216264589312.pcx", + "01r_00.pcx", +- ]: +- with Image.open(os.path.join("Tests/images", file)) as im: +- try: +- im.load() +- assert False +- except OSError as e: +- assert str(e) == "buffer overrun when reading image file" ++ ]) ++ def test_overrun(self, path): ++ """For overrun completeness, test as: ++ valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c ++ """ ++ with Image.open(os.path.join("Tests/images", path)) as im: ++ try: ++ im.load() ++ assert False ++ except OSError as e: ++ assert (str(e) == "buffer overrun when reading image file" or ++ "image file is truncated" in str(e)) + ++ def test_fli_overrun2(self): + with Image.open("Tests/images/fli_overrun2.bin") as im: + try: + im.seek(1) +diff --git a/src/PIL/PcxImagePlugin.py b/src/PIL/PcxImagePlugin.py +index b337b7dde..a24d44b42 100644 +--- a/src/PIL/PcxImagePlugin.py ++++ b/src/PIL/PcxImagePlugin.py +@@ -66,13 +66,13 @@ class PcxImageFile(ImageFile.ImageFile): + version = s[1] + bits = s[3] + planes = s[65] +- stride = i16(s, 66) ++ ignored_stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, +- stride, ++ ignored_stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) +@@ -110,6 +110,11 @@ class PcxImageFile(ImageFile.ImageFile): + self.mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + ++ # don't trust the passed in stride. Calculate for ourselves. ++ # CVE-2020-35655 ++ stride = (self._size[0] * bits + 7) // 8 ++ stride += stride % 2 ++ + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..1e7bf4b406e4c33f7a3e3044087fc25b45af3ef7 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/post_context.md @@ -0,0 +1,987 @@ +# Patch-overlapping Python context after the fix + +## `Tests/test_image.py` — `class:TestImage` (lines 21-818) + +```python +class TestImage: + def test_image_modes_success(self): + for mode in [ + "1", + "P", + "PA", + "L", + "LA", + "La", + "F", + "I", + "I;16", + "I;16L", + "I;16B", + "I;16N", + "RGB", + "RGBX", + "RGBA", + "RGBa", + "CMYK", + "YCbCr", + "LAB", + "HSV", + ]: + Image.new(mode, (1, 1)) + + def test_image_modes_fail(self): + for mode in [ + "", + "bad", + "very very long", + "BGR;15", + "BGR;16", + "BGR;24", + "BGR;32", + ]: + with pytest.raises(ValueError) as e: + Image.new(mode, (1, 1)) + assert str(e.value) == "unrecognized image mode" + + def test_exception_inheritance(self): + assert issubclass(UnidentifiedImageError, OSError) + + def test_sanity(self): + + im = Image.new("L", (100, 100)) + assert repr(im)[:45] == "= 7 + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION < "9.9.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION <= "9.9.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION != "7.0.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION >= "7.0.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION > "7.0.0" + + @pytest.mark.parametrize("path", [ + "fli_overrun.bin", + "sgi_overrun.bin", + "sgi_overrun_expandrow.bin", + "sgi_overrun_expandrow2.bin", + "pcx_overrun.bin", + "pcx_overrun2.bin", + "ossfuzz-4836216264589312.pcx", + "01r_00.pcx", + ]) + def test_overrun(self, path): + """For overrun completeness, test as: + valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c + """ + with Image.open(os.path.join("Tests/images", path)) as im: + try: + im.load() + assert False + except OSError as e: + assert (str(e) == "buffer overrun when reading image file" or + "image file is truncated" in str(e)) + + def test_fli_overrun2(self): + with Image.open("Tests/images/fli_overrun2.bin") as im: + try: + im.seek(1) + assert False + except OSError as e: + assert str(e) == "buffer overrun when reading image file" + + def test_show_deprecation(self, monkeypatch): + monkeypatch.setattr(Image, "_show", lambda *args, **kwargs: None) + + im = Image.new("RGB", (50, 50), "white") + + with pytest.warns(None) as raised: + im.show() + assert not raised + + with pytest.warns(DeprecationWarning): + im.show(command="mock") +``` + +## `Tests/test_image.py` — `function:TestImage.test_overrun` (lines 778-798) + +```python + def test_overrun(self, path): + """For overrun completeness, test as: + valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c + """ + with Image.open(os.path.join("Tests/images", path)) as im: + try: + im.load() + assert False + except OSError as e: + assert (str(e) == "buffer overrun when reading image file" or + "image file is truncated" in str(e)) +``` + +## `Tests/test_image.py` — `function:TestImage.test_fli_overrun2` (lines 800-806) + +```python + def test_fli_overrun2(self): + with Image.open("Tests/images/fli_overrun2.bin") as im: + try: + im.seek(1) + assert False + except OSError as e: + assert str(e) == "buffer overrun when reading image file" +``` + +## `src/PIL/PcxImagePlugin.py` — `class:PcxImageFile` (lines 47-121) + +```python +class PcxImageFile(ImageFile.ImageFile): + + format = "PCX" + format_description = "Paintbrush" + + def _open(self): + + # header + s = self.fp.read(128) + if not _accept(s): + raise SyntaxError("not a PCX file") + + # image + bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 + if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: + raise SyntaxError("bad PCX image size") + logger.debug("BBox: %s %s %s %s", *bbox) + + # format + version = s[1] + bits = s[3] + planes = s[65] + ignored_stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, + ignored_stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) + + if bits == 1 and planes == 1: + mode = rawmode = "1" + + elif bits == 1 and planes in (2, 4): + mode = "P" + rawmode = "P;%dL" % planes + self.palette = ImagePalette.raw("RGB", s[16:64]) + + elif version == 5 and bits == 8 and planes == 1: + mode = rawmode = "L" + # FIXME: hey, this doesn't work with the incremental loader !!! + self.fp.seek(-769, io.SEEK_END) + s = self.fp.read(769) + if len(s) == 769 and s[0] == 12: + # check if the palette is linear greyscale + for i in range(256): + if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: + mode = rawmode = "P" + break + if mode == "P": + self.palette = ImagePalette.raw("RGB", s[1:]) + self.fp.seek(128) + + elif version == 5 and bits == 8 and planes == 3: + mode = "RGB" + rawmode = "RGB;L" + + else: + raise OSError("unknown PCX mode") + + self.mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + + # don't trust the passed in stride. Calculate for ourselves. + # CVE-2020-35655 + stride = (self._size[0] * bits + 7) // 8 + stride += stride % 2 + + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + + self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] +``` + +## `src/PIL/PcxImagePlugin.py` — `function:PcxImageFile._open` (lines 52-121) + +```python + def _open(self): + + # header + s = self.fp.read(128) + if not _accept(s): + raise SyntaxError("not a PCX file") + + # image + bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 + if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: + raise SyntaxError("bad PCX image size") + logger.debug("BBox: %s %s %s %s", *bbox) + + # format + version = s[1] + bits = s[3] + planes = s[65] + ignored_stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, + ignored_stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) + + if bits == 1 and planes == 1: + mode = rawmode = "1" + + elif bits == 1 and planes in (2, 4): + mode = "P" + rawmode = "P;%dL" % planes + self.palette = ImagePalette.raw("RGB", s[16:64]) + + elif version == 5 and bits == 8 and planes == 1: + mode = rawmode = "L" + # FIXME: hey, this doesn't work with the incremental loader !!! + self.fp.seek(-769, io.SEEK_END) + s = self.fp.read(769) + if len(s) == 769 and s[0] == 12: + # check if the palette is linear greyscale + for i in range(256): + if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: + mode = rawmode = "P" + break + if mode == "P": + self.palette = ImagePalette.raw("RGB", s[1:]) + self.fp.seek(128) + + elif version == 5 and bits == 8 and planes == 3: + mode = "RGB" + rawmode = "RGB;L" + + else: + raise OSError("unknown PCX mode") + + self.mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + + # don't trust the passed in stride. Calculate for ourselves. + # CVE-2020-35655 + stride = (self._size[0] * bits + 7) // 8 + stride += stride % 2 + + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + + self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..2535bf30d1bf14a133414dfe655ca94ad4339550 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/pre_context.md @@ -0,0 +1,977 @@ +# Patch-overlapping Python context before the fix + +## `Tests/test_image.py` — `class:TestImage` (lines 21-815) + +```python +class TestImage: + def test_image_modes_success(self): + for mode in [ + "1", + "P", + "PA", + "L", + "LA", + "La", + "F", + "I", + "I;16", + "I;16L", + "I;16B", + "I;16N", + "RGB", + "RGBX", + "RGBA", + "RGBa", + "CMYK", + "YCbCr", + "LAB", + "HSV", + ]: + Image.new(mode, (1, 1)) + + def test_image_modes_fail(self): + for mode in [ + "", + "bad", + "very very long", + "BGR;15", + "BGR;16", + "BGR;24", + "BGR;32", + ]: + with pytest.raises(ValueError) as e: + Image.new(mode, (1, 1)) + assert str(e.value) == "unrecognized image mode" + + def test_exception_inheritance(self): + assert issubclass(UnidentifiedImageError, OSError) + + def test_sanity(self): + + im = Image.new("L", (100, 100)) + assert repr(im)[:45] == "= 7 + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION < "9.9.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION <= "9.9.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION != "7.0.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION >= "7.0.0" + + with pytest.warns(DeprecationWarning): + assert test_module.PILLOW_VERSION > "7.0.0" + + def test_overrun(self): + """For overrun completeness, test as: + valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c + """ + for file in [ + "fli_overrun.bin", + "sgi_overrun.bin", + "sgi_overrun_expandrow.bin", + "sgi_overrun_expandrow2.bin", + "pcx_overrun.bin", + "pcx_overrun2.bin", + "01r_00.pcx", + ]: + with Image.open(os.path.join("Tests/images", file)) as im: + try: + im.load() + assert False + except OSError as e: + assert str(e) == "buffer overrun when reading image file" + + with Image.open("Tests/images/fli_overrun2.bin") as im: + try: + im.seek(1) + assert False + except OSError as e: + assert str(e) == "buffer overrun when reading image file" + + def test_show_deprecation(self, monkeypatch): + monkeypatch.setattr(Image, "_show", lambda *args, **kwargs: None) + + im = Image.new("RGB", (50, 50), "white") + + with pytest.warns(None) as raised: + im.show() + assert not raised + + with pytest.warns(DeprecationWarning): + im.show(command="mock") +``` + +## `Tests/test_image.py` — `function:TestImage.test_overrun` (lines 778-803) + +```python + def test_overrun(self): + """For overrun completeness, test as: + valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c + """ + for file in [ + "fli_overrun.bin", + "sgi_overrun.bin", + "sgi_overrun_expandrow.bin", + "sgi_overrun_expandrow2.bin", + "pcx_overrun.bin", + "pcx_overrun2.bin", + "01r_00.pcx", + ]: + with Image.open(os.path.join("Tests/images", file)) as im: + try: + im.load() + assert False + except OSError as e: + assert str(e) == "buffer overrun when reading image file" + + with Image.open("Tests/images/fli_overrun2.bin") as im: + try: + im.seek(1) + assert False + except OSError as e: + assert str(e) == "buffer overrun when reading image file" +``` + +## `src/PIL/PcxImagePlugin.py` — `class:PcxImageFile` (lines 47-116) + +```python +class PcxImageFile(ImageFile.ImageFile): + + format = "PCX" + format_description = "Paintbrush" + + def _open(self): + + # header + s = self.fp.read(128) + if not _accept(s): + raise SyntaxError("not a PCX file") + + # image + bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 + if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: + raise SyntaxError("bad PCX image size") + logger.debug("BBox: %s %s %s %s", *bbox) + + # format + version = s[1] + bits = s[3] + planes = s[65] + stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, + stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) + + if bits == 1 and planes == 1: + mode = rawmode = "1" + + elif bits == 1 and planes in (2, 4): + mode = "P" + rawmode = "P;%dL" % planes + self.palette = ImagePalette.raw("RGB", s[16:64]) + + elif version == 5 and bits == 8 and planes == 1: + mode = rawmode = "L" + # FIXME: hey, this doesn't work with the incremental loader !!! + self.fp.seek(-769, io.SEEK_END) + s = self.fp.read(769) + if len(s) == 769 and s[0] == 12: + # check if the palette is linear greyscale + for i in range(256): + if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: + mode = rawmode = "P" + break + if mode == "P": + self.palette = ImagePalette.raw("RGB", s[1:]) + self.fp.seek(128) + + elif version == 5 and bits == 8 and planes == 3: + mode = "RGB" + rawmode = "RGB;L" + + else: + raise OSError("unknown PCX mode") + + self.mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + + self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] +``` + +## `src/PIL/PcxImagePlugin.py` — `function:PcxImageFile._open` (lines 52-116) + +```python + def _open(self): + + # header + s = self.fp.read(128) + if not _accept(s): + raise SyntaxError("not a PCX file") + + # image + bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 + if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: + raise SyntaxError("bad PCX image size") + logger.debug("BBox: %s %s %s %s", *bbox) + + # format + version = s[1] + bits = s[3] + planes = s[65] + stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, + stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) + + if bits == 1 and planes == 1: + mode = rawmode = "1" + + elif bits == 1 and planes in (2, 4): + mode = "P" + rawmode = "P;%dL" % planes + self.palette = ImagePalette.raw("RGB", s[16:64]) + + elif version == 5 and bits == 8 and planes == 1: + mode = rawmode = "L" + # FIXME: hey, this doesn't work with the incremental loader !!! + self.fp.seek(-769, io.SEEK_END) + s = self.fp.read(769) + if len(s) == 769 and s[0] == 12: + # check if the palette is linear greyscale + for i in range(256): + if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: + mode = rawmode = "P" + break + if mode == "P": + self.palette = ImagePalette.raw("RGB", s[1:]) + self.fp.seek(128) + + elif version == 5 and bits == 8 and planes == 3: + mode = "RGB" + rawmode = "RGB;L" + + else: + raise OSError("unknown PCX mode") + + self.mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + + self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9c977200b15cdc7fad5c8d1309fdac0f6c5d020a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/task.json @@ -0,0 +1,52 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-a44d900bae2c75f9ea8d", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-a44d900bae2c75f9ea8d", + "project_id": "pyvul__python-pillow__pillow", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "Tests/test_image.py", + "src/PIL/PcxImagePlugin.py" + ], + "patch_units": { + "before": [ + "class:TestImage", + "function:TestImage.test_overrun", + "class:PcxImageFile", + "function:PcxImageFile._open" + ], + "after": [ + "class:TestImage", + "function:TestImage.test_overrun", + "function:TestImage.test_fli_overrun2", + "class:PcxImageFile", + "function:PcxImageFile._open" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/03c787c8a545c86aedafc83abe89ad760a2a2d3e5e1fe7b2fa3ce0f59e429adb/database", + "cache_key": "03c787c8a545c86aedafc83abe89ad760a2a2d3e5e1fe7b2fa3ce0f59e429adb", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/093c0114ac26dd65fe3d033efd8642df24577eeb3bdff33318a1374f7143cc17/database", + "cache_key": "093c0114ac26dd65fe3d033efd8642df24577eeb3bdff33318a1374f7143cc17", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/1b75f9f34c7dc5dd3901491db7adf822d336c5bfecba61f3ef670d0e0cc843d6/database", + "cache_key": "1b75f9f34c7dc5dd3901491db7adf822d336c5bfecba61f3ef670d0e0cc843d6", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-a44d900bae2c75f9ea8d/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-a44d900bae2c75f9ea8d/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-a44d900bae2c75f9ea8d/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4997bfd35d3825707bfb77bf03b606f99cabcd08 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/patch.diff @@ -0,0 +1,30 @@ +diff --git a/thefuck/rules/dirty_untar.py b/thefuck/rules/dirty_untar.py +index d94958b..638aa87 100644 +--- a/thefuck/rules/dirty_untar.py ++++ b/thefuck/rules/dirty_untar.py +@@ -41,6 +41,10 @@ def get_new_command(command): + def side_effect(old_cmd, command): + with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive: + for file in archive.getnames(): ++ if not os.path.abspath(file).startswith(os.getcwd()): ++ # it's unsafe to overwrite files outside of the current directory ++ continue ++ + try: + os.remove(file) + except OSError: +diff --git a/thefuck/rules/dirty_unzip.py b/thefuck/rules/dirty_unzip.py +index 5369dea..6b50798 100644 +--- a/thefuck/rules/dirty_unzip.py ++++ b/thefuck/rules/dirty_unzip.py +@@ -45,6 +45,10 @@ def get_new_command(command): + def side_effect(old_cmd, command): + with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive: + for file in archive.namelist(): ++ if not os.path.abspath(file).startswith(os.getcwd()): ++ # it's unsafe to overwrite files outside of the current directory ++ continue ++ + try: + os.remove(file) + except OSError: diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6f344ace50dac713d7c78f965c4eeff57bbdd2eb --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/post_context.md @@ -0,0 +1,37 @@ +# Patch-overlapping Python context after the fix + +## `thefuck/rules/dirty_untar.py` — `function:side_effect` (lines 41-53) + +```python +def side_effect(old_cmd, command): + with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive: + for file in archive.getnames(): + if not os.path.abspath(file).startswith(os.getcwd()): + # it's unsafe to overwrite files outside of the current directory + continue + + try: + os.remove(file) + except OSError: + # does not try to remove directories as we cannot know if they + # already existed before + pass +``` + +## `thefuck/rules/dirty_unzip.py` — `function:side_effect` (lines 45-57) + +```python +def side_effect(old_cmd, command): + with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive: + for file in archive.namelist(): + if not os.path.abspath(file).startswith(os.getcwd()): + # it's unsafe to overwrite files outside of the current directory + continue + + try: + os.remove(file) + except OSError: + # does not try to remove directories as we cannot know if they + # already existed before + pass +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..0db6164e0f94b613efb8e2939a8b0b3e5f467f47 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/pre_context.md @@ -0,0 +1,29 @@ +# Patch-overlapping Python context before the fix + +## `thefuck/rules/dirty_untar.py` — `function:side_effect` (lines 41-49) + +```python +def side_effect(old_cmd, command): + with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive: + for file in archive.getnames(): + try: + os.remove(file) + except OSError: + # does not try to remove directories as we cannot know if they + # already existed before + pass +``` + +## `thefuck/rules/dirty_unzip.py` — `function:side_effect` (lines 45-53) + +```python +def side_effect(old_cmd, command): + with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive: + for file in archive.namelist(): + try: + os.remove(file) + except OSError: + # does not try to remove directories as we cannot know if they + # already existed before + pass +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/task.json new file mode 100644 index 0000000000000000000000000000000000000000..27cfa8e852c319ffa189e4f3efa0b66e354d9ec0 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/task.json @@ -0,0 +1,47 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-b10e0389c54d164db5b4", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-b10e0389c54d164db5b4", + "project_id": "pyvul__nvbn__thefuck", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "thefuck/rules/dirty_untar.py", + "thefuck/rules/dirty_unzip.py" + ], + "patch_units": { + "before": [ + "function:side_effect", + "function:side_effect" + ], + "after": [ + "function:side_effect", + "function:side_effect" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/0e839fea9262753ad50d7f0df82cd74903407c550f13ac05aa69b64aa92e54bb/database", + "cache_key": "0e839fea9262753ad50d7f0df82cd74903407c550f13ac05aa69b64aa92e54bb", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/d333f9d38f152e15538a8b25f312de6902f750fa40f902959609f1067be6d9ac/database", + "cache_key": "d333f9d38f152e15538a8b25f312de6902f750fa40f902959609f1067be6d9ac", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/4b74d846fd4f46214f8c27c298f92b4fb8059b7ef8312cad0fd5a8911ee2dae3/database", + "cache_key": "4b74d846fd4f46214f8c27c298f92b4fb8059b7ef8312cad0fd5a8911ee2dae3", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-b10e0389c54d164db5b4/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-b10e0389c54d164db5b4/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b10e0389c54d164db5b4/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cb78876e81a8fbb48da3d6fe52175567b8db8f21 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/patch.diff @@ -0,0 +1,82 @@ +diff --git a/rply/parsergenerator.py b/rply/parsergenerator.py +index f2ed8ee..995f78e 100644 +--- a/rply/parsergenerator.py ++++ b/rply/parsergenerator.py +@@ -8,6 +8,8 @@ import sys + import tempfile + import warnings + ++from appdirs import AppDirs ++ + from rply.errors import ParserGeneratorError, ParserGeneratorWarning + from rply.grammar import Grammar + from rply.parser import LRParser +@@ -175,44 +177,28 @@ class ParserGenerator(object): + g.compute_first() + g.compute_follow() + +- # win32 temp directories are already per-user +- if os.name == "nt": +- cache_file = os.path.join( +- tempfile.gettempdir(), +- "rply-%s-%s-%s.json" % ( +- self.VERSION, self.cache_id, self.compute_grammar_hash(g) +- ) +- ) +- else: +- cache_file = os.path.join( +- tempfile.gettempdir(), +- "rply-%s-%s-%s-%s.json" % ( +- self.VERSION, +- os.getuid(), +- self.cache_id, +- self.compute_grammar_hash(g) +- ) ++ cache_dir = AppDirs("rply").user_cache_dir ++ cache_file = os.path.join( ++ cache_dir, ++ "rply-%s-%s-%s.json" % ( ++ self.VERSION, self.cache_id, self.compute_grammar_hash(g) + ) ++ ) ++ + table = None + if os.path.exists(cache_file): + with open(cache_file) as f: + data = json.load(f) +- stat_result = os.fstat(f.fileno()) +- if ( +- os.name == "nt" or ( +- stat_result.st_uid == os.getuid() and +- stat.S_IMODE(stat_result.st_mode) == 0o0600 +- ) +- ): +- if self.data_is_valid(g, data): +- table = LRTable.from_cache(g, data) ++ if self.data_is_valid(g, data): ++ table = LRTable.from_cache(g, data) + if table is None: + table = LRTable.from_grammar(g) +- fd = os.open( +- cache_file, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o0600 +- ) +- with os.fdopen(fd, "w") as f: ++ if not os.path.exists(cache_dir): ++ os.makedirs(cache_dir) ++ ++ with open(cache_file, "w") as f: + json.dump(self.serialize_table(table), f) ++ + if table.sr_conflicts: + warnings.warn( + "%d shift/reduce conflict%s" % ( +diff --git a/setup.py b/setup.py +index df6af7e..1072f5e 100644 +--- a/setup.py ++++ b/setup.py +@@ -13,4 +13,5 @@ setup( + author="Alex Gaynor", + author_email="alex.gaynor@gmail.com", + packages=["rply"], ++ install_requires=["appdirs"], + ) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..e80b7f22f24bbbb43088310ab176c832337b0b46 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/post_context.md @@ -0,0 +1,302 @@ +# Patch-overlapping Python context after the fix + +## `rply/parsergenerator.py` — `class:ParserGenerator` (lines 22-220) + +```python +class ParserGenerator(object): + """ + A ParserGenerator represents a set of production rules, that define a + sequence of terminals and non-terminals to be replaced with a non-terminal, + which can be turned into a parser. + + :param tokens: A list of token (non-terminal) names. + :param precedence: A list of tuples defining the order of operation for + avoiding ambiguity, consisting of a string defining + associativity (left, right or nonassoc) and a list of + token names with the same associativity and level of + precedence. + :param cache_id: A string specifying an ID for caching. + """ + VERSION = 1 + + def __init__(self, tokens, precedence=[], cache_id=None): + self.tokens = tokens + self.productions = [] + self.precedence = precedence + if cache_id is None: + # This ensures that we always go through the caching code. + cache_id = "".join(random.choice(string.ascii_letters) for _ in range(6)) + self.cache_id = cache_id + self.error_handler = None + + def production(self, rule, precedence=None): + """ + A decorator that defines a production rule and registers the decorated + function to be called with the terminals and non-terminals matched by + that rule. + + A `rule` should consist of a name defining the non-terminal returned + by the decorated function and a sequence of non-terminals and terminals + that are supposed to be replaced:: + + replacing_non_terminal : ATERMINAL non_terminal + + The name of the non-terminal replacing the sequence is on the left, + separated from the sequence by a colon. The whitespace around the colon + is required. + + Knowing this we can define productions:: + + pg = ParserGenerator(['NUMBER', 'ADD']) + + @pg.production('number : NUMBER') + def expr_number(p): + return BoxInt(int(p[0].getstr())) + + @pg.production('expr : number ADD number') + def expr_add(p): + return BoxInt(p[0].getint() + p[2].getint()) + + If a state was passed to the parser, the decorated function is + additionally called with that state as first argument. + """ + parts = rule.split() + production_name = parts[0] + if parts[1] != ":": + raise ParserGeneratorError("Expecting :") + syms = parts[2:] + + def inner(func): + self.productions.append((production_name, syms, func, precedence)) + return func + return inner + + def error(self, func): + """ + Sets the error handler that is called with the state (if passed to the + parser) and the token the parser errored on. + + Currently error handlers must raise an exception. If an error handler + is not defined, a :exc:`rply.ParsingError` will be raised. + """ + self.error_handler = func + return func + + def compute_grammar_hash(self, g): + hasher = hashlib.sha1() + hasher.update(g.start.encode()) + hasher.update(json.dumps(sorted(g.terminals)).encode()) + for term, (assoc, level) in sorted(iteritems(g.precedence)): + hasher.update(term.encode()) + hasher.update(assoc.encode()) + hasher.update(bytes(level)) + for p in g.productions: + hasher.update(p.name.encode()) + hasher.update(json.dumps(p.prec).encode()) + hasher.update(json.dumps(p.prod).encode()) + return hasher.hexdigest() + + def serialize_table(self, table): + return { + "lr_action": table.lr_action, + "lr_goto": table.lr_goto, + "sr_conflicts": table.sr_conflicts, + "rr_conflicts": table.rr_conflicts, + "default_reductions": table.default_reductions, + "start": table.grammar.start, + "terminals": sorted(table.grammar.terminals), + "precedence": table.grammar.precedence, + "productions": [ + (p.name, p.prod, p.prec) for p in table.grammar.productions + ], + } + + def data_is_valid(self, g, data): + if g.start != data["start"]: + return False + if sorted(g.terminals) != data["terminals"]: + return False + if sorted(g.precedence) != sorted(data["precedence"]): + return False + for key, (assoc, level) in iteritems(g.precedence): + if data["precedence"][key] != [assoc, level]: + return False + if len(g.productions) != len(data["productions"]): + return False + for p, (name, prod, (assoc, level)) in zip(g.productions, data["productions"]): + if p.name != name: + return False + if p.prod != prod: + return False + if p.prec != (assoc, level): + return False + return True + + def build(self): + g = Grammar(self.tokens) + + for level, (assoc, terms) in enumerate(self.precedence, 1): + for term in terms: + g.set_precedence(term, assoc, level) + + for prod_name, syms, func, precedence in self.productions: + g.add_production(prod_name, syms, func, precedence) + + g.set_start() + + for unused_term in g.unused_terminals(): + warnings.warn( + "Token %r is unused" % unused_term, + ParserGeneratorWarning, + stacklevel=2 + ) + for unused_prod in g.unused_productions(): + warnings.warn( + "Production %r is not reachable" % unused_prod, + ParserGeneratorWarning, + stacklevel=2 + ) + + g.build_lritems() + g.compute_first() + g.compute_follow() + + cache_dir = AppDirs("rply").user_cache_dir + cache_file = os.path.join( + cache_dir, + "rply-%s-%s-%s.json" % ( + self.VERSION, self.cache_id, self.compute_grammar_hash(g) + ) + ) + + table = None + if os.path.exists(cache_file): + with open(cache_file) as f: + data = json.load(f) + if self.data_is_valid(g, data): + table = LRTable.from_cache(g, data) + if table is None: + table = LRTable.from_grammar(g) + if not os.path.exists(cache_dir): + os.makedirs(cache_dir) + + with open(cache_file, "w") as f: + json.dump(self.serialize_table(table), f) + + if table.sr_conflicts: + warnings.warn( + "%d shift/reduce conflict%s" % ( + len(table.sr_conflicts), + "s" if len(table.sr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + if table.rr_conflicts: + warnings.warn( + "%d reduce/reduce conflict%s" % ( + len(table.rr_conflicts), + "s" if len(table.rr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + return LRParser(table, self.error_handler) +``` + +## `rply/parsergenerator.py` — `function:ParserGenerator.build` (lines 151-220) + +```python + def build(self): + g = Grammar(self.tokens) + + for level, (assoc, terms) in enumerate(self.precedence, 1): + for term in terms: + g.set_precedence(term, assoc, level) + + for prod_name, syms, func, precedence in self.productions: + g.add_production(prod_name, syms, func, precedence) + + g.set_start() + + for unused_term in g.unused_terminals(): + warnings.warn( + "Token %r is unused" % unused_term, + ParserGeneratorWarning, + stacklevel=2 + ) + for unused_prod in g.unused_productions(): + warnings.warn( + "Production %r is not reachable" % unused_prod, + ParserGeneratorWarning, + stacklevel=2 + ) + + g.build_lritems() + g.compute_first() + g.compute_follow() + + cache_dir = AppDirs("rply").user_cache_dir + cache_file = os.path.join( + cache_dir, + "rply-%s-%s-%s.json" % ( + self.VERSION, self.cache_id, self.compute_grammar_hash(g) + ) + ) + + table = None + if os.path.exists(cache_file): + with open(cache_file) as f: + data = json.load(f) + if self.data_is_valid(g, data): + table = LRTable.from_cache(g, data) + if table is None: + table = LRTable.from_grammar(g) + if not os.path.exists(cache_dir): + os.makedirs(cache_dir) + + with open(cache_file, "w") as f: + json.dump(self.serialize_table(table), f) + + if table.sr_conflicts: + warnings.warn( + "%d shift/reduce conflict%s" % ( + len(table.sr_conflicts), + "s" if len(table.sr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + if table.rr_conflicts: + warnings.warn( + "%d reduce/reduce conflict%s" % ( + len(table.rr_conflicts), + "s" if len(table.rr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + return LRParser(table, self.error_handler) +``` + +## `rply/parsergenerator.py` — `module:@11` (lines 11-11) + +```python +from appdirs import AppDirs +``` + +## `setup.py` — `module:@7` (lines 7-17) + +```python +setup( + name="rply", + description="A pure Python Lex/Yacc that works with RPython", + long_description=readme, + # duplicated in docs/conf.py + version="0.7.3", + author="Alex Gaynor", + author_email="alex.gaynor@gmail.com", + packages=["rply"], + install_requires=["appdirs"], +) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..d06ed45900a410c667b71f96454a74a6708d19da --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/pre_context.md @@ -0,0 +1,333 @@ +# Patch-overlapping Python context before the fix + +## `rply/parsergenerator.py` — `class:ParserGenerator` (lines 20-234) + +```python +class ParserGenerator(object): + """ + A ParserGenerator represents a set of production rules, that define a + sequence of terminals and non-terminals to be replaced with a non-terminal, + which can be turned into a parser. + + :param tokens: A list of token (non-terminal) names. + :param precedence: A list of tuples defining the order of operation for + avoiding ambiguity, consisting of a string defining + associativity (left, right or nonassoc) and a list of + token names with the same associativity and level of + precedence. + :param cache_id: A string specifying an ID for caching. + """ + VERSION = 1 + + def __init__(self, tokens, precedence=[], cache_id=None): + self.tokens = tokens + self.productions = [] + self.precedence = precedence + if cache_id is None: + # This ensures that we always go through the caching code. + cache_id = "".join(random.choice(string.ascii_letters) for _ in range(6)) + self.cache_id = cache_id + self.error_handler = None + + def production(self, rule, precedence=None): + """ + A decorator that defines a production rule and registers the decorated + function to be called with the terminals and non-terminals matched by + that rule. + + A `rule` should consist of a name defining the non-terminal returned + by the decorated function and a sequence of non-terminals and terminals + that are supposed to be replaced:: + + replacing_non_terminal : ATERMINAL non_terminal + + The name of the non-terminal replacing the sequence is on the left, + separated from the sequence by a colon. The whitespace around the colon + is required. + + Knowing this we can define productions:: + + pg = ParserGenerator(['NUMBER', 'ADD']) + + @pg.production('number : NUMBER') + def expr_number(p): + return BoxInt(int(p[0].getstr())) + + @pg.production('expr : number ADD number') + def expr_add(p): + return BoxInt(p[0].getint() + p[2].getint()) + + If a state was passed to the parser, the decorated function is + additionally called with that state as first argument. + """ + parts = rule.split() + production_name = parts[0] + if parts[1] != ":": + raise ParserGeneratorError("Expecting :") + syms = parts[2:] + + def inner(func): + self.productions.append((production_name, syms, func, precedence)) + return func + return inner + + def error(self, func): + """ + Sets the error handler that is called with the state (if passed to the + parser) and the token the parser errored on. + + Currently error handlers must raise an exception. If an error handler + is not defined, a :exc:`rply.ParsingError` will be raised. + """ + self.error_handler = func + return func + + def compute_grammar_hash(self, g): + hasher = hashlib.sha1() + hasher.update(g.start.encode()) + hasher.update(json.dumps(sorted(g.terminals)).encode()) + for term, (assoc, level) in sorted(iteritems(g.precedence)): + hasher.update(term.encode()) + hasher.update(assoc.encode()) + hasher.update(bytes(level)) + for p in g.productions: + hasher.update(p.name.encode()) + hasher.update(json.dumps(p.prec).encode()) + hasher.update(json.dumps(p.prod).encode()) + return hasher.hexdigest() + + def serialize_table(self, table): + return { + "lr_action": table.lr_action, + "lr_goto": table.lr_goto, + "sr_conflicts": table.sr_conflicts, + "rr_conflicts": table.rr_conflicts, + "default_reductions": table.default_reductions, + "start": table.grammar.start, + "terminals": sorted(table.grammar.terminals), + "precedence": table.grammar.precedence, + "productions": [ + (p.name, p.prod, p.prec) for p in table.grammar.productions + ], + } + + def data_is_valid(self, g, data): + if g.start != data["start"]: + return False + if sorted(g.terminals) != data["terminals"]: + return False + if sorted(g.precedence) != sorted(data["precedence"]): + return False + for key, (assoc, level) in iteritems(g.precedence): + if data["precedence"][key] != [assoc, level]: + return False + if len(g.productions) != len(data["productions"]): + return False + for p, (name, prod, (assoc, level)) in zip(g.productions, data["productions"]): + if p.name != name: + return False + if p.prod != prod: + return False + if p.prec != (assoc, level): + return False + return True + + def build(self): + g = Grammar(self.tokens) + + for level, (assoc, terms) in enumerate(self.precedence, 1): + for term in terms: + g.set_precedence(term, assoc, level) + + for prod_name, syms, func, precedence in self.productions: + g.add_production(prod_name, syms, func, precedence) + + g.set_start() + + for unused_term in g.unused_terminals(): + warnings.warn( + "Token %r is unused" % unused_term, + ParserGeneratorWarning, + stacklevel=2 + ) + for unused_prod in g.unused_productions(): + warnings.warn( + "Production %r is not reachable" % unused_prod, + ParserGeneratorWarning, + stacklevel=2 + ) + + g.build_lritems() + g.compute_first() + g.compute_follow() + + # win32 temp directories are already per-user + if os.name == "nt": + cache_file = os.path.join( + tempfile.gettempdir(), + "rply-%s-%s-%s.json" % ( + self.VERSION, self.cache_id, self.compute_grammar_hash(g) + ) + ) + else: + cache_file = os.path.join( + tempfile.gettempdir(), + "rply-%s-%s-%s-%s.json" % ( + self.VERSION, + os.getuid(), + self.cache_id, + self.compute_grammar_hash(g) + ) + ) + table = None + if os.path.exists(cache_file): + with open(cache_file) as f: + data = json.load(f) + stat_result = os.fstat(f.fileno()) + if ( + os.name == "nt" or ( + stat_result.st_uid == os.getuid() and + stat.S_IMODE(stat_result.st_mode) == 0o0600 + ) + ): + if self.data_is_valid(g, data): + table = LRTable.from_cache(g, data) + if table is None: + table = LRTable.from_grammar(g) + fd = os.open( + cache_file, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o0600 + ) + with os.fdopen(fd, "w") as f: + json.dump(self.serialize_table(table), f) + if table.sr_conflicts: + warnings.warn( + "%d shift/reduce conflict%s" % ( + len(table.sr_conflicts), + "s" if len(table.sr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + if table.rr_conflicts: + warnings.warn( + "%d reduce/reduce conflict%s" % ( + len(table.rr_conflicts), + "s" if len(table.rr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + return LRParser(table, self.error_handler) +``` + +## `rply/parsergenerator.py` — `function:ParserGenerator.build` (lines 149-234) + +```python + def build(self): + g = Grammar(self.tokens) + + for level, (assoc, terms) in enumerate(self.precedence, 1): + for term in terms: + g.set_precedence(term, assoc, level) + + for prod_name, syms, func, precedence in self.productions: + g.add_production(prod_name, syms, func, precedence) + + g.set_start() + + for unused_term in g.unused_terminals(): + warnings.warn( + "Token %r is unused" % unused_term, + ParserGeneratorWarning, + stacklevel=2 + ) + for unused_prod in g.unused_productions(): + warnings.warn( + "Production %r is not reachable" % unused_prod, + ParserGeneratorWarning, + stacklevel=2 + ) + + g.build_lritems() + g.compute_first() + g.compute_follow() + + # win32 temp directories are already per-user + if os.name == "nt": + cache_file = os.path.join( + tempfile.gettempdir(), + "rply-%s-%s-%s.json" % ( + self.VERSION, self.cache_id, self.compute_grammar_hash(g) + ) + ) + else: + cache_file = os.path.join( + tempfile.gettempdir(), + "rply-%s-%s-%s-%s.json" % ( + self.VERSION, + os.getuid(), + self.cache_id, + self.compute_grammar_hash(g) + ) + ) + table = None + if os.path.exists(cache_file): + with open(cache_file) as f: + data = json.load(f) + stat_result = os.fstat(f.fileno()) + if ( + os.name == "nt" or ( + stat_result.st_uid == os.getuid() and + stat.S_IMODE(stat_result.st_mode) == 0o0600 + ) + ): + if self.data_is_valid(g, data): + table = LRTable.from_cache(g, data) + if table is None: + table = LRTable.from_grammar(g) + fd = os.open( + cache_file, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o0600 + ) + with os.fdopen(fd, "w") as f: + json.dump(self.serialize_table(table), f) + if table.sr_conflicts: + warnings.warn( + "%d shift/reduce conflict%s" % ( + len(table.sr_conflicts), + "s" if len(table.sr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + if table.rr_conflicts: + warnings.warn( + "%d reduce/reduce conflict%s" % ( + len(table.rr_conflicts), + "s" if len(table.rr_conflicts) > 1 else "" + ), + ParserGeneratorWarning, + stacklevel=2, + ) + return LRParser(table, self.error_handler) +``` + +## `rply/parsergenerator.py` — `module:@11` (lines 11-11) + +```python +from rply.errors import ParserGeneratorError, ParserGeneratorWarning +``` + +## `setup.py` — `module:@7` (lines 7-16) + +```python +setup( + name="rply", + description="A pure Python Lex/Yacc that works with RPython", + long_description=readme, + # duplicated in docs/conf.py + version="0.7.3", + author="Alex Gaynor", + author_email="alex.gaynor@gmail.com", + packages=["rply"], +) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d025158e7b5a78c3c52222b53d33345ea14cbbb0 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-b5417e7c5b6909a4c5f9", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-b5417e7c5b6909a4c5f9", + "project_id": "pyvul__alex__rply", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "rply/parsergenerator.py", + "setup.py" + ], + "patch_units": { + "before": [ + "class:ParserGenerator", + "function:ParserGenerator.build", + "module:@11", + "module:@7" + ], + "after": [ + "class:ParserGenerator", + "function:ParserGenerator.build", + "module:@11", + "module:@7" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/f96103c25dd91b54de57179289e617f3cb7c5336d4f6aa449bef9e4ae91e725a/database", + "cache_key": "f96103c25dd91b54de57179289e617f3cb7c5336d4f6aa449bef9e4ae91e725a", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/8eedd1d47c1786df5ce6c4f3625e73f84e2304b1e748915311d88ab037f8dadd/database", + "cache_key": "8eedd1d47c1786df5ce6c4f3625e73f84e2304b1e748915311d88ab037f8dadd", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/b002c93cb83d831875ccbcb3cc48614e535d34aaa7095c248cd40817ceb20dca/database", + "cache_key": "b002c93cb83d831875ccbcb3cc48614e535d34aaa7095c248cd40817ceb20dca", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-b5417e7c5b6909a4c5f9/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-b5417e7c5b6909a4c5f9/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-b5417e7c5b6909a4c5f9/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..61add82eb933879664c3daa7d602cf5cfdaee1a2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/patch.diff @@ -0,0 +1,98 @@ +diff --git a/CHANGES.rst b/CHANGES.rst +index 60d0d82..cc2aad0 100644 +--- a/CHANGES.rst ++++ b/CHANGES.rst +@@ -4,7 +4,7 @@ Changelog + 2.1.1 (unreleased) + ------------------ + +-- Enforce access control on setup tool log files ++- Enforce access control on setup tool log files and snapshot files and folders. + (`#101 `_) + + +diff --git a/src/Products/GenericSetup/context.py b/src/Products/GenericSetup/context.py +index 1c8ba1d..9977929 100644 +--- a/src/Products/GenericSetup/context.py ++++ b/src/Products/GenericSetup/context.py +@@ -26,6 +26,7 @@ from tarfile import TarInfo + import six + + from AccessControl.class_init import InitializeClass ++from AccessControl.Permissions import view + from AccessControl.SecurityInfo import ClassSecurityInfo + from Acquisition import Implicit + from Acquisition import aq_base +@@ -499,6 +500,10 @@ class SnapshotExportContext(BaseContext): + # MISSING: switch on content_type + ob = self._createObjectByType(filename, text, content_type) + folder._setObject(str(filename), ob) # No Unicode IDs! ++ # Tighten the View permission on the new object. ++ # Only the owner and Manager users may view the log. ++ # file_ob = self._getOb(name) ++ ob.manage_permission(view, ('Manager', 'Owner'), 0) + + @security.protected(ManagePortal) + def getSnapshotURL(self): +@@ -559,8 +564,10 @@ class SnapshotExportContext(BaseContext): + if element not in current.objectIds(): + # No Unicode IDs! + current._setObject(str(element), Folder(element)) +- +- current = current._getOb(element) ++ current = current._getOb(element) ++ current.manage_permission(view, ('Manager', 'Owner'), 0) ++ else: ++ current = current._getOb(element) + + return current + +diff --git a/src/Products/GenericSetup/tests/test_tool.py b/src/Products/GenericSetup/tests/test_tool.py +index 2ce313c..d392bbc 100644 +--- a/src/Products/GenericSetup/tests/test_tool.py ++++ b/src/Products/GenericSetup/tests/test_tool.py +@@ -473,6 +473,15 @@ class SetupToolTests(FilesystemTestBase, TarballTester, ConformsToISetupTool): + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + ++ def check_restricted_access(self, obj): ++ # For most objects that we create, we do not want ordinary users to ++ # see it, also not when they have View permission on a higher level. ++ rop_info = obj.rolesOfPermission(view) ++ allowed_roles = sorted([x['name'] for x in rop_info ++ if x['selected']]) ++ self.assertEqual(allowed_roles, ['Manager', 'Owner']) ++ self.assertFalse(obj.acquiredRolesAreUsedBy(view)) ++ + def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): + + TITLE = 'original title' +@@ -497,11 +506,7 @@ class SetupToolTests(FilesystemTestBase, TarballTester, ConformsToISetupTool): + logged = [x for x in tool.objectIds('File')] + for file_id in logged: + file_ob = tool._getOb(file_id) +- rop_info = file_ob.rolesOfPermission(view) +- allowed_roles = sorted([x['name'] for x in rop_info +- if x['selected']]) +- self.assertEqual(allowed_roles, ['Manager', 'Owner']) +- self.assertFalse(file_ob.acquiredRolesAreUsedBy(view)) ++ self.check_restricted_access(file_ob) + + def test_runAllImportStepsFromProfile_sorted_explicit_purge(self): + +@@ -1101,6 +1106,15 @@ class SetupToolTests(FilesystemTestBase, TarballTester, ConformsToISetupTool): + self.assertEqual(info['id'], 'default') + self.assertEqual(info['title'], 'default') + ++ # Check access restriction on snapshot files and folders ++ self.check_restricted_access(tool.snapshots) ++ self.check_restricted_access(snapshot) ++ for obj in snapshot.objectValues(): ++ self.check_restricted_access(obj) ++ if hasattr(aq_base(obj), 'objectValues'): ++ for child in obj.objectValues(): ++ self.check_restricted_access(child) ++ + def test_applyContext(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..fa800fd13dca76a7edc2016749d0c76aa7da2043 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/post_context.md @@ -0,0 +1,1958 @@ +# Patch-overlapping Python context after the fix + +## `src/Products/GenericSetup/context.py` — `class:SnapshotExportContext` (lines 472-572) + +```python +class SnapshotExportContext(BaseContext): + + security = ClassSecurityInfo() + + def __init__(self, tool, snapshot_id, encoding=None): + + BaseContext.__init__(self, tool, encoding) + self._snapshot_id = snapshot_id + + @security.protected(ManagePortal) + def writeDataFile(self, filename, text, content_type, subdir=None): + """ See IExportContext. + """ + if subdir is not None: + filename = '/'.join((subdir, filename)) + + sep = filename.rfind('/') + if sep != -1: + subdir = filename[:sep] + filename = filename[sep+1:] + + if six.PY2 and isinstance(text, six.text_type): + encoding = self.getEncoding() or 'utf-8' + text = text.encode(encoding) + + folder = self._ensureSnapshotsFolder(subdir) + + # MISSING: switch on content_type + ob = self._createObjectByType(filename, text, content_type) + folder._setObject(str(filename), ob) # No Unicode IDs! + # Tighten the View permission on the new object. + # Only the owner and Manager users may view the log. + # file_ob = self._getOb(name) + ob.manage_permission(view, ('Manager', 'Owner'), 0) + + @security.protected(ManagePortal) + def getSnapshotURL(self): + """ See IExportContext. + """ + return '%s/%s' % (self._tool.absolute_url(), self._snapshot_id) + + @security.protected(ManagePortal) + def getSnapshotFolder(self): + """ See IExportContext. + """ + return self._ensureSnapshotsFolder() + + # + # Helper methods + # + @security.private + def _createObjectByType(self, name, body, content_type): + encoding = self.getEncoding() or 'utf-8' + + if six.PY2 and isinstance(body, six.text_type): + body = body.encode(encoding) + + if name.endswith('.py'): + ob = PythonScript(name) + ob.write(body) + return ob + + if name.endswith('.dtml'): + ob = DTMLDocument('', __name__=name) + ob.munge(body) + return ob + + if content_type in ('text/html', 'text/xml'): + return ZopePageTemplate(name, body, content_type=content_type) + + if isinstance(body, six.text_type): + body = body.encode(encoding) + + if content_type[:6] == 'image/': + return Image(name, '', body, content_type=content_type) + + return File(name, '', body, content_type=content_type) + + @security.private + def _ensureSnapshotsFolder(self, subdir=None): + """ Ensure that the appropriate snapshot folder exists. + """ + path = ['snapshots', self._snapshot_id] + + if subdir is not None: + path.extend(subdir.split('/')) + + current = self._tool + + for element in path: + + if element not in current.objectIds(): + # No Unicode IDs! + current._setObject(str(element), Folder(element)) + current = current._getOb(element) + current.manage_permission(view, ('Manager', 'Owner'), 0) + else: + current = current._getOb(element) + + return current +``` + +## `src/Products/GenericSetup/context.py` — `function:SnapshotExportContext.writeDataFile` (lines 482-506) + +```python + def writeDataFile(self, filename, text, content_type, subdir=None): + """ See IExportContext. + """ + if subdir is not None: + filename = '/'.join((subdir, filename)) + + sep = filename.rfind('/') + if sep != -1: + subdir = filename[:sep] + filename = filename[sep+1:] + + if six.PY2 and isinstance(text, six.text_type): + encoding = self.getEncoding() or 'utf-8' + text = text.encode(encoding) + + folder = self._ensureSnapshotsFolder(subdir) + + # MISSING: switch on content_type + ob = self._createObjectByType(filename, text, content_type) + folder._setObject(str(filename), ob) # No Unicode IDs! + # Tighten the View permission on the new object. + # Only the owner and Manager users may view the log. + # file_ob = self._getOb(name) + ob.manage_permission(view, ('Manager', 'Owner'), 0) +``` + +## `src/Products/GenericSetup/context.py` — `function:SnapshotExportContext._ensureSnapshotsFolder` (lines 551-572) + +```python + def _ensureSnapshotsFolder(self, subdir=None): + """ Ensure that the appropriate snapshot folder exists. + """ + path = ['snapshots', self._snapshot_id] + + if subdir is not None: + path.extend(subdir.split('/')) + + current = self._tool + + for element in path: + + if element not in current.objectIds(): + # No Unicode IDs! + current._setObject(str(element), Folder(element)) + current = current._getOb(element) + current.manage_permission(view, ('Manager', 'Owner'), 0) + else: + current = current._getOb(element) + + return current +``` + +## `src/Products/GenericSetup/context.py` — `module:@29` (lines 29-29) + +```python +from AccessControl.Permissions import view +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `class:SetupToolTests` (lines 111-1786) + +```python +class SetupToolTests(FilesystemTestBase, TarballTester, ConformsToISetupTool): + + layer = ExportImportZCMLLayer + + _PROFILE_PATH = tempfile.mkdtemp(prefix='STT_test') + _PROFILE_PATH2 = tempfile.mkdtemp(prefix='STT_test2') + _PROFILE_PATH3 = tempfile.mkdtemp(prefix='STT_test3') + + def afterSetUp(self): + from ..upgrade import _upgrade_registry + _upgrade_registry.clear() + profile_registry.clear() + global _before_import_events + global _after_import_events + _before_import_events = [] + provideHandler(handleBeforeProfileImportEvent) + _after_import_events = [] + provideHandler(handleProfileImportedEvent) + + def beforeTearDown(self): + base_registry.unregisterHandler(handleBeforeProfileImportEvent) + base_registry.unregisterHandler(handleProfileImportedEvent) + FilesystemTestBase.beforeTearDown(self) + from ..upgrade import _upgrade_registry + profile_registry.clear() + _upgrade_registry.clear() + noSecurityManager() + + def _getTargetClass(self): + from ..tool import SetupTool + + return SetupTool + + def _makeSite(self, title="Don't care"): + + site = Folder() + site._setId('site') + site.title = title + + self.app._setObject('site', site) + self.app.acl_users.userFolderAddUser('admin', '', ['Manager'], []) + newSecurityManager(None, self.app.acl_users.getUser('admin')) + return self.app._getOb('site') + + def test_empty(self): + + tool = self._makeOne('setup_tool') + + self.assertEqual(tool.getBaselineContextID(), '') + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 0) + + export_registry = tool.getExportStepRegistry() + export_steps = export_registry.listSteps() + self.assertEqual(len(export_steps), 0) + + toolset_registry = tool.getToolsetRegistry() + self.assertEqual(len(toolset_registry.listForbiddenTools()), 0) + self.assertEqual(len(toolset_registry.listRequiredTools()), 0) + + def test_getBaselineContextID(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + tool = self._makeOne('setup_tool') + + self._makeFile(IMPORT_STEPS_XML, _EMPTY_IMPORT_XML) + self._makeFile(EXPORT_STEPS_XML, _EMPTY_EXPORT_XML) + self._makeFile(TOOLSET_XML, _EMPTY_TOOLSET_XML) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + tool.setBaselineContext('profile-other:foo') + + self.assertEqual(tool.getBaselineContextID(), 'profile-other:foo') + + def test_setBaselineContext_invalid(self): + + tool = self._makeOne('setup_tool') + + self.assertRaises(KeyError, tool.setBaselineContext, 'profile-foo') + + def test_setBaselineContext_empty_string(self): + + tool = self._makeOne('setup_tool') + + self.assertRaises(KeyError, tool.setBaselineContext, '') + + def test_setBaselineContext(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + tool = self._makeOne('setup_tool') + tool.getExportStepRegistry().clear() + + self._makeFile(IMPORT_STEPS_XML, _SINGLE_IMPORT_XML) + self._makeFile(EXPORT_STEPS_XML, _SINGLE_EXPORT_XML) + self._makeFile(TOOLSET_XML, _NORMAL_TOOLSET_XML) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + tool.setBaselineContext('profile-other:foo') + + self.assertEqual(tool.getBaselineContextID(), 'profile-other:foo') + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = import_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertEqual(info['version'], '1') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(import_registry.getStep('one'), ONE_FUNC) + + export_registry = tool.getExportStepRegistry() + self.assertEqual(len(export_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = export_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(export_registry.getStep('one'), ONE_FUNC) + + def test_runImportStepFromProfile_nonesuch(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + + self.assertRaises(KeyError, tool.runImportStepFromProfile, + '', 'nonesuch') + + def test_runImportStepFromProfile_simple(self): + + TITLE = 'original title' + site = self._makeSite(TITLE) + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('simple', '1', _uppercaseSiteTitle) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'simple') + + self.assertEqual(len(result['steps']), 1) + + self.assertEqual(result['steps'][0], 'simple') + self.assertEqual(result['messages']['simple'], 'Uppercased title') + + self.assertEqual(site.title, TITLE.upper()) + + global _before_import_events + self.assertEqual(len(_before_import_events), 1) + self.assertEqual(_before_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_before_import_events[0].steps, ['simple']) + self.assertEqual(_before_import_events[0].full_import, False) + + global _after_import_events + self.assertEqual(len(_after_import_events), 1) + self.assertEqual(_after_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_after_import_events[0].steps, ['simple']) + self.assertEqual(_after_import_events[0].full_import, False) + + def test_runImportStepFromProfile_dependencies(self): + + TITLE = 'original title' + site = self._makeSite(TITLE) + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('dependable', '1', _underscoreSiteTitle) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'dependent') + + self.assertEqual(len(result['steps']), 2) + + self.assertEqual(result['steps'][0], 'dependable') + self.assertEqual(result['messages']['dependable'], 'Underscored title') + + self.assertEqual(result['steps'][1], 'dependent') + self.assertEqual(result['messages']['dependent'], 'Uppercased title') + self.assertEqual(site.title, TITLE.replace(' ', '_').upper()) + + global _before_import_events + self.assertEqual(len(_before_import_events), 1) + self.assertEqual(_before_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_before_import_events[0].steps, + ['dependable', 'dependent']) + self.assertEqual(_before_import_events[0].full_import, False) + + global _after_import_events + self.assertEqual(len(_after_import_events), 1) + self.assertEqual(_after_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_after_import_events[0].steps, + ['dependable', 'dependent']) + self.assertEqual(_after_import_events[0].full_import, False) + + def test_runImportStepFromProfile_skip_dependencies(self): + + TITLE = 'original title' + site = self._makeSite(TITLE) + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('dependable', '1', _underscoreSiteTitle) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'dependent', + run_dependencies=False) + + self.assertEqual(len(result['steps']), 1) + + self.assertEqual(result['steps'][0], 'dependent') + self.assertEqual(result['messages']['dependent'], 'Uppercased title') + + self.assertEqual(site.title, TITLE.upper()) + + global _before_import_events + self.assertEqual(len(_before_import_events), 1) + self.assertEqual(_before_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_before_import_events[0].steps, ['dependent']) + self.assertEqual(_before_import_events[0].full_import, False) + + global _after_import_events + self.assertEqual(len(_after_import_events), 1) + self.assertEqual(_after_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_after_import_events[0].steps, ['dependent']) + self.assertEqual(_after_import_events[0].full_import, False) + + def test_runImportStepFromProfile_default_purge(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'purging') + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + self.assertTrue(site.purged) + + def test_runImportStepFromProfile_explicit_purge(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'purging', + purge_old=True) + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + self.assertTrue(site.purged) + + def test_runImportStepFromProfile_skip_purge(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'purging', + purge_old=False) + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Unpurged') + self.assertFalse(site.purged) + + def test_runImportStepFromProfile_consistent_context(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('purging', )) + + tool.runImportStepFromProfile('snapshot-dummy', 'dependent', + purge_old=False) + self.assertFalse(site.purged) + + def test_runAllImportStepsFromProfile_empty(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + result = tool.runAllImportStepsFromProfile('snapshot-dummy') + + self.assertEqual(len(result['steps']), 3) + + def test_runAllImportStepsFromProfile_inquicksuccession(self): + """ + This test provokes an issue that only appears in testing. + There it can happen that profiles get run multiple times within + a second. As of 1.6.3, genericsetup does not handle this. + """ + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + tool.runAllImportStepsFromProfile('snapshot-dummy') + tool.runAllImportStepsFromProfile('snapshot-dummy') + # For good measurement + tool.runAllImportStepsFromProfile('snapshot-dummy') + + self.assertTrue("No exception thrown") + + def test_runAllImportStepsFromProfile_sorted_default_purge(self): + + TITLE = 'original title' + PROFILE_ID = 'snapshot-testing' + site = self._makeSite(TITLE) + tool = self._makeOne('setup_tool').__of__(site) + tool._exclude_global_steps = True + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runAllImportStepsFromProfile(PROFILE_ID) + + self.assertEqual(len(result['steps']), 3) + + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + + self.assertEqual(result['steps'][1], 'dependable') + self.assertEqual(result['messages']['dependable'], 'Underscored title') + + self.assertEqual(result['steps'][2], 'dependent') + self.assertEqual(result['messages']['dependent'], 'Uppercased title') + + self.assertEqual(site.title, TITLE.replace(' ', '_').upper()) + self.assertTrue(site.purged) + + prefix = 'import-all-%s' % PROFILE_ID + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + + def check_restricted_access(self, obj): + # For most objects that we create, we do not want ordinary users to + # see it, also not when they have View permission on a higher level. + rop_info = obj.rolesOfPermission(view) + allowed_roles = sorted([x['name'] for x in rop_info + if x['selected']]) + self.assertEqual(allowed_roles, ['Manager', 'Owner']) + self.assertFalse(obj.acquiredRolesAreUsedBy(view)) + + def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): + + TITLE = 'original title' + PROFILE_ID = u'snapshot-testing' + site = self._makeSite(TITLE) + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + tool.runAllImportStepsFromProfile(PROFILE_ID) + + prefix = str('import-all-%s' % PROFILE_ID) + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + + # Check acess restriction on log files + logged = [x for x in tool.objectIds('File')] + for file_id in logged: + file_ob = tool._getOb(file_id) + self.check_restricted_access(file_ob) + + def test_runAllImportStepsFromProfile_sorted_explicit_purge(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool._exclude_global_steps = True + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runAllImportStepsFromProfile('snapshot-dummy', + purge_old=True) + + self.assertEqual(len(result['steps']), 3) + + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + + self.assertEqual(result['steps'][1], 'dependable') + self.assertEqual(result['steps'][2], 'dependent') + self.assertTrue(site.purged) + + def test_runAllImportStepsFromProfile_sorted_skip_purge(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool._exclude_global_steps = True + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runAllImportStepsFromProfile('snapshot-dummy', + purge_old=False) + + self.assertEqual(len(result['steps']), 3) + + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Unpurged') + + self.assertEqual(result['steps'][1], 'dependable') + self.assertEqual(result['steps'][2], 'dependent') + self.assertFalse(site.purged) + + def test_runAllImportStepsFromProfile_without_depends(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + + _imported = [] + + def applyContext(context): + _imported.append(context._profile_path) + + tool.applyContext = applyContext + tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=True) + self.assertEqual(_imported, [self._PROFILE_PATH]) + + def test_runAllImportStepsFromProfile_with_depends(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + profile_registry.registerProfile('bar', 'Bar', '', self._PROFILE_PATH2) + + _imported = [] + + def applyContext(context): + _imported.append(context._profile_path) + + tool.applyContext = applyContext + tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=False) + self.assertEqual(_imported, [self._PROFILE_PATH2, self._PROFILE_PATH]) + + def _setup_dependency_strategy_test_tool(self): + # If we add a dependency profile in our metadata.xml, and this + # dependency was already applied, then we do not need to apply + # it yet again. Once is quite enough, thank you. Running any + # upgrade steps would be nice though. There are options. + # Setup a tool and profiles for testing dependency strategies. + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + self._makeFile(METADATA_XML, _DOUBLE_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _PLAIN_METADATA_XML) + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register main profile and two dependency profiles. + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + profile_type=EXTENSION) + profile_registry.registerProfile('bar', 'Bar', '', self._PROFILE_PATH2, + profile_type=EXTENSION) + profile_registry.registerProfile('ham', 'Ham', '', self._PROFILE_PATH3, + profile_type=EXTENSION) + + # Apply the second profile. + tool.runAllImportStepsFromProfile('profile-other:bar') + + # Register an upgrade step. Note that applying this step will + # set the profile version to 1.1, even though the metadata of + # the profile really says 1.0. We will use this to check + # whether the upgrade step has been applied (version is 1.1) + # or the full profile has been applied (version is 1.0). + step_bar = UpgradeStep( + "Upgrade", "other:bar", '1.0', '1.1', '', dummy_upgrade, None, "1") + _registerUpgradeStep(step_bar) + # And another one. + step_ham = UpgradeStep( + "Upgrade", "other:ham", '1.0', '1.1', '', dummy_upgrade, None, "1") + _registerUpgradeStep(step_ham) + + # Gather list of imported profiles. + tool._imported = [] + + def applyContext(context): + tool._imported.append(context._profile_path) + + tool.applyContext = applyContext + + return tool + + def test_runAllImportStepsFromProfile_with_default_strategy(self): + # Default strategy: apply new profiles, upgrade old profiles. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + tool.runAllImportStepsFromProfile('profile-other:foo') + # The main and third profile have been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH3, self._PROFILE_PATH]) + # The upgrade step of the second profile has been applied, + # pushing it to version 1.1. + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '1')) + # Third profile is at 1.0. + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('1', '0')) + + def test_runAllImportStepsFromProfile_with_reapply_strategy(self): + # You can choose the old behavior of always applying the + # dependencies. This ignores any upgrade steps. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + from ..tool import DEPENDENCY_STRATEGY_REAPPLY + tool.runAllImportStepsFromProfile( + 'profile-other:foo', + dependency_strategy=DEPENDENCY_STRATEGY_REAPPLY) + # All three profiles have been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH2, self._PROFILE_PATH3, + self._PROFILE_PATH]) + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '0')) + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('1', '0')) + + def test_runAllImportStepsFromProfile_with_new_strategy(self): + # You can choose to be happy with any applied version and + # ignore any upgrade steps. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + from ..tool import DEPENDENCY_STRATEGY_NEW + tool.runAllImportStepsFromProfile( + 'profile-other:foo', + dependency_strategy=DEPENDENCY_STRATEGY_NEW) + # The main and third profile have been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH3, self._PROFILE_PATH]) + # Second profile stays at 1.0. + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '0')) + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('1', '0')) + + def test_runAllImportStepsFromProfile_with_ignore_strategy(self): + # You can choose to be ignore all dependency profiles. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + from ..tool import DEPENDENCY_STRATEGY_IGNORE + tool.runAllImportStepsFromProfile( + 'profile-other:foo', + dependency_strategy=DEPENDENCY_STRATEGY_IGNORE) + # Only the main profile has been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH]) + # Second profile stays at 1.0. + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '0')) + # Third profile is not applied. + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('unknown')) + + def test_runAllImportStepsFromProfile_unknown_strategy(self): + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + self.assertRaises(ValueError, tool.runAllImportStepsFromProfile, + 'profile-other:foo', dependency_strategy='random') + + def test_runAllImportStepsFromProfile_set_last_profile_version(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + + # test initial states + profile_id = "other:foo" + self.assertEqual(tool.getVersionForProfile(profile_id), '1.0') + self.assertEqual(tool.getLastVersionForProfile(profile_id), + 'unknown') + + # run all imports steps + tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=True) + + # events.handleProfileImportedEvent should set last profile version + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '0')) + + def test_runAllImportStepsFromProfile_step_registration_with_depends(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + _IMPORT_STEPS_XML = """ + + + One small step + + +""" + self._makeFile('import_steps.xml', _IMPORT_STEPS_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + profile_registry.registerProfile('bar', 'Bar', '', self._PROFILE_PATH2) + + result = tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=False) + + # ensure the additional step on foo was imported + self.assertTrue('one' in result['steps']) + + def test_runAllImportStepsFromProfile_skipStep(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + result = tool.runAllImportStepsFromProfile( + 'snapshot-dummy', + blacklisted_steps=['toolset'], + ) + + self.assertEqual((result['messages']['toolset']), 'step skipped') + + def test_runAllImportStepsFromProfile_with_base_profile(self): + # Applying a base profile should clear the profile upgrade + # versions. + from ..interfaces import BASE + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _PLAIN_METADATA_XML) + + # Register a base and two extension profile. The base profile + # 'foo' has a dependency 'bar'. This might not make sense, + # but it will serve to check that we clear the profile + # versions right before we apply the base profile, which means + # right after any dependency profiles. + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=BASE) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + profile_registry.registerProfile( + 'ham', 'Ham', '', self._PROFILE_PATH3, profile_type=EXTENSION) + # Apply the extension profile. + tool.runAllImportStepsFromProfile('profile-other:ham') + self.assertEqual(tool._profile_upgrade_versions, + {u'other:ham': (u'1', u'0')}) + # Apply the base profile. + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool._profile_upgrade_versions, + {u'other:foo': (u'1', u'0')}) + + def test_runAllImportStepsFromProfile_with_unknown_pre_handler(self): + # Registering already fails. + self.assertRaises( + ValueError, profile_registry.registerProfile, + 'foo', 'Foo', '', self._PROFILE_PATH, + pre_handler='Products.GenericSetup.tests.test_tool.foo_handler') + + def test_runAllImportStepsFromProfile_with_unknown_post_handler(self): + # Registering already fails. + self.assertRaises( + ValueError, profile_registry.registerProfile, + 'foo', 'Foo', '', self._PROFILE_PATH, + post_handler='Products.GenericSetup.tests.test_tool.foo_handler') + + def test_runAllImportStepsFromProfile_pre_post_handlers_dotted_names(self): + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, + pre_handler='Products.GenericSetup.tests.test_tool.pre_handler', + post_handler='Products.GenericSetup.tests.test_tool.post_handler') + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 1) + self.assertEqual(tool.post_handler_called, 1) + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 2) + self.assertEqual(tool.post_handler_called, 2) + + def test_runAllImportStepsFromProfile_pre_post_handlers_functions(self): + # When you register a profile with pre/post handlers in zcml, you do + # not get dotted names (strings) but an actual function. + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, + pre_handler=pre_handler, + post_handler=post_handler) + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 1) + self.assertEqual(tool.post_handler_called, 1) + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 2) + self.assertEqual(tool.post_handler_called, 2) + + def test_runExportStep_nonesuch(self): + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + self.assertRaises(ValueError, tool.runExportStep, 'nonesuch') + + def test_runExportStep_step_registry_empty(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + + result = tool.runExportStep('step_registries') + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'step_registries') + self.assertEqual(result['messages']['step_registries'], None) + + def test_runExportStep_step_registry_default(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + steps = 'Products.GenericSetup.tool.exportStepRegistries' + tool._export_registry.registerStep('step_registries', steps, + 'Export import / export steps.') + + result = tool.runExportStep('step_registries') + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'step_registries') + self.assertEqual(result['messages']['step_registries'], None) + fileish = BytesIO(result['tarball']) + + self._verifyTarballContents(fileish, + ['import_steps.xml', 'export_steps.xml']) + self._verifyTarballEntryXML( + fileish, 'import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML) + self._verifyTarballEntryXML( + fileish, 'export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML) + + def test_runAllExportSteps_empty(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + + result = tool.runAllExportSteps() + + self.assertEqual( + sorted(result['steps']), + ['componentregistry', 'rolemap', 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + + def test_runAllExportSteps_default(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + steps = 'Products.GenericSetup.tool.exportStepRegistries' + tool._export_registry.registerStep('step_registries', steps, + 'Export import / export steps.') + + result = tool.runAllExportSteps() + + self.assertEqual(sorted(result['steps']), + ['componentregistry', 'rolemap', + 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + fileish = BytesIO(result['tarball']) + + self._verifyTarballContents(fileish, + ['import_steps.xml', 'export_steps.xml', + 'rolemap.xml', 'toolset.xml']) + self._verifyTarballEntryXML( + fileish, 'import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML) + self._verifyTarballEntryXML( + fileish, 'export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML) + + def test_runAllExportSteps_extras(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + steps = 'Products.GenericSetup.tool.exportStepRegistries' + tool._export_registry.registerStep('step_registries', steps, + 'Export import / export steps.') + + import_reg = tool.getImportStepRegistry() + import_reg.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + import_reg.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + import_reg.registerStep('purging', '1', _purgeIfRequired) + + export_reg = tool.getExportStepRegistry() + export_reg.registerStep('properties', _exportPropertiesINI) + + result = tool.runAllExportSteps() + + self.assertEqual(len(result['steps']), 5) + self.assertEqual(sorted(result['steps']), + ['componentregistry', 'properties', 'rolemap', + 'step_registries', 'toolset']) + + self.assertEqual(result['messages']['properties'], + 'Exported properties') + self.assertEqual(result['messages']['step_registries'], None) + + fileish = BytesIO(result['tarball']) + + self._verifyTarballContents(fileish, + ['import_steps.xml', 'export_steps.xml', + 'properties.ini', 'rolemap.xml', + 'toolset.xml']) + self._verifyTarballEntryXML( + fileish, 'import_steps.xml', _EXTRAS_STEP_REGISTRIES_IMPORT_XML) + self._verifyTarballEntryXML( + fileish, 'export_steps.xml', _EXTRAS_STEP_REGISTRIES_EXPORT_XML) + ini_string = _PROPERTIES_INI % site.title + self._verifyTarballEntry(fileish, 'properties.ini', + ini_string.encode('utf-8')) + + def test_manage_importTarball(self): + # Tests for importing a tarball with GenericSetup files. + # We are especially interested to see if old settings get purged. + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + # We need to be Manager to see the result of calling + # manage_importTarball. + newSecurityManager(None, UnrestrictedUser('root', '', ['Manager'], '')) + + ROLEMAP_XML = """ + + + + + + +""" + + def rolemap_tarball(name): + # Create a tarball archive with rolemap.xml containing 'name' as + # role. + context = TarballExportContext(tool) + contents = ROLEMAP_XML % name + if isinstance(contents, six.text_type): + contents = contents.encode('utf-8') + context.writeDataFile('rolemap.xml', contents, 'text/xml') + return context.getArchive() + + # Import first role. + tool.manage_importTarball(rolemap_tarball('First')) + self.assertTrue('First' in site.valid_roles()) + + # Import second role. + tool.manage_importTarball(rolemap_tarball('Second')) + self.assertTrue('Second' in site.valid_roles()) + # The first role has been purged, because that is the default. + self.assertFalse('First' in site.valid_roles()) + # A few standard roles are never removed, probably because they are + # defined one level higher. + self.assertTrue('Anonymous' in site.valid_roles()) + self.assertTrue('Authenticated' in site.valid_roles()) + self.assertTrue('Manager' in site.valid_roles()) + self.assertTrue('Owner' in site.valid_roles()) + + # Import third role in non-purge mode. + tool.manage_importTarball(rolemap_tarball('Third'), purge_old=False) + self.assertTrue('Third' in site.valid_roles()) + # The second role is still there. + self.assertTrue('Second' in site.valid_roles()) + + # When you use the form, and uncheck the purge_old checkbox, then the + # browser does not send the purge_old parameter in the request. To + # work around this, the form always passes a hidden 'submitted' + # parameter. + # Import fourth role in non-purge mode with a form submit. + tool.manage_importTarball(rolemap_tarball('Fourth'), submitted='yes') + self.assertTrue('Fourth' in site.valid_roles()) + # The other roles are still there. + self.assertTrue('Second' in site.valid_roles()) + self.assertTrue('Third' in site.valid_roles()) + self.assertTrue('Manager' in site.valid_roles()) + + def test_createSnapshot_default(self): + _EXPECTED = [ + ('import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML), + ('export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML), + ('rolemap.xml', 'dummy'), + ('toolset.xml', 'dummy'), + ] + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + tool._export_registry.registerStep( + 'step_registries', + 'Products.GenericSetup.tool.exportStepRegistries', + 'Export import / export steps.') + + self.assertEqual(len(tool.listSnapshotInfo()), 0) + + result = tool.createSnapshot('default') + + self.assertEqual( + sorted(result['steps']), + ['componentregistry', 'rolemap', 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + + snapshot = result['snapshot'] + + self.assertEqual(len(snapshot.objectIds()), len(_EXPECTED)) + + for id in [x[0] for x in _EXPECTED]: + self.assertTrue(id in snapshot.objectIds()) + + def normalize_xml(xml): + # using this might mask a real problem on windows, but so far the + # different newlines just caused problems in this test + lines = [line.strip() for line in xml.splitlines() if line.strip()] + return ' '.join(lines) + + fileobj = snapshot._getOb('import_steps.xml') + self.assertEqual(normalize_xml(fileobj.read()), + normalize_xml(_DEFAULT_STEP_REGISTRIES_IMPORT_XML)) + + fileobj = snapshot._getOb('export_steps.xml') + self.assertEqual(normalize_xml(fileobj.read()), + normalize_xml(_DEFAULT_STEP_REGISTRIES_EXPORT_XML)) + + self.assertEqual(len(tool.listSnapshotInfo()), 1) + + info = tool.listSnapshotInfo()[0] + + self.assertEqual(info['id'], 'default') + self.assertEqual(info['title'], 'default') + + # Check access restriction on snapshot files and folders + self.check_restricted_access(tool.snapshots) + self.check_restricted_access(snapshot) + for obj in snapshot.objectValues(): + self.check_restricted_access(obj) + if hasattr(aq_base(obj), 'objectValues'): + for child in obj.objectValues(): + self.check_restricted_access(child) + + def test_applyContext(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool.getImportStepRegistry().clear() + tool.getExportStepRegistry().clear() + tool.getToolsetRegistry().clear() + + context = DummyImportContext(site, tool=tool) + context._files[IMPORT_STEPS_XML] = _SINGLE_IMPORT_XML + context._files[EXPORT_STEPS_XML] = _SINGLE_EXPORT_XML + context._files[TOOLSET_XML] = _NORMAL_TOOLSET_XML + + tool.applyContext(context) + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = import_registry.getStepMetadata('one') + + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertEqual(info['version'], '1') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(import_registry.getStep('one'), ONE_FUNC) + + export_registry = tool.getExportStepRegistry() + self.assertEqual(len(export_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = export_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(export_registry.getStep('one'), ONE_FUNC) + + def test_listContextInfos_empty(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + infos = tool.listContextInfos() + self.assertEqual(len(infos), 0) + + def test_listContextInfos_with_snapshot(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.createSnapshot('testing') + infos = tool.listContextInfos() + self.assertEqual(len(infos), 1) + info = infos[0] + self.assertEqual(info['id'], 'snapshot-testing') + self.assertEqual(info['title'], 'testing') + self.assertEqual(info['type'], 'snapshot') + + def test_listContextInfos_with_registered_base_profile(self): + from ..interfaces import BASE + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + 'Foo', BASE) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + infos = tool.listContextInfos() + self.assertEqual(len(infos), 1) + info = infos[0] + self.assertEqual(info['id'], 'profile-Foo:foo') + self.assertEqual(info['title'], 'Foo') + self.assertEqual(info['type'], 'base') + + def test_listContextInfos_with_registered_extension_profile(self): + from ..interfaces import EXTENSION + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + 'Foo', EXTENSION) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + infos = tool.listContextInfos() + self.assertEqual(len(infos), 1) + info = infos[0] + self.assertEqual(info['id'], 'profile-Foo:foo') + self.assertEqual(info['title'], 'Foo') + self.assertEqual(info['type'], 'extension') + + def test_listContextInfos_with_ordering(self): + from ..interfaces import BASE + from ..interfaces import EXTENSION + + # three extension profiles + profile_registry.registerProfile( + 'bar', 'bar', '', self._PROFILE_PATH, 'bar', EXTENSION) + profile_registry.registerProfile( + 'foo', 'foo', '', self._PROFILE_PATH, 'foo', EXTENSION) + profile_registry.registerProfile( + 'upper', 'UPPER', '', self._PROFILE_PATH, 'UPPER', EXTENSION) + # one base profile + profile_registry.registerProfile( + 'base', 'base', '', self._PROFILE_PATH, 'base', BASE) + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.createSnapshot('UPPER') + tool.createSnapshot('lower') + infos = tool.listContextInfos() + self.assertEqual(len(infos), 6) + # We sort case insensitively, so by lowercase. + # First snapshots. + self.assertEqual(infos[0]['id'], 'snapshot-lower') + self.assertEqual(infos[1]['id'], 'snapshot-UPPER') + # Then base and extension profiles + self.assertEqual(infos[2]['id'], 'profile-bar:bar') + self.assertEqual(infos[3]['id'], 'profile-base:base') + self.assertEqual(infos[4]['id'], 'profile-foo:foo') + self.assertEqual(infos[5]['id'], 'profile-UPPER:upper') + + def test_getProfileImportDate_nonesuch(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool.getProfileImportDate('nonesuch'), None) + + def test_getProfileImportDate_simple_id(self): + from OFS.Image import File + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + filename = 'import-all-foo-20070315123456.log' + tool._setObject(filename, File(filename, '', b'')) + self.assertEqual(tool.getProfileImportDate('foo'), + '2007-03-15T12:34:56Z') + + def test_getProfileImportDate_id_with_colon(self): + from OFS.Image import File + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + filename = 'import-all-foo_bar-20070315123456.log' + tool._setObject(filename, File(filename, '', b'')) + self.assertEqual(tool.getProfileImportDate('foo:bar'), + '2007-03-15T12:34:56Z') + + def test_getProfileImportDate_id_with_prefix(self): + # Test if getProfileImportDate does not fail if there is another + # item id with id with a longer id which starts with the same + # prefix + from OFS.Image import File + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + filename = 'import-all-foo_bar-20070315123456.log' + tool._setObject(filename, File(filename, '', b'')) + filename2 = 'import-all-foo_bar-boo-20070315123456.log' + tool._setObject(filename2, File(filename2, '', b'')) + self.assertEqual(tool.getProfileImportDate('foo:bar'), + '2007-03-15T12:34:56Z') + + def test_profileVersioning(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + profile_id = 'dummy_profile' + product_name = 'GenericSetup' + directory = os.path.split(__file__)[0] + path = os.path.join(directory, 'versioned_profile') + + # register profile + profile_registry.registerProfile(profile_id, + 'Dummy Profile', + 'This is a dummy profile', + path, + product=product_name) + + # register upgrade step + step = UpgradeStep("Upgrade", + "GenericSetup:dummy_profile", '*', '1.1', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step) + + # test initial states + profile_id = ':'.join((product_name, profile_id)) + self.assertEqual(tool.getVersionForProfile(profile_id), '1.1') + self.assertEqual(tool.getLastVersionForProfile(profile_id), + 'unknown') + + # run upgrade steps + request = site.REQUEST + request.form['profile_id'] = profile_id + steps = listUpgradeSteps(tool, profile_id, '1.0') + step_id = steps[0]['id'] + request.form['upgrades'] = [step_id] + tool.manage_doUpgrades() + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '1')) + + def test_get_and_setLastVersionForProfile(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool._profile_upgrade_versions, {}) + # Any 'profile-' is stripped off in these calls. + self.assertEqual(tool.getLastVersionForProfile('foo'), 'unknown') + self.assertEqual(tool.getLastVersionForProfile( + 'profile-foo'), 'unknown') + tool.setLastVersionForProfile('foo', '1.0') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('1', '0')) + self.assertEqual(tool.getLastVersionForProfile( + 'profile-foo'), ('1', '0')) + tool.setLastVersionForProfile('profile-foo', '2.0') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('2', '0')) + self.assertEqual(tool.getLastVersionForProfile( + 'profile-foo'), ('2', '0')) + + # Setting the profile to unknown, removes it from the versions. + self.assertEqual(tool._profile_upgrade_versions, {'foo': ('2', '0')}) + tool.setLastVersionForProfile('profile-foo', 'unknown') + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_unsetLastVersionForProfile(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.setLastVersionForProfile('foo', '1.0') + tool.setLastVersionForProfile('bar', '2.0') + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0'), 'bar': ('2', '0')}) + + # Any 'profile-' is stripped off in these calls. + tool.unsetLastVersionForProfile('profile-foo') + self.assertEqual(tool._profile_upgrade_versions, + {'bar': ('2', '0')}) + tool.unsetLastVersionForProfile('bar') + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_purgeProfileVersions(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.setLastVersionForProfile('foo', '1.0') + tool.setLastVersionForProfile('bar', '2.0') + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0'), 'bar': ('2', '0')}) + tool.purgeProfileVersions() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_listProfilesWithUpgrades(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool.listProfilesWithUpgrades(), []) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + profile_id = 'dummy_profile' + product_name = 'GenericSetup' + directory = os.path.split(__file__)[0] + path = os.path.join(directory, 'versioned_profile') + + # register profile + profile_registry.registerProfile(profile_id, + 'Dummy Profile', + 'This is a dummy profile', + path, + product=product_name) + self.assertEqual(tool.listProfilesWithUpgrades(), []) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # register upgrade step + step1 = UpgradeStep("Upgrade 1", + "GenericSetup:dummy_profile", '*', '1.1', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step1) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # register another upgrade step + step2 = UpgradeStep("Upgrade 2", + "GenericSetup:dummy_profile", '1.1', '1.2', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step2) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # get full profile id + profile_id = ':'.join((product_name, profile_id)) + + # Pretend the profile was installed + tool.setLastVersionForProfile(profile_id, '1.0') + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), True) + + # run first upgrade step + request = site.REQUEST + request.form['profile_id'] = profile_id + steps = listUpgradeSteps(tool, profile_id, '1.0') + step_id = steps[0]['id'] + request.form['upgrades'] = [step_id] + tool.manage_doUpgrades() + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '1')) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), True) + + # run second upgrade step + request = site.REQUEST + request.form['profile_id'] = profile_id + steps = listUpgradeSteps(tool, profile_id, '1.1') + step_id = steps[0]['id'] + request.form['upgrades'] = [step_id] + tool.manage_doUpgrades() + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '2')) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # Pretend the profile was never installed. + tool.unsetLastVersionForProfile(profile_id) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + def test_hasPendingUpgrades(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + profile_id_1 = 'dummy_profile1' + profile_id_2 = 'dummy_profile2' + product_name = 'GenericSetup' + directory = os.path.split(__file__)[0] + path = os.path.join(directory, 'versioned_profile') + + # register profiles + profile_registry.registerProfile(profile_id_1, + 'Dummy Profile 1', + 'This is dummy profile 1', + path, + product=product_name) + profile_registry.registerProfile(profile_id_2, + 'Dummy Profile 2', + 'This is dummy profile 2', + path, + product=product_name) + + # get full profile ids + profile_id_1 = ':'.join((product_name, profile_id_1)) + profile_id_2 = ':'.join((product_name, profile_id_2)) + + # test + self.assertEqual(tool.hasPendingUpgrades(), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + self.assertEqual(tool.hasPendingUpgrades('non-existing'), False) + + # register upgrade steps + step1 = UpgradeStep("Upgrade 1", + profile_id_1, '*', '1.1', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step1) + step2 = UpgradeStep("Upgrade 2", + profile_id_2, '*', '2.2', '', + dummy_upgrade, + None, "2") + _registerUpgradeStep(step2) + # No profile has been applied, so no upgrade is pending. + self.assertEqual(tool.hasPendingUpgrades(), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + + # Pretend profile 1 was installed to an earlier version. + tool.setLastVersionForProfile(profile_id_1, '1.0') + self.assertEqual(tool.hasPendingUpgrades(), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + + # Pretend profile 2 was installed to an earlier version. + tool.setLastVersionForProfile(profile_id_2, '2.0') + self.assertEqual(tool.hasPendingUpgrades(), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), True) + + # Pretend profile 1 was installed to the final version. + tool.setLastVersionForProfile(profile_id_1, '1.1') + self.assertEqual(tool.hasPendingUpgrades(), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), True) + + # Pretend profile 2 was installed to the final version. + tool.setLastVersionForProfile(profile_id_2, '2.2') + self.assertEqual(tool.hasPendingUpgrades(), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + + def test_manage_doUpgrades_no_profile_id_or_updates(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.manage_doUpgrades() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_manage_doUpgrades_upgrade_w_no_target_version(self): + def notool(): + return None + step = UpgradeStep('TITLE', 'foo', '*', '*', 'DESC', notool) + _registerUpgradeStep(step) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + request = site.REQUEST + request['profile_id'] = ['foo'] + request['upgrade'] = [step.id] + tool.manage_doUpgrades() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_upgradeProfile_no_profile_id_or_updates(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + # Mostly this checks to see if we can call this without an + # exception. + tool.upgradeProfile('no.such.profile:default') + self.assertEqual(tool._profile_upgrade_versions, {}) + tool.upgradeProfile('no.such.profile:default', dest='42') + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_persistent_profile_upgrade_versions(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + savepoint1 = transaction.savepoint() + tool.setLastVersionForProfile('foo', '1.0') + savepoint2 = transaction.savepoint() + tool.setLastVersionForProfile('bar', '2.0') + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0'), 'bar': ('2', '0')}) + savepoint2.rollback() + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0')}) + savepoint1.rollback() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_separate_profile_upgrade_versions(self): + # _profile_upgrade_versions used to be a class property. That is fine + # as long as we only work on copies, otherwise state is shared between + # two instances. We now create the property in the __init__ method, + # but let's test it to avoid a regression. + site = self._makeSite() + site.setup_tool1 = self._makeOne('setup_tool1') + tool1 = site.setup_tool1 + site.setup_tool2 = self._makeOne('setup_tool2') + tool2 = site.setup_tool2 + tool1._profile_upgrade_versions['foo'] = '1.0' + self.assertEqual(tool2._profile_upgrade_versions, {}) + tool2.setLastVersionForProfile('bar', '2.0') + self.assertEqual(self._makeOne('t')._profile_upgrade_versions, {}) + + def test_upgradeProfile(self): + def dummy_handler(tool): + return None + + def step3_handler(tool): + tool._step3_applied = 'just a marker' + + def step3_checker(tool): + # False means already applied or does not apply. + # True means can be applied. + return not hasattr(tool, '_step3_applied') + + step1 = UpgradeStep('Step 1', 'foo', '0', '1', 'DESC', + dummy_handler) + step2 = UpgradeStep('Step 2', 'foo', '1', '2', 'DESC', + dummy_handler) + step3 = UpgradeStep('Step 3', 'foo', '2', '3', 'DESC', + step3_handler, checker=step3_checker) + step4 = UpgradeStep('Step 4', 'foo', '3', '4', 'DESC', + dummy_handler) + _registerUpgradeStep(step1) + _registerUpgradeStep(step2) + _registerUpgradeStep(step3) + _registerUpgradeStep(step4) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool.getLastVersionForProfile('foo'), 'unknown') + tool.setLastVersionForProfile('foo', '0') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('0',)) + # Upgrade the profile one step to version 1. + tool.upgradeProfile('foo', '1') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('1',)) + # Upgrade the profile two steps to version 3. This one has a + # checker. The profile version must be correctly updated. + tool.upgradeProfile('foo', '3') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('3',)) + # Upgrade the profile to a non existing version. Nothing + # should happen. + tool.upgradeProfile('foo', '5') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('3',)) + # Upgrade the profile to the latest version. + tool.upgradeProfile('foo') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('4',)) + + def test_listExportSteps(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + result = tool.listExportSteps() + self.assertEqual(len(result), 4) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'step_registries' in result) + self.assertTrue(u'toolset' in result) + + tool._export_registry.registerStep(u'foo', handler='foo.export') + tool._export_registry.registerStep(u'toolset', + handler='toolset.export') + result = tool.listExportSteps() + self.assertEqual(len(result), 5) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'foo' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'step_registries' in result) + self.assertTrue(u'toolset' in result) + + def test_getSortedImportSteps(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + result = tool.getSortedImportSteps() + self.assertEqual(len(result), 3) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'toolset' in result) + self.assertTrue(list(result).index(u'componentregistry') > + list(result).index(u'toolset')) + + tool._import_registry.registerStep(u'foo', handler='foo.import') + tool._import_registry.registerStep(u'toolset', + handler='toolset.import') + result = tool.getSortedImportSteps() + self.assertEqual(len(result), 4) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'foo' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'toolset' in result) + self.assertTrue(list(result).index(u'componentregistry') > + list(result).index(u'toolset')) + + def test_listProfileInfo_for_parameter(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + for_=ISite) + # tool.listProfileInfo should call registry.listProfileInfo + # with the for_ parameter + self.assertEqual(len(tool.listProfileInfo()), 1) + self.assertEqual(len(tool.listProfileInfo(for_=ISite)), 1) + self.assertEqual(len(tool.listProfileInfo(for_=IDerivedSite)), 1) + self.assertEqual(len(tool.listProfileInfo(for_=IAnotherSite)), 0) + + def test_profileExists(self): + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register two extension profiles. Profile 'foo' has a dependency + # 'bar'. + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=EXTENSION) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + + self.assertTrue(tool.profileExists('other:foo')) + self.assertTrue(tool.profileExists('other:bar')) + self.assertFalse(tool.profileExists('snapshot-something')) + self.assertFalse(tool.profileExists(None)) + self.assertFalse(tool.profileExists('nonesuch')) + + def test_getDependenciesForProfile(self): + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register three extension profiles. Profile 'foo' has a dependency + # 'bar', and 'baz' contains non-existing dependency-profiles. + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _BROKEN_METADATA_XML) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=EXTENSION) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + profile_registry.registerProfile( + 'baz', 'Baz', '', self._PROFILE_PATH3, profile_type=EXTENSION) + + self.assertEqual(tool.getDependenciesForProfile('other:foo'), + (u'profile-other:bar', )) + self.assertEqual(tool.getDependenciesForProfile('other:bar'), ()) + self.assertEqual(tool.getDependenciesForProfile('snapshot-some'), ()) + self.assertEqual(tool.getDependenciesForProfile(None), ()) + self.assertRaises(KeyError, tool.getDependenciesForProfile, 'nonesuch') + + def test_getBrokenDependencies(self): + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register three extension profiles. Profile 'foo' has a dependency + # 'bar' and 'baz' contains non-existing dependency-profiles. + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _BROKEN_METADATA_XML) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=EXTENSION) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + profile_registry.registerProfile( + 'baz', 'Baz', '', self._PROFILE_PATH3, profile_type=EXTENSION) + + # profile has dependencies and none of them is broken: + self.assertFalse(tool.hasBrokenDependencies('other:foo')) + # profile has no dependencies, therfore nothing can be broken: + self.assertFalse(tool.hasBrokenDependencies('other:bar')) + # profile has dependencies and at least one of them is broken: + self.assertTrue(tool.hasBrokenDependencies('other:baz')) +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `function:SetupToolTests.check_restricted_access` (lines 476-483) + +```python + def check_restricted_access(self, obj): + # For most objects that we create, we do not want ordinary users to + # see it, also not when they have View permission on a higher level. + rop_info = obj.rolesOfPermission(view) + allowed_roles = sorted([x['name'] for x in rop_info + if x['selected']]) + self.assertEqual(allowed_roles, ['Manager', 'Owner']) + self.assertFalse(obj.acquiredRolesAreUsedBy(view)) +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `function:SetupToolTests.test_runAllImportStepsFromProfile_unicode_id_creates_reports` (lines 485-509) + +```python + def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): + + TITLE = 'original title' + PROFILE_ID = u'snapshot-testing' + site = self._makeSite(TITLE) + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + tool.runAllImportStepsFromProfile(PROFILE_ID) + + prefix = str('import-all-%s' % PROFILE_ID) + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + + # Check acess restriction on log files + logged = [x for x in tool.objectIds('File')] + for file_id in logged: + file_ob = tool._getOb(file_id) + self.check_restricted_access(file_ob) +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `function:SetupToolTests.test_createSnapshot_default` (lines 1055-1116) + +```python + def test_createSnapshot_default(self): + _EXPECTED = [ + ('import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML), + ('export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML), + ('rolemap.xml', 'dummy'), + ('toolset.xml', 'dummy'), + ] + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + tool._export_registry.registerStep( + 'step_registries', + 'Products.GenericSetup.tool.exportStepRegistries', + 'Export import / export steps.') + + self.assertEqual(len(tool.listSnapshotInfo()), 0) + + result = tool.createSnapshot('default') + + self.assertEqual( + sorted(result['steps']), + ['componentregistry', 'rolemap', 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + + snapshot = result['snapshot'] + + self.assertEqual(len(snapshot.objectIds()), len(_EXPECTED)) + + for id in [x[0] for x in _EXPECTED]: + self.assertTrue(id in snapshot.objectIds()) + + def normalize_xml(xml): + # using this might mask a real problem on windows, but so far the + # different newlines just caused problems in this test + lines = [line.strip() for line in xml.splitlines() if line.strip()] + return ' '.join(lines) + + fileobj = snapshot._getOb('import_steps.xml') + self.assertEqual(normalize_xml(fileobj.read()), + normalize_xml(_DEFAULT_STEP_REGISTRIES_IMPORT_XML)) + + fileobj = snapshot._getOb('export_steps.xml') + self.assertEqual(normalize_xml(fileobj.read()), + normalize_xml(_DEFAULT_STEP_REGISTRIES_EXPORT_XML)) + + self.assertEqual(len(tool.listSnapshotInfo()), 1) + + info = tool.listSnapshotInfo()[0] + + self.assertEqual(info['id'], 'default') + self.assertEqual(info['title'], 'default') + + # Check access restriction on snapshot files and folders + self.check_restricted_access(tool.snapshots) + self.check_restricted_access(snapshot) + for obj in snapshot.objectValues(): + self.check_restricted_access(obj) + if hasattr(aq_base(obj), 'objectValues'): + for child in obj.objectValues(): + self.check_restricted_access(child) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..57dc3821b805132d723bd62abec5174727e8c290 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/pre_context.md @@ -0,0 +1,1879 @@ +# Patch-overlapping Python context before the fix + +## `src/Products/GenericSetup/context.py` — `class:SnapshotExportContext` (lines 471-565) + +```python +class SnapshotExportContext(BaseContext): + + security = ClassSecurityInfo() + + def __init__(self, tool, snapshot_id, encoding=None): + + BaseContext.__init__(self, tool, encoding) + self._snapshot_id = snapshot_id + + @security.protected(ManagePortal) + def writeDataFile(self, filename, text, content_type, subdir=None): + """ See IExportContext. + """ + if subdir is not None: + filename = '/'.join((subdir, filename)) + + sep = filename.rfind('/') + if sep != -1: + subdir = filename[:sep] + filename = filename[sep+1:] + + if six.PY2 and isinstance(text, six.text_type): + encoding = self.getEncoding() or 'utf-8' + text = text.encode(encoding) + + folder = self._ensureSnapshotsFolder(subdir) + + # MISSING: switch on content_type + ob = self._createObjectByType(filename, text, content_type) + folder._setObject(str(filename), ob) # No Unicode IDs! + + @security.protected(ManagePortal) + def getSnapshotURL(self): + """ See IExportContext. + """ + return '%s/%s' % (self._tool.absolute_url(), self._snapshot_id) + + @security.protected(ManagePortal) + def getSnapshotFolder(self): + """ See IExportContext. + """ + return self._ensureSnapshotsFolder() + + # + # Helper methods + # + @security.private + def _createObjectByType(self, name, body, content_type): + encoding = self.getEncoding() or 'utf-8' + + if six.PY2 and isinstance(body, six.text_type): + body = body.encode(encoding) + + if name.endswith('.py'): + ob = PythonScript(name) + ob.write(body) + return ob + + if name.endswith('.dtml'): + ob = DTMLDocument('', __name__=name) + ob.munge(body) + return ob + + if content_type in ('text/html', 'text/xml'): + return ZopePageTemplate(name, body, content_type=content_type) + + if isinstance(body, six.text_type): + body = body.encode(encoding) + + if content_type[:6] == 'image/': + return Image(name, '', body, content_type=content_type) + + return File(name, '', body, content_type=content_type) + + @security.private + def _ensureSnapshotsFolder(self, subdir=None): + """ Ensure that the appropriate snapshot folder exists. + """ + path = ['snapshots', self._snapshot_id] + + if subdir is not None: + path.extend(subdir.split('/')) + + current = self._tool + + for element in path: + + if element not in current.objectIds(): + # No Unicode IDs! + current._setObject(str(element), Folder(element)) + + current = current._getOb(element) + + return current +``` + +## `src/Products/GenericSetup/context.py` — `function:SnapshotExportContext._ensureSnapshotsFolder` (lines 546-565) + +```python + def _ensureSnapshotsFolder(self, subdir=None): + """ Ensure that the appropriate snapshot folder exists. + """ + path = ['snapshots', self._snapshot_id] + + if subdir is not None: + path.extend(subdir.split('/')) + + current = self._tool + + for element in path: + + if element not in current.objectIds(): + # No Unicode IDs! + current._setObject(str(element), Folder(element)) + + current = current._getOb(element) + + return current +``` + +## `src/Products/GenericSetup/context.py` — `module:@29` (lines 29-29) + +```python +from AccessControl.SecurityInfo import ClassSecurityInfo +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `class:SetupToolTests` (lines 111-1772) + +```python +class SetupToolTests(FilesystemTestBase, TarballTester, ConformsToISetupTool): + + layer = ExportImportZCMLLayer + + _PROFILE_PATH = tempfile.mkdtemp(prefix='STT_test') + _PROFILE_PATH2 = tempfile.mkdtemp(prefix='STT_test2') + _PROFILE_PATH3 = tempfile.mkdtemp(prefix='STT_test3') + + def afterSetUp(self): + from ..upgrade import _upgrade_registry + _upgrade_registry.clear() + profile_registry.clear() + global _before_import_events + global _after_import_events + _before_import_events = [] + provideHandler(handleBeforeProfileImportEvent) + _after_import_events = [] + provideHandler(handleProfileImportedEvent) + + def beforeTearDown(self): + base_registry.unregisterHandler(handleBeforeProfileImportEvent) + base_registry.unregisterHandler(handleProfileImportedEvent) + FilesystemTestBase.beforeTearDown(self) + from ..upgrade import _upgrade_registry + profile_registry.clear() + _upgrade_registry.clear() + noSecurityManager() + + def _getTargetClass(self): + from ..tool import SetupTool + + return SetupTool + + def _makeSite(self, title="Don't care"): + + site = Folder() + site._setId('site') + site.title = title + + self.app._setObject('site', site) + self.app.acl_users.userFolderAddUser('admin', '', ['Manager'], []) + newSecurityManager(None, self.app.acl_users.getUser('admin')) + return self.app._getOb('site') + + def test_empty(self): + + tool = self._makeOne('setup_tool') + + self.assertEqual(tool.getBaselineContextID(), '') + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 0) + + export_registry = tool.getExportStepRegistry() + export_steps = export_registry.listSteps() + self.assertEqual(len(export_steps), 0) + + toolset_registry = tool.getToolsetRegistry() + self.assertEqual(len(toolset_registry.listForbiddenTools()), 0) + self.assertEqual(len(toolset_registry.listRequiredTools()), 0) + + def test_getBaselineContextID(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + tool = self._makeOne('setup_tool') + + self._makeFile(IMPORT_STEPS_XML, _EMPTY_IMPORT_XML) + self._makeFile(EXPORT_STEPS_XML, _EMPTY_EXPORT_XML) + self._makeFile(TOOLSET_XML, _EMPTY_TOOLSET_XML) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + tool.setBaselineContext('profile-other:foo') + + self.assertEqual(tool.getBaselineContextID(), 'profile-other:foo') + + def test_setBaselineContext_invalid(self): + + tool = self._makeOne('setup_tool') + + self.assertRaises(KeyError, tool.setBaselineContext, 'profile-foo') + + def test_setBaselineContext_empty_string(self): + + tool = self._makeOne('setup_tool') + + self.assertRaises(KeyError, tool.setBaselineContext, '') + + def test_setBaselineContext(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + tool = self._makeOne('setup_tool') + tool.getExportStepRegistry().clear() + + self._makeFile(IMPORT_STEPS_XML, _SINGLE_IMPORT_XML) + self._makeFile(EXPORT_STEPS_XML, _SINGLE_EXPORT_XML) + self._makeFile(TOOLSET_XML, _NORMAL_TOOLSET_XML) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + tool.setBaselineContext('profile-other:foo') + + self.assertEqual(tool.getBaselineContextID(), 'profile-other:foo') + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = import_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertEqual(info['version'], '1') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(import_registry.getStep('one'), ONE_FUNC) + + export_registry = tool.getExportStepRegistry() + self.assertEqual(len(export_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = export_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(export_registry.getStep('one'), ONE_FUNC) + + def test_runImportStepFromProfile_nonesuch(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + + self.assertRaises(KeyError, tool.runImportStepFromProfile, + '', 'nonesuch') + + def test_runImportStepFromProfile_simple(self): + + TITLE = 'original title' + site = self._makeSite(TITLE) + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('simple', '1', _uppercaseSiteTitle) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'simple') + + self.assertEqual(len(result['steps']), 1) + + self.assertEqual(result['steps'][0], 'simple') + self.assertEqual(result['messages']['simple'], 'Uppercased title') + + self.assertEqual(site.title, TITLE.upper()) + + global _before_import_events + self.assertEqual(len(_before_import_events), 1) + self.assertEqual(_before_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_before_import_events[0].steps, ['simple']) + self.assertEqual(_before_import_events[0].full_import, False) + + global _after_import_events + self.assertEqual(len(_after_import_events), 1) + self.assertEqual(_after_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_after_import_events[0].steps, ['simple']) + self.assertEqual(_after_import_events[0].full_import, False) + + def test_runImportStepFromProfile_dependencies(self): + + TITLE = 'original title' + site = self._makeSite(TITLE) + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('dependable', '1', _underscoreSiteTitle) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'dependent') + + self.assertEqual(len(result['steps']), 2) + + self.assertEqual(result['steps'][0], 'dependable') + self.assertEqual(result['messages']['dependable'], 'Underscored title') + + self.assertEqual(result['steps'][1], 'dependent') + self.assertEqual(result['messages']['dependent'], 'Uppercased title') + self.assertEqual(site.title, TITLE.replace(' ', '_').upper()) + + global _before_import_events + self.assertEqual(len(_before_import_events), 1) + self.assertEqual(_before_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_before_import_events[0].steps, + ['dependable', 'dependent']) + self.assertEqual(_before_import_events[0].full_import, False) + + global _after_import_events + self.assertEqual(len(_after_import_events), 1) + self.assertEqual(_after_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_after_import_events[0].steps, + ['dependable', 'dependent']) + self.assertEqual(_after_import_events[0].full_import, False) + + def test_runImportStepFromProfile_skip_dependencies(self): + + TITLE = 'original title' + site = self._makeSite(TITLE) + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('dependable', '1', _underscoreSiteTitle) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'dependent', + run_dependencies=False) + + self.assertEqual(len(result['steps']), 1) + + self.assertEqual(result['steps'][0], 'dependent') + self.assertEqual(result['messages']['dependent'], 'Uppercased title') + + self.assertEqual(site.title, TITLE.upper()) + + global _before_import_events + self.assertEqual(len(_before_import_events), 1) + self.assertEqual(_before_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_before_import_events[0].steps, ['dependent']) + self.assertEqual(_before_import_events[0].full_import, False) + + global _after_import_events + self.assertEqual(len(_after_import_events), 1) + self.assertEqual(_after_import_events[0].profile_id, 'snapshot-dummy') + self.assertEqual(_after_import_events[0].steps, ['dependent']) + self.assertEqual(_after_import_events[0].full_import, False) + + def test_runImportStepFromProfile_default_purge(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'purging') + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + self.assertTrue(site.purged) + + def test_runImportStepFromProfile_explicit_purge(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'purging', + purge_old=True) + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + self.assertTrue(site.purged) + + def test_runImportStepFromProfile_skip_purge(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runImportStepFromProfile('snapshot-dummy', 'purging', + purge_old=False) + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Unpurged') + self.assertFalse(site.purged) + + def test_runImportStepFromProfile_consistent_context(self): + + site = self._makeSite() + + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep('purging', '1', _purgeIfRequired) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('purging', )) + + tool.runImportStepFromProfile('snapshot-dummy', 'dependent', + purge_old=False) + self.assertFalse(site.purged) + + def test_runAllImportStepsFromProfile_empty(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + result = tool.runAllImportStepsFromProfile('snapshot-dummy') + + self.assertEqual(len(result['steps']), 3) + + def test_runAllImportStepsFromProfile_inquicksuccession(self): + """ + This test provokes an issue that only appears in testing. + There it can happen that profiles get run multiple times within + a second. As of 1.6.3, genericsetup does not handle this. + """ + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + tool.runAllImportStepsFromProfile('snapshot-dummy') + tool.runAllImportStepsFromProfile('snapshot-dummy') + # For good measurement + tool.runAllImportStepsFromProfile('snapshot-dummy') + + self.assertTrue("No exception thrown") + + def test_runAllImportStepsFromProfile_sorted_default_purge(self): + + TITLE = 'original title' + PROFILE_ID = 'snapshot-testing' + site = self._makeSite(TITLE) + tool = self._makeOne('setup_tool').__of__(site) + tool._exclude_global_steps = True + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runAllImportStepsFromProfile(PROFILE_ID) + + self.assertEqual(len(result['steps']), 3) + + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + + self.assertEqual(result['steps'][1], 'dependable') + self.assertEqual(result['messages']['dependable'], 'Underscored title') + + self.assertEqual(result['steps'][2], 'dependent') + self.assertEqual(result['messages']['dependent'], 'Uppercased title') + + self.assertEqual(site.title, TITLE.replace(' ', '_').upper()) + self.assertTrue(site.purged) + + prefix = 'import-all-%s' % PROFILE_ID + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + + def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): + + TITLE = 'original title' + PROFILE_ID = u'snapshot-testing' + site = self._makeSite(TITLE) + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + tool.runAllImportStepsFromProfile(PROFILE_ID) + + prefix = str('import-all-%s' % PROFILE_ID) + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + + # Check acess restriction on log files + logged = [x for x in tool.objectIds('File')] + for file_id in logged: + file_ob = tool._getOb(file_id) + rop_info = file_ob.rolesOfPermission(view) + allowed_roles = sorted([x['name'] for x in rop_info + if x['selected']]) + self.assertEqual(allowed_roles, ['Manager', 'Owner']) + self.assertFalse(file_ob.acquiredRolesAreUsedBy(view)) + + def test_runAllImportStepsFromProfile_sorted_explicit_purge(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool._exclude_global_steps = True + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runAllImportStepsFromProfile('snapshot-dummy', + purge_old=True) + + self.assertEqual(len(result['steps']), 3) + + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Purged') + + self.assertEqual(result['steps'][1], 'dependable') + self.assertEqual(result['steps'][2], 'dependent') + self.assertTrue(site.purged) + + def test_runAllImportStepsFromProfile_sorted_skip_purge(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool._exclude_global_steps = True + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + result = tool.runAllImportStepsFromProfile('snapshot-dummy', + purge_old=False) + + self.assertEqual(len(result['steps']), 3) + + self.assertEqual(result['steps'][0], 'purging') + self.assertEqual(result['messages']['purging'], 'Unpurged') + + self.assertEqual(result['steps'][1], 'dependable') + self.assertEqual(result['steps'][2], 'dependent') + self.assertFalse(site.purged) + + def test_runAllImportStepsFromProfile_without_depends(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + + _imported = [] + + def applyContext(context): + _imported.append(context._profile_path) + + tool.applyContext = applyContext + tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=True) + self.assertEqual(_imported, [self._PROFILE_PATH]) + + def test_runAllImportStepsFromProfile_with_depends(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + profile_registry.registerProfile('bar', 'Bar', '', self._PROFILE_PATH2) + + _imported = [] + + def applyContext(context): + _imported.append(context._profile_path) + + tool.applyContext = applyContext + tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=False) + self.assertEqual(_imported, [self._PROFILE_PATH2, self._PROFILE_PATH]) + + def _setup_dependency_strategy_test_tool(self): + # If we add a dependency profile in our metadata.xml, and this + # dependency was already applied, then we do not need to apply + # it yet again. Once is quite enough, thank you. Running any + # upgrade steps would be nice though. There are options. + # Setup a tool and profiles for testing dependency strategies. + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + self._makeFile(METADATA_XML, _DOUBLE_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _PLAIN_METADATA_XML) + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register main profile and two dependency profiles. + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + profile_type=EXTENSION) + profile_registry.registerProfile('bar', 'Bar', '', self._PROFILE_PATH2, + profile_type=EXTENSION) + profile_registry.registerProfile('ham', 'Ham', '', self._PROFILE_PATH3, + profile_type=EXTENSION) + + # Apply the second profile. + tool.runAllImportStepsFromProfile('profile-other:bar') + + # Register an upgrade step. Note that applying this step will + # set the profile version to 1.1, even though the metadata of + # the profile really says 1.0. We will use this to check + # whether the upgrade step has been applied (version is 1.1) + # or the full profile has been applied (version is 1.0). + step_bar = UpgradeStep( + "Upgrade", "other:bar", '1.0', '1.1', '', dummy_upgrade, None, "1") + _registerUpgradeStep(step_bar) + # And another one. + step_ham = UpgradeStep( + "Upgrade", "other:ham", '1.0', '1.1', '', dummy_upgrade, None, "1") + _registerUpgradeStep(step_ham) + + # Gather list of imported profiles. + tool._imported = [] + + def applyContext(context): + tool._imported.append(context._profile_path) + + tool.applyContext = applyContext + + return tool + + def test_runAllImportStepsFromProfile_with_default_strategy(self): + # Default strategy: apply new profiles, upgrade old profiles. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + tool.runAllImportStepsFromProfile('profile-other:foo') + # The main and third profile have been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH3, self._PROFILE_PATH]) + # The upgrade step of the second profile has been applied, + # pushing it to version 1.1. + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '1')) + # Third profile is at 1.0. + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('1', '0')) + + def test_runAllImportStepsFromProfile_with_reapply_strategy(self): + # You can choose the old behavior of always applying the + # dependencies. This ignores any upgrade steps. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + from ..tool import DEPENDENCY_STRATEGY_REAPPLY + tool.runAllImportStepsFromProfile( + 'profile-other:foo', + dependency_strategy=DEPENDENCY_STRATEGY_REAPPLY) + # All three profiles have been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH2, self._PROFILE_PATH3, + self._PROFILE_PATH]) + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '0')) + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('1', '0')) + + def test_runAllImportStepsFromProfile_with_new_strategy(self): + # You can choose to be happy with any applied version and + # ignore any upgrade steps. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + from ..tool import DEPENDENCY_STRATEGY_NEW + tool.runAllImportStepsFromProfile( + 'profile-other:foo', + dependency_strategy=DEPENDENCY_STRATEGY_NEW) + # The main and third profile have been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH3, self._PROFILE_PATH]) + # Second profile stays at 1.0. + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '0')) + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('1', '0')) + + def test_runAllImportStepsFromProfile_with_ignore_strategy(self): + # You can choose to be ignore all dependency profiles. + tool = self._setup_dependency_strategy_test_tool() + + # Run the main profile. + from ..tool import DEPENDENCY_STRATEGY_IGNORE + tool.runAllImportStepsFromProfile( + 'profile-other:foo', + dependency_strategy=DEPENDENCY_STRATEGY_IGNORE) + # Only the main profile has been applied. + self.assertEqual(tool._imported, + [self._PROFILE_PATH]) + # Second profile stays at 1.0. + self.assertEqual(tool.getLastVersionForProfile('other:bar'), + ('1', '0')) + # Third profile is not applied. + self.assertEqual(tool.getLastVersionForProfile('other:ham'), + ('unknown')) + + def test_runAllImportStepsFromProfile_unknown_strategy(self): + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + self.assertRaises(ValueError, tool.runAllImportStepsFromProfile, + 'profile-other:foo', dependency_strategy='random') + + def test_runAllImportStepsFromProfile_set_last_profile_version(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + + # test initial states + profile_id = "other:foo" + self.assertEqual(tool.getVersionForProfile(profile_id), '1.0') + self.assertEqual(tool.getLastVersionForProfile(profile_id), + 'unknown') + + # run all imports steps + tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=True) + + # events.handleProfileImportedEvent should set last profile version + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '0')) + + def test_runAllImportStepsFromProfile_step_registration_with_depends(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + _IMPORT_STEPS_XML = """ + + + One small step + + +""" + self._makeFile('import_steps.xml', _IMPORT_STEPS_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH) + profile_registry.registerProfile('bar', 'Bar', '', self._PROFILE_PATH2) + + result = tool.runAllImportStepsFromProfile('profile-other:foo', + ignore_dependencies=False) + + # ensure the additional step on foo was imported + self.assertTrue('one' in result['steps']) + + def test_runAllImportStepsFromProfile_skipStep(self): + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + result = tool.runAllImportStepsFromProfile( + 'snapshot-dummy', + blacklisted_steps=['toolset'], + ) + + self.assertEqual((result['messages']['toolset']), 'step skipped') + + def test_runAllImportStepsFromProfile_with_base_profile(self): + # Applying a base profile should clear the profile upgrade + # versions. + from ..interfaces import BASE + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _PLAIN_METADATA_XML) + + # Register a base and two extension profile. The base profile + # 'foo' has a dependency 'bar'. This might not make sense, + # but it will serve to check that we clear the profile + # versions right before we apply the base profile, which means + # right after any dependency profiles. + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=BASE) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + profile_registry.registerProfile( + 'ham', 'Ham', '', self._PROFILE_PATH3, profile_type=EXTENSION) + # Apply the extension profile. + tool.runAllImportStepsFromProfile('profile-other:ham') + self.assertEqual(tool._profile_upgrade_versions, + {u'other:ham': (u'1', u'0')}) + # Apply the base profile. + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool._profile_upgrade_versions, + {u'other:foo': (u'1', u'0')}) + + def test_runAllImportStepsFromProfile_with_unknown_pre_handler(self): + # Registering already fails. + self.assertRaises( + ValueError, profile_registry.registerProfile, + 'foo', 'Foo', '', self._PROFILE_PATH, + pre_handler='Products.GenericSetup.tests.test_tool.foo_handler') + + def test_runAllImportStepsFromProfile_with_unknown_post_handler(self): + # Registering already fails. + self.assertRaises( + ValueError, profile_registry.registerProfile, + 'foo', 'Foo', '', self._PROFILE_PATH, + post_handler='Products.GenericSetup.tests.test_tool.foo_handler') + + def test_runAllImportStepsFromProfile_pre_post_handlers_dotted_names(self): + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, + pre_handler='Products.GenericSetup.tests.test_tool.pre_handler', + post_handler='Products.GenericSetup.tests.test_tool.post_handler') + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 1) + self.assertEqual(tool.post_handler_called, 1) + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 2) + self.assertEqual(tool.post_handler_called, 2) + + def test_runAllImportStepsFromProfile_pre_post_handlers_functions(self): + # When you register a profile with pre/post handlers in zcml, you do + # not get dotted names (strings) but an actual function. + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, + pre_handler=pre_handler, + post_handler=post_handler) + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 1) + self.assertEqual(tool.post_handler_called, 1) + tool.runAllImportStepsFromProfile('profile-other:foo') + self.assertEqual(tool.pre_handler_called, 2) + self.assertEqual(tool.post_handler_called, 2) + + def test_runExportStep_nonesuch(self): + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + self.assertRaises(ValueError, tool.runExportStep, 'nonesuch') + + def test_runExportStep_step_registry_empty(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + + result = tool.runExportStep('step_registries') + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'step_registries') + self.assertEqual(result['messages']['step_registries'], None) + + def test_runExportStep_step_registry_default(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + steps = 'Products.GenericSetup.tool.exportStepRegistries' + tool._export_registry.registerStep('step_registries', steps, + 'Export import / export steps.') + + result = tool.runExportStep('step_registries') + + self.assertEqual(len(result['steps']), 1) + self.assertEqual(result['steps'][0], 'step_registries') + self.assertEqual(result['messages']['step_registries'], None) + fileish = BytesIO(result['tarball']) + + self._verifyTarballContents(fileish, + ['import_steps.xml', 'export_steps.xml']) + self._verifyTarballEntryXML( + fileish, 'import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML) + self._verifyTarballEntryXML( + fileish, 'export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML) + + def test_runAllExportSteps_empty(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + + result = tool.runAllExportSteps() + + self.assertEqual( + sorted(result['steps']), + ['componentregistry', 'rolemap', 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + + def test_runAllExportSteps_default(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + steps = 'Products.GenericSetup.tool.exportStepRegistries' + tool._export_registry.registerStep('step_registries', steps, + 'Export import / export steps.') + + result = tool.runAllExportSteps() + + self.assertEqual(sorted(result['steps']), + ['componentregistry', 'rolemap', + 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + fileish = BytesIO(result['tarball']) + + self._verifyTarballContents(fileish, + ['import_steps.xml', 'export_steps.xml', + 'rolemap.xml', 'toolset.xml']) + self._verifyTarballEntryXML( + fileish, 'import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML) + self._verifyTarballEntryXML( + fileish, 'export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML) + + def test_runAllExportSteps_extras(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + steps = 'Products.GenericSetup.tool.exportStepRegistries' + tool._export_registry.registerStep('step_registries', steps, + 'Export import / export steps.') + + import_reg = tool.getImportStepRegistry() + import_reg.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + import_reg.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + import_reg.registerStep('purging', '1', _purgeIfRequired) + + export_reg = tool.getExportStepRegistry() + export_reg.registerStep('properties', _exportPropertiesINI) + + result = tool.runAllExportSteps() + + self.assertEqual(len(result['steps']), 5) + self.assertEqual(sorted(result['steps']), + ['componentregistry', 'properties', 'rolemap', + 'step_registries', 'toolset']) + + self.assertEqual(result['messages']['properties'], + 'Exported properties') + self.assertEqual(result['messages']['step_registries'], None) + + fileish = BytesIO(result['tarball']) + + self._verifyTarballContents(fileish, + ['import_steps.xml', 'export_steps.xml', + 'properties.ini', 'rolemap.xml', + 'toolset.xml']) + self._verifyTarballEntryXML( + fileish, 'import_steps.xml', _EXTRAS_STEP_REGISTRIES_IMPORT_XML) + self._verifyTarballEntryXML( + fileish, 'export_steps.xml', _EXTRAS_STEP_REGISTRIES_EXPORT_XML) + ini_string = _PROPERTIES_INI % site.title + self._verifyTarballEntry(fileish, 'properties.ini', + ini_string.encode('utf-8')) + + def test_manage_importTarball(self): + # Tests for importing a tarball with GenericSetup files. + # We are especially interested to see if old settings get purged. + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + # We need to be Manager to see the result of calling + # manage_importTarball. + newSecurityManager(None, UnrestrictedUser('root', '', ['Manager'], '')) + + ROLEMAP_XML = """ + + + + + + +""" + + def rolemap_tarball(name): + # Create a tarball archive with rolemap.xml containing 'name' as + # role. + context = TarballExportContext(tool) + contents = ROLEMAP_XML % name + if isinstance(contents, six.text_type): + contents = contents.encode('utf-8') + context.writeDataFile('rolemap.xml', contents, 'text/xml') + return context.getArchive() + + # Import first role. + tool.manage_importTarball(rolemap_tarball('First')) + self.assertTrue('First' in site.valid_roles()) + + # Import second role. + tool.manage_importTarball(rolemap_tarball('Second')) + self.assertTrue('Second' in site.valid_roles()) + # The first role has been purged, because that is the default. + self.assertFalse('First' in site.valid_roles()) + # A few standard roles are never removed, probably because they are + # defined one level higher. + self.assertTrue('Anonymous' in site.valid_roles()) + self.assertTrue('Authenticated' in site.valid_roles()) + self.assertTrue('Manager' in site.valid_roles()) + self.assertTrue('Owner' in site.valid_roles()) + + # Import third role in non-purge mode. + tool.manage_importTarball(rolemap_tarball('Third'), purge_old=False) + self.assertTrue('Third' in site.valid_roles()) + # The second role is still there. + self.assertTrue('Second' in site.valid_roles()) + + # When you use the form, and uncheck the purge_old checkbox, then the + # browser does not send the purge_old parameter in the request. To + # work around this, the form always passes a hidden 'submitted' + # parameter. + # Import fourth role in non-purge mode with a form submit. + tool.manage_importTarball(rolemap_tarball('Fourth'), submitted='yes') + self.assertTrue('Fourth' in site.valid_roles()) + # The other roles are still there. + self.assertTrue('Second' in site.valid_roles()) + self.assertTrue('Third' in site.valid_roles()) + self.assertTrue('Manager' in site.valid_roles()) + + def test_createSnapshot_default(self): + _EXPECTED = [ + ('import_steps.xml', _DEFAULT_STEP_REGISTRIES_IMPORT_XML), + ('export_steps.xml', _DEFAULT_STEP_REGISTRIES_EXPORT_XML), + ('rolemap.xml', 'dummy'), + ('toolset.xml', 'dummy'), + ] + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool._import_registry.registerStep('foo', handler='foo.bar') + tool._export_registry.registerStep( + 'step_registries', + 'Products.GenericSetup.tool.exportStepRegistries', + 'Export import / export steps.') + + self.assertEqual(len(tool.listSnapshotInfo()), 0) + + result = tool.createSnapshot('default') + + self.assertEqual( + sorted(result['steps']), + ['componentregistry', 'rolemap', 'step_registries', 'toolset']) + self.assertEqual(result['messages']['step_registries'], None) + + snapshot = result['snapshot'] + + self.assertEqual(len(snapshot.objectIds()), len(_EXPECTED)) + + for id in [x[0] for x in _EXPECTED]: + self.assertTrue(id in snapshot.objectIds()) + + def normalize_xml(xml): + # using this might mask a real problem on windows, but so far the + # different newlines just caused problems in this test + lines = [line.strip() for line in xml.splitlines() if line.strip()] + return ' '.join(lines) + + fileobj = snapshot._getOb('import_steps.xml') + self.assertEqual(normalize_xml(fileobj.read()), + normalize_xml(_DEFAULT_STEP_REGISTRIES_IMPORT_XML)) + + fileobj = snapshot._getOb('export_steps.xml') + self.assertEqual(normalize_xml(fileobj.read()), + normalize_xml(_DEFAULT_STEP_REGISTRIES_EXPORT_XML)) + + self.assertEqual(len(tool.listSnapshotInfo()), 1) + + info = tool.listSnapshotInfo()[0] + + self.assertEqual(info['id'], 'default') + self.assertEqual(info['title'], 'default') + + def test_applyContext(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool.getImportStepRegistry().clear() + tool.getExportStepRegistry().clear() + tool.getToolsetRegistry().clear() + + context = DummyImportContext(site, tool=tool) + context._files[IMPORT_STEPS_XML] = _SINGLE_IMPORT_XML + context._files[EXPORT_STEPS_XML] = _SINGLE_EXPORT_XML + context._files[TOOLSET_XML] = _NORMAL_TOOLSET_XML + + tool.applyContext(context) + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = import_registry.getStepMetadata('one') + + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertEqual(info['version'], '1') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(import_registry.getStep('one'), ONE_FUNC) + + export_registry = tool.getExportStepRegistry() + self.assertEqual(len(export_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = export_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(export_registry.getStep('one'), ONE_FUNC) + + def test_listContextInfos_empty(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + infos = tool.listContextInfos() + self.assertEqual(len(infos), 0) + + def test_listContextInfos_with_snapshot(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.createSnapshot('testing') + infos = tool.listContextInfos() + self.assertEqual(len(infos), 1) + info = infos[0] + self.assertEqual(info['id'], 'snapshot-testing') + self.assertEqual(info['title'], 'testing') + self.assertEqual(info['type'], 'snapshot') + + def test_listContextInfos_with_registered_base_profile(self): + from ..interfaces import BASE + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + 'Foo', BASE) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + infos = tool.listContextInfos() + self.assertEqual(len(infos), 1) + info = infos[0] + self.assertEqual(info['id'], 'profile-Foo:foo') + self.assertEqual(info['title'], 'Foo') + self.assertEqual(info['type'], 'base') + + def test_listContextInfos_with_registered_extension_profile(self): + from ..interfaces import EXTENSION + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + 'Foo', EXTENSION) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + infos = tool.listContextInfos() + self.assertEqual(len(infos), 1) + info = infos[0] + self.assertEqual(info['id'], 'profile-Foo:foo') + self.assertEqual(info['title'], 'Foo') + self.assertEqual(info['type'], 'extension') + + def test_listContextInfos_with_ordering(self): + from ..interfaces import BASE + from ..interfaces import EXTENSION + + # three extension profiles + profile_registry.registerProfile( + 'bar', 'bar', '', self._PROFILE_PATH, 'bar', EXTENSION) + profile_registry.registerProfile( + 'foo', 'foo', '', self._PROFILE_PATH, 'foo', EXTENSION) + profile_registry.registerProfile( + 'upper', 'UPPER', '', self._PROFILE_PATH, 'UPPER', EXTENSION) + # one base profile + profile_registry.registerProfile( + 'base', 'base', '', self._PROFILE_PATH, 'base', BASE) + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.createSnapshot('UPPER') + tool.createSnapshot('lower') + infos = tool.listContextInfos() + self.assertEqual(len(infos), 6) + # We sort case insensitively, so by lowercase. + # First snapshots. + self.assertEqual(infos[0]['id'], 'snapshot-lower') + self.assertEqual(infos[1]['id'], 'snapshot-UPPER') + # Then base and extension profiles + self.assertEqual(infos[2]['id'], 'profile-bar:bar') + self.assertEqual(infos[3]['id'], 'profile-base:base') + self.assertEqual(infos[4]['id'], 'profile-foo:foo') + self.assertEqual(infos[5]['id'], 'profile-UPPER:upper') + + def test_getProfileImportDate_nonesuch(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool.getProfileImportDate('nonesuch'), None) + + def test_getProfileImportDate_simple_id(self): + from OFS.Image import File + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + filename = 'import-all-foo-20070315123456.log' + tool._setObject(filename, File(filename, '', b'')) + self.assertEqual(tool.getProfileImportDate('foo'), + '2007-03-15T12:34:56Z') + + def test_getProfileImportDate_id_with_colon(self): + from OFS.Image import File + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + filename = 'import-all-foo_bar-20070315123456.log' + tool._setObject(filename, File(filename, '', b'')) + self.assertEqual(tool.getProfileImportDate('foo:bar'), + '2007-03-15T12:34:56Z') + + def test_getProfileImportDate_id_with_prefix(self): + # Test if getProfileImportDate does not fail if there is another + # item id with id with a longer id which starts with the same + # prefix + from OFS.Image import File + + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + filename = 'import-all-foo_bar-20070315123456.log' + tool._setObject(filename, File(filename, '', b'')) + filename2 = 'import-all-foo_bar-boo-20070315123456.log' + tool._setObject(filename2, File(filename2, '', b'')) + self.assertEqual(tool.getProfileImportDate('foo:bar'), + '2007-03-15T12:34:56Z') + + def test_profileVersioning(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + profile_id = 'dummy_profile' + product_name = 'GenericSetup' + directory = os.path.split(__file__)[0] + path = os.path.join(directory, 'versioned_profile') + + # register profile + profile_registry.registerProfile(profile_id, + 'Dummy Profile', + 'This is a dummy profile', + path, + product=product_name) + + # register upgrade step + step = UpgradeStep("Upgrade", + "GenericSetup:dummy_profile", '*', '1.1', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step) + + # test initial states + profile_id = ':'.join((product_name, profile_id)) + self.assertEqual(tool.getVersionForProfile(profile_id), '1.1') + self.assertEqual(tool.getLastVersionForProfile(profile_id), + 'unknown') + + # run upgrade steps + request = site.REQUEST + request.form['profile_id'] = profile_id + steps = listUpgradeSteps(tool, profile_id, '1.0') + step_id = steps[0]['id'] + request.form['upgrades'] = [step_id] + tool.manage_doUpgrades() + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '1')) + + def test_get_and_setLastVersionForProfile(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool._profile_upgrade_versions, {}) + # Any 'profile-' is stripped off in these calls. + self.assertEqual(tool.getLastVersionForProfile('foo'), 'unknown') + self.assertEqual(tool.getLastVersionForProfile( + 'profile-foo'), 'unknown') + tool.setLastVersionForProfile('foo', '1.0') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('1', '0')) + self.assertEqual(tool.getLastVersionForProfile( + 'profile-foo'), ('1', '0')) + tool.setLastVersionForProfile('profile-foo', '2.0') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('2', '0')) + self.assertEqual(tool.getLastVersionForProfile( + 'profile-foo'), ('2', '0')) + + # Setting the profile to unknown, removes it from the versions. + self.assertEqual(tool._profile_upgrade_versions, {'foo': ('2', '0')}) + tool.setLastVersionForProfile('profile-foo', 'unknown') + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_unsetLastVersionForProfile(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.setLastVersionForProfile('foo', '1.0') + tool.setLastVersionForProfile('bar', '2.0') + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0'), 'bar': ('2', '0')}) + + # Any 'profile-' is stripped off in these calls. + tool.unsetLastVersionForProfile('profile-foo') + self.assertEqual(tool._profile_upgrade_versions, + {'bar': ('2', '0')}) + tool.unsetLastVersionForProfile('bar') + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_purgeProfileVersions(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.setLastVersionForProfile('foo', '1.0') + tool.setLastVersionForProfile('bar', '2.0') + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0'), 'bar': ('2', '0')}) + tool.purgeProfileVersions() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_listProfilesWithUpgrades(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool.listProfilesWithUpgrades(), []) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + profile_id = 'dummy_profile' + product_name = 'GenericSetup' + directory = os.path.split(__file__)[0] + path = os.path.join(directory, 'versioned_profile') + + # register profile + profile_registry.registerProfile(profile_id, + 'Dummy Profile', + 'This is a dummy profile', + path, + product=product_name) + self.assertEqual(tool.listProfilesWithUpgrades(), []) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # register upgrade step + step1 = UpgradeStep("Upgrade 1", + "GenericSetup:dummy_profile", '*', '1.1', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step1) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # register another upgrade step + step2 = UpgradeStep("Upgrade 2", + "GenericSetup:dummy_profile", '1.1', '1.2', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step2) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # get full profile id + profile_id = ':'.join((product_name, profile_id)) + + # Pretend the profile was installed + tool.setLastVersionForProfile(profile_id, '1.0') + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), True) + + # run first upgrade step + request = site.REQUEST + request.form['profile_id'] = profile_id + steps = listUpgradeSteps(tool, profile_id, '1.0') + step_id = steps[0]['id'] + request.form['upgrades'] = [step_id] + tool.manage_doUpgrades() + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '1')) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), True) + + # run second upgrade step + request = site.REQUEST + request.form['profile_id'] = profile_id + steps = listUpgradeSteps(tool, profile_id, '1.1') + step_id = steps[0]['id'] + request.form['upgrades'] = [step_id] + tool.manage_doUpgrades() + self.assertEqual(tool.getLastVersionForProfile(profile_id), + ('1', '2')) + self.assertEqual(tool.listProfilesWithUpgrades(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), + [u'GenericSetup:dummy_profile']) + self.assertEqual(tool.hasPendingUpgrades(), False) + + # Pretend the profile was never installed. + tool.unsetLastVersionForProfile(profile_id) + self.assertEqual(tool.listProfilesWithPendingUpgrades(), []) + self.assertEqual(tool.listUptodateProfiles(), []) + self.assertEqual(tool.hasPendingUpgrades(), False) + + def test_hasPendingUpgrades(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + profile_id_1 = 'dummy_profile1' + profile_id_2 = 'dummy_profile2' + product_name = 'GenericSetup' + directory = os.path.split(__file__)[0] + path = os.path.join(directory, 'versioned_profile') + + # register profiles + profile_registry.registerProfile(profile_id_1, + 'Dummy Profile 1', + 'This is dummy profile 1', + path, + product=product_name) + profile_registry.registerProfile(profile_id_2, + 'Dummy Profile 2', + 'This is dummy profile 2', + path, + product=product_name) + + # get full profile ids + profile_id_1 = ':'.join((product_name, profile_id_1)) + profile_id_2 = ':'.join((product_name, profile_id_2)) + + # test + self.assertEqual(tool.hasPendingUpgrades(), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + self.assertEqual(tool.hasPendingUpgrades('non-existing'), False) + + # register upgrade steps + step1 = UpgradeStep("Upgrade 1", + profile_id_1, '*', '1.1', '', + dummy_upgrade, + None, "1") + _registerUpgradeStep(step1) + step2 = UpgradeStep("Upgrade 2", + profile_id_2, '*', '2.2', '', + dummy_upgrade, + None, "2") + _registerUpgradeStep(step2) + # No profile has been applied, so no upgrade is pending. + self.assertEqual(tool.hasPendingUpgrades(), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + + # Pretend profile 1 was installed to an earlier version. + tool.setLastVersionForProfile(profile_id_1, '1.0') + self.assertEqual(tool.hasPendingUpgrades(), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + + # Pretend profile 2 was installed to an earlier version. + tool.setLastVersionForProfile(profile_id_2, '2.0') + self.assertEqual(tool.hasPendingUpgrades(), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), True) + + # Pretend profile 1 was installed to the final version. + tool.setLastVersionForProfile(profile_id_1, '1.1') + self.assertEqual(tool.hasPendingUpgrades(), True) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), True) + + # Pretend profile 2 was installed to the final version. + tool.setLastVersionForProfile(profile_id_2, '2.2') + self.assertEqual(tool.hasPendingUpgrades(), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_1), False) + self.assertEqual(tool.hasPendingUpgrades(profile_id_2), False) + + def test_manage_doUpgrades_no_profile_id_or_updates(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + tool.manage_doUpgrades() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_manage_doUpgrades_upgrade_w_no_target_version(self): + def notool(): + return None + step = UpgradeStep('TITLE', 'foo', '*', '*', 'DESC', notool) + _registerUpgradeStep(step) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + request = site.REQUEST + request['profile_id'] = ['foo'] + request['upgrade'] = [step.id] + tool.manage_doUpgrades() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_upgradeProfile_no_profile_id_or_updates(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + # Mostly this checks to see if we can call this without an + # exception. + tool.upgradeProfile('no.such.profile:default') + self.assertEqual(tool._profile_upgrade_versions, {}) + tool.upgradeProfile('no.such.profile:default', dest='42') + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_persistent_profile_upgrade_versions(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + savepoint1 = transaction.savepoint() + tool.setLastVersionForProfile('foo', '1.0') + savepoint2 = transaction.savepoint() + tool.setLastVersionForProfile('bar', '2.0') + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0'), 'bar': ('2', '0')}) + savepoint2.rollback() + self.assertEqual(tool._profile_upgrade_versions, + {'foo': ('1', '0')}) + savepoint1.rollback() + self.assertEqual(tool._profile_upgrade_versions, {}) + + def test_separate_profile_upgrade_versions(self): + # _profile_upgrade_versions used to be a class property. That is fine + # as long as we only work on copies, otherwise state is shared between + # two instances. We now create the property in the __init__ method, + # but let's test it to avoid a regression. + site = self._makeSite() + site.setup_tool1 = self._makeOne('setup_tool1') + tool1 = site.setup_tool1 + site.setup_tool2 = self._makeOne('setup_tool2') + tool2 = site.setup_tool2 + tool1._profile_upgrade_versions['foo'] = '1.0' + self.assertEqual(tool2._profile_upgrade_versions, {}) + tool2.setLastVersionForProfile('bar', '2.0') + self.assertEqual(self._makeOne('t')._profile_upgrade_versions, {}) + + def test_upgradeProfile(self): + def dummy_handler(tool): + return None + + def step3_handler(tool): + tool._step3_applied = 'just a marker' + + def step3_checker(tool): + # False means already applied or does not apply. + # True means can be applied. + return not hasattr(tool, '_step3_applied') + + step1 = UpgradeStep('Step 1', 'foo', '0', '1', 'DESC', + dummy_handler) + step2 = UpgradeStep('Step 2', 'foo', '1', '2', 'DESC', + dummy_handler) + step3 = UpgradeStep('Step 3', 'foo', '2', '3', 'DESC', + step3_handler, checker=step3_checker) + step4 = UpgradeStep('Step 4', 'foo', '3', '4', 'DESC', + dummy_handler) + _registerUpgradeStep(step1) + _registerUpgradeStep(step2) + _registerUpgradeStep(step3) + _registerUpgradeStep(step4) + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + self.assertEqual(tool.getLastVersionForProfile('foo'), 'unknown') + tool.setLastVersionForProfile('foo', '0') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('0',)) + # Upgrade the profile one step to version 1. + tool.upgradeProfile('foo', '1') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('1',)) + # Upgrade the profile two steps to version 3. This one has a + # checker. The profile version must be correctly updated. + tool.upgradeProfile('foo', '3') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('3',)) + # Upgrade the profile to a non existing version. Nothing + # should happen. + tool.upgradeProfile('foo', '5') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('3',)) + # Upgrade the profile to the latest version. + tool.upgradeProfile('foo') + self.assertEqual(tool.getLastVersionForProfile('foo'), ('4',)) + + def test_listExportSteps(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + result = tool.listExportSteps() + self.assertEqual(len(result), 4) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'step_registries' in result) + self.assertTrue(u'toolset' in result) + + tool._export_registry.registerStep(u'foo', handler='foo.export') + tool._export_registry.registerStep(u'toolset', + handler='toolset.export') + result = tool.listExportSteps() + self.assertEqual(len(result), 5) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'foo' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'step_registries' in result) + self.assertTrue(u'toolset' in result) + + def test_getSortedImportSteps(self): + site = self._makeSite() + site.setup_tool = self._makeOne('setup_tool') + tool = site.setup_tool + result = tool.getSortedImportSteps() + self.assertEqual(len(result), 3) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'toolset' in result) + self.assertTrue(list(result).index(u'componentregistry') > + list(result).index(u'toolset')) + + tool._import_registry.registerStep(u'foo', handler='foo.import') + tool._import_registry.registerStep(u'toolset', + handler='toolset.import') + result = tool.getSortedImportSteps() + self.assertEqual(len(result), 4) + self.assertTrue(u'componentregistry' in result) + self.assertTrue(u'foo' in result) + self.assertTrue(u'rolemap' in result) + self.assertTrue(u'toolset' in result) + self.assertTrue(list(result).index(u'componentregistry') > + list(result).index(u'toolset')) + + def test_listProfileInfo_for_parameter(self): + from ..metadata import METADATA_XML + + self._makeFile(METADATA_XML, _METADATA_XML) + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + profile_registry.registerProfile('foo', 'Foo', '', self._PROFILE_PATH, + for_=ISite) + # tool.listProfileInfo should call registry.listProfileInfo + # with the for_ parameter + self.assertEqual(len(tool.listProfileInfo()), 1) + self.assertEqual(len(tool.listProfileInfo(for_=ISite)), 1) + self.assertEqual(len(tool.listProfileInfo(for_=IDerivedSite)), 1) + self.assertEqual(len(tool.listProfileInfo(for_=IAnotherSite)), 0) + + def test_profileExists(self): + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register two extension profiles. Profile 'foo' has a dependency + # 'bar'. + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=EXTENSION) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + + self.assertTrue(tool.profileExists('other:foo')) + self.assertTrue(tool.profileExists('other:bar')) + self.assertFalse(tool.profileExists('snapshot-something')) + self.assertFalse(tool.profileExists(None)) + self.assertFalse(tool.profileExists('nonesuch')) + + def test_getDependenciesForProfile(self): + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register three extension profiles. Profile 'foo' has a dependency + # 'bar', and 'baz' contains non-existing dependency-profiles. + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _BROKEN_METADATA_XML) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=EXTENSION) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + profile_registry.registerProfile( + 'baz', 'Baz', '', self._PROFILE_PATH3, profile_type=EXTENSION) + + self.assertEqual(tool.getDependenciesForProfile('other:foo'), + (u'profile-other:bar', )) + self.assertEqual(tool.getDependenciesForProfile('other:bar'), ()) + self.assertEqual(tool.getDependenciesForProfile('snapshot-some'), ()) + self.assertEqual(tool.getDependenciesForProfile(None), ()) + self.assertRaises(KeyError, tool.getDependenciesForProfile, 'nonesuch') + + def test_getBrokenDependencies(self): + from ..interfaces import EXTENSION + from ..metadata import METADATA_XML + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + + # Register three extension profiles. Profile 'foo' has a dependency + # 'bar' and 'baz' contains non-existing dependency-profiles. + self._makeFile(METADATA_XML, _METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH2, _PLAIN_METADATA_XML) + _makeTestFile(METADATA_XML, self._PROFILE_PATH3, _BROKEN_METADATA_XML) + profile_registry.registerProfile( + 'foo', 'Foo', '', self._PROFILE_PATH, profile_type=EXTENSION) + profile_registry.registerProfile( + 'bar', 'Bar', '', self._PROFILE_PATH2, profile_type=EXTENSION) + profile_registry.registerProfile( + 'baz', 'Baz', '', self._PROFILE_PATH3, profile_type=EXTENSION) + + # profile has dependencies and none of them is broken: + self.assertFalse(tool.hasBrokenDependencies('other:foo')) + # profile has no dependencies, therfore nothing can be broken: + self.assertFalse(tool.hasBrokenDependencies('other:bar')) + # profile has dependencies and at least one of them is broken: + self.assertTrue(tool.hasBrokenDependencies('other:baz')) +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `function:SetupToolTests.test_runAllImportStepsFromProfile_unicode_id_creates_reports` (lines 476-504) + +```python + def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): + + TITLE = 'original title' + PROFILE_ID = u'snapshot-testing' + site = self._makeSite(TITLE) + tool = self._makeOne('setup_tool').__of__(site) + + registry = tool.getImportStepRegistry() + registry.registerStep( + 'dependable', '1', _underscoreSiteTitle, ('purging', )) + registry.registerStep( + 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) + registry.registerStep('purging', '1', _purgeIfRequired) + + tool.runAllImportStepsFromProfile(PROFILE_ID) + + prefix = str('import-all-%s' % PROFILE_ID) + logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] + self.assertEqual(len(logged), 1) + + # Check acess restriction on log files + logged = [x for x in tool.objectIds('File')] + for file_id in logged: + file_ob = tool._getOb(file_id) + rop_info = file_ob.rolesOfPermission(view) + allowed_roles = sorted([x['name'] for x in rop_info + if x['selected']]) + self.assertEqual(allowed_roles, ['Manager', 'Owner']) + self.assertFalse(file_ob.acquiredRolesAreUsedBy(view)) +``` + +## `src/Products/GenericSetup/tests/test_tool.py` — `function:SetupToolTests.test_applyContext` (lines 1104-1146) + +```python + def test_applyContext(self): + from ..tool import EXPORT_STEPS_XML + from ..tool import IMPORT_STEPS_XML + from ..tool import TOOLSET_XML + + site = self._makeSite() + tool = self._makeOne('setup_tool').__of__(site) + tool.getImportStepRegistry().clear() + tool.getExportStepRegistry().clear() + tool.getToolsetRegistry().clear() + + context = DummyImportContext(site, tool=tool) + context._files[IMPORT_STEPS_XML] = _SINGLE_IMPORT_XML + context._files[EXPORT_STEPS_XML] = _SINGLE_EXPORT_XML + context._files[TOOLSET_XML] = _NORMAL_TOOLSET_XML + + tool.applyContext(context) + + import_registry = tool.getImportStepRegistry() + self.assertEqual(len(import_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = import_registry.getStepMetadata('one') + + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertEqual(info['version'], '1') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(import_registry.getStep('one'), ONE_FUNC) + + export_registry = tool.getExportStepRegistry() + self.assertEqual(len(export_registry.listSteps()), 1) + self.assertTrue('one' in import_registry.listSteps()) + info = export_registry.getStepMetadata('one') + self.assertEqual(info['id'], 'one') + self.assertEqual(info['title'], 'One Step') + self.assertTrue('One small step' in info['description']) + self.assertEqual(info['handler'], + 'Products.GenericSetup.tests.test_registry.ONE_FUNC') + + self.assertEqual(export_registry.getStep('one'), ONE_FUNC) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c327d32540b77ebf249d92d96cd80f95bdadddfa --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/task.json @@ -0,0 +1,57 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-bae2a9b05bba64edb040", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-bae2a9b05bba64edb040", + "project_id": "pyvul__zopefoundation__products.genericsetup", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "src/Products/GenericSetup/context.py", + "src/Products/GenericSetup/tests/test_tool.py" + ], + "patch_units": { + "before": [ + "class:SnapshotExportContext", + "function:SnapshotExportContext._ensureSnapshotsFolder", + "module:@29", + "class:SetupToolTests", + "function:SetupToolTests.test_runAllImportStepsFromProfile_unicode_id_creates_reports", + "function:SetupToolTests.test_applyContext" + ], + "after": [ + "class:SnapshotExportContext", + "function:SnapshotExportContext.writeDataFile", + "function:SnapshotExportContext._ensureSnapshotsFolder", + "module:@29", + "class:SetupToolTests", + "function:SetupToolTests.check_restricted_access", + "function:SetupToolTests.test_runAllImportStepsFromProfile_unicode_id_creates_reports", + "function:SetupToolTests.test_createSnapshot_default" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/4625469d61f52d0592178cacd44a53f32de79f4887c3f6794a8e28a419d4577c/database", + "cache_key": "4625469d61f52d0592178cacd44a53f32de79f4887c3f6794a8e28a419d4577c", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/38782b9865f316638d1d171445928873ae17725922448bc77820a3ff9a51fbd6/database", + "cache_key": "38782b9865f316638d1d171445928873ae17725922448bc77820a3ff9a51fbd6", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/059c643d6dd139fc5b88c6e464b29dec7137c7ccc26cbb76b0a2c474a68a5fa3/database", + "cache_key": "059c643d6dd139fc5b88c6e464b29dec7137c7ccc26cbb76b0a2c474a68a5fa3", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-bae2a9b05bba64edb040/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-bae2a9b05bba64edb040/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bae2a9b05bba64edb040/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6d0eb2dc210dba3747f969563e44d4f8d6af8f01 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/patch.diff @@ -0,0 +1,131 @@ +diff --git a/paramiko/pkey.py b/paramiko/pkey.py +index 7865a6ea..67945261 100644 +--- a/paramiko/pkey.py ++++ b/paramiko/pkey.py +@@ -558,7 +558,17 @@ class PKey(object): + + :raises: ``IOError`` -- if there was an error writing the file. + """ +- with open(filename, "w") as f: ++ # Ensure that we create new key files directly with a user-only mode, ++ # instead of opening, writing, then chmodding, which leaves us open to ++ # CVE-2022-24302. ++ # NOTE: O_TRUNC is a noop on new files, and O_CREAT is a noop on ++ # existing files, so using all 3 in both cases is fine. Ditto the use ++ # of the 'mode' argument; it should be safe to give even for existing ++ # files (though it will not act like a chmod in that case). ++ kwargs = dict(flags=os.O_WRONLY | os.O_TRUNC | os.O_CREAT, mode=o600) ++ # NOTE: yea, you still gotta inform the FLO that it is in "write" mode ++ with os.fdopen(os.open(filename, **kwargs), mode="w") as f: ++ # TODO 3.0: remove the now redundant chmod + os.chmod(filename, o600) + self._write_private_key(f, key, format, password=password) + +diff --git a/sites/www/changelog.rst b/sites/www/changelog.rst +index af648ddc..37d149f2 100644 +--- a/sites/www/changelog.rst ++++ b/sites/www/changelog.rst +@@ -2,6 +2,20 @@ + Changelog + ========= + ++- :bug:`-` (`CVE-2022-24302 ++ `_) Creation ++ of new private key files using `~paramiko.pkey.PKey` subclasses was subject ++ to a race condition between file creation & mode modification, which could be ++ exploited by an attacker with knowledge of where the Paramiko-using code ++ would write out such files. ++ ++ This has been patched by using `os.open` and `os.fdopen` to ensure new files ++ are opened with the correct mode immediately. We've left the subsequent ++ explicit ``chmod`` in place to minimize any possible disruption, though it ++ may get removed in future backwards-incompatible updates. ++ ++ Thanks to Jan Schejbal for the report & feedback on the solution, and to ++ Jeremy Katz at Tidelift for coordinating the disclosure. + - :release:`2.10.0 <2022-03-11>` + - :feature:`1976` Add support for the ``%C`` token when parsing SSH config + files. Foundational PR submitted by ``@jbrand42``. +diff --git a/tests/test_pkey.py b/tests/test_pkey.py +index 0cc20133..d44a96ac 100644 +--- a/tests/test_pkey.py ++++ b/tests/test_pkey.py +@@ -23,6 +23,7 @@ Some unit tests for public/private key objects. + + import unittest + import os ++import stat + from binascii import hexlify + from hashlib import md5 + +@@ -36,10 +37,11 @@ from paramiko import ( + SSHException, + ) + from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2 ++from paramiko.common import o600 + + from cryptography.exceptions import UnsupportedAlgorithm + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers +-from mock import patch ++from mock import patch, Mock + import pytest + + from .util import _support, is_low_entropy +@@ -696,3 +698,57 @@ class KeyTest(unittest.TestCase): + key1.load_certificate, + _support("test_rsa.key-cert.pub"), + ) ++ ++ @patch("paramiko.pkey.os") ++ def _test_keyfile_race(self, os_, exists): ++ # Re: CVE-2022-24302 ++ password = "television" ++ newpassword = "radio" ++ source = _support("test_ecdsa_384.key") ++ new = source + ".new" ++ # Mock setup ++ os_.path.exists.return_value = exists ++ # Attach os flag values to mock ++ for attr, value in vars(os).items(): ++ if attr.startswith("O_"): ++ setattr(os_, attr, value) ++ # Load fixture key ++ key = ECDSAKey(filename=source, password=password) ++ key._write_private_key = Mock() ++ # Write out in new location ++ key.write_private_key_file(new, password=newpassword) ++ # Expected open via os module ++ os_.open.assert_called_once_with(new, flags=os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=o600) ++ os_.fdopen.assert_called_once_with(os_.open.return_value, mode="w") ++ # Old chmod still around for backwards compat ++ os_.chmod.assert_called_once_with(new, o600) ++ assert ( ++ key._write_private_key.call_args[0][0] ++ == os_.fdopen.return_value.__enter__.return_value ++ ) ++ ++ def test_new_keyfiles_avoid_file_descriptor_race_on_chmod(self): ++ self._test_keyfile_race(exists=False) ++ ++ def test_existing_keyfiles_still_work_ok(self): ++ self._test_keyfile_race(exists=True) ++ ++ def test_new_keyfiles_avoid_descriptor_race_integration(self): ++ # Integration-style version of above ++ password = "television" ++ newpassword = "radio" ++ source = _support("test_ecdsa_384.key") ++ new = source + ".new" ++ # Load fixture key ++ key = ECDSAKey(filename=source, password=password) ++ try: ++ # Write out in new location ++ key.write_private_key_file(new, password=newpassword) ++ # Test mode ++ assert stat.S_IMODE(os.stat(new).st_mode) == o600 ++ # Prove can open with new password ++ reloaded = ECDSAKey(filename=new, password=newpassword) ++ assert reloaded == key ++ finally: ++ if os.path.exists(new): ++ os.unlink(new) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..ae7b4621b7fbae9c4166f54939f0bd38ba2ec36a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/post_context.md @@ -0,0 +1,1348 @@ +# Patch-overlapping Python context after the fix + +## `paramiko/pkey.py` — `class:PKey` (lines 62-663) + +```python +class PKey(object): + """ + Base class for public keys. + """ + + # known encryption types for private key files: + _CIPHER_TABLE = { + "AES-128-CBC": { + "cipher": algorithms.AES, + "keysize": 16, + "blocksize": 16, + "mode": modes.CBC, + }, + "AES-256-CBC": { + "cipher": algorithms.AES, + "keysize": 32, + "blocksize": 16, + "mode": modes.CBC, + }, + "DES-EDE3-CBC": { + "cipher": algorithms.TripleDES, + "keysize": 24, + "blocksize": 8, + "mode": modes.CBC, + }, + } + _PRIVATE_KEY_FORMAT_ORIGINAL = 1 + _PRIVATE_KEY_FORMAT_OPENSSH = 2 + BEGIN_TAG = re.compile( + r"^-{5}BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$" + ) + END_TAG = re.compile(r"^-{5}END (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$") + + def __init__(self, msg=None, data=None): + """ + Create a new instance of this public key type. If ``msg`` is given, + the key's public part(s) will be filled in from the message. If + ``data`` is given, the key's public part(s) will be filled in from + the string. + + :param .Message msg: + an optional SSH `.Message` containing a public key of this type. + :param str data: an optional string containing a public key + of this type + + :raises: `.SSHException` -- + if a key cannot be created from the ``data`` or ``msg`` given, or + no key was passed in. + """ + pass + + def asbytes(self): + """ + Return a string of an SSH `.Message` made up of the public part(s) of + this key. This string is suitable for passing to `__init__` to + re-create the key object later. + """ + return bytes() + + def __str__(self): + return self.asbytes() + + # noinspection PyUnresolvedReferences + # TODO: The comparison functions should be removed as per: + # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons + def __cmp__(self, other): + """ + Compare this key to another. Returns 0 if this key is equivalent to + the given key, or non-0 if they are different. Only the public parts + of the key are compared, so a public key will compare equal to its + corresponding private key. + + :param .PKey other: key to compare to. + """ + hs = hash(self) + ho = hash(other) + if hs != ho: + return cmp(hs, ho) # noqa + return cmp(self.asbytes(), other.asbytes()) # noqa + + def __eq__(self, other): + return self._fields == other._fields + + def __hash__(self): + return hash(self._fields) + + @property + def _fields(self): + raise NotImplementedError + + def get_name(self): + """ + Return the name of this private key implementation. + + :return: + name of this private key type, in SSH terminology, as a `str` (for + example, ``"ssh-rsa"``). + """ + return "" + + def get_bits(self): + """ + Return the number of significant bits in this key. This is useful + for judging the relative security of a key. + + :return: bits in the key (as an `int`) + """ + return 0 + + def can_sign(self): + """ + Return ``True`` if this key has the private part necessary for signing + data. + """ + return False + + def get_fingerprint(self): + """ + Return an MD5 fingerprint of the public part of this key. Nothing + secret is revealed. + + :return: + a 16-byte `string ` (binary) of the MD5 fingerprint, in SSH + format. + """ + return md5(self.asbytes()).digest() + + def get_base64(self): + """ + Return a base64 string containing the public part of this key. Nothing + secret is revealed. This format is compatible with that used to store + public key files or recognized host keys. + + :return: a base64 `string ` containing the public part of the key. + """ + return u(encodebytes(self.asbytes())).replace("\n", "") + + def sign_ssh_data(self, data, algorithm=None): + """ + Sign a blob of data with this private key, and return a `.Message` + representing an SSH signature message. + + :param str data: + the data to sign. + :param str algorithm: + the signature algorithm to use, if different from the key's + internal name. Default: ``None``. + :return: an SSH signature `message <.Message>`. + + .. versionchanged:: 2.9 + Added the ``algorithm`` kwarg. + """ + return bytes() + + def verify_ssh_sig(self, data, msg): + """ + Given a blob of data, and an SSH message representing a signature of + that data, verify that it was signed with this key. + + :param str data: the data that was signed. + :param .Message msg: an SSH signature message + :return: + ``True`` if the signature verifies correctly; ``False`` otherwise. + """ + return False + + @classmethod + def from_private_key_file(cls, filename, password=None): + """ + Create a key object by reading a private key file. If the private + key is encrypted and ``password`` is not ``None``, the given password + will be used to decrypt the key (otherwise `.PasswordRequiredException` + is thrown). Through the magic of Python, this factory method will + exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but + is useless on the abstract PKey class. + + :param str filename: name of the file to read + :param str password: + an optional password to use to decrypt the key file, if it's + encrypted + :return: a new `.PKey` based on the given private key + + :raises: ``IOError`` -- if there was an error reading the file + :raises: `.PasswordRequiredException` -- if the private key file is + encrypted, and ``password`` is ``None`` + :raises: `.SSHException` -- if the key file is invalid + """ + key = cls(filename=filename, password=password) + return key + + @classmethod + def from_private_key(cls, file_obj, password=None): + """ + Create a key object by reading a private key from a file (or file-like) + object. If the private key is encrypted and ``password`` is not + ``None``, the given password will be used to decrypt the key (otherwise + `.PasswordRequiredException` is thrown). + + :param file_obj: the file-like object to read from + :param str password: + an optional password to use to decrypt the key, if it's encrypted + :return: a new `.PKey` based on the given private key + + :raises: ``IOError`` -- if there was an error reading the key + :raises: `.PasswordRequiredException` -- + if the private key file is encrypted, and ``password`` is ``None`` + :raises: `.SSHException` -- if the key file is invalid + """ + key = cls(file_obj=file_obj, password=password) + return key + + def write_private_key_file(self, filename, password=None): + """ + Write private key contents into a file. If the password is not + ``None``, the key is encrypted before writing. + + :param str filename: name of the file to write + :param str password: + an optional password to use to encrypt the key file + + :raises: ``IOError`` -- if there was an error writing the file + :raises: `.SSHException` -- if the key is invalid + """ + raise Exception("Not implemented in PKey") + + def write_private_key(self, file_obj, password=None): + """ + Write private key contents into a file (or file-like) object. If the + password is not ``None``, the key is encrypted before writing. + + :param file_obj: the file-like object to write into + :param str password: an optional password to use to encrypt the key + + :raises: ``IOError`` -- if there was an error writing to the file + :raises: `.SSHException` -- if the key is invalid + """ + raise Exception("Not implemented in PKey") + + def _read_private_key_file(self, tag, filename, password=None): + """ + Read an SSH2-format private key file, looking for a string of the type + ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we + find, and return it as a string. If the private key is encrypted and + ``password`` is not ``None``, the given password will be used to + decrypt the key (otherwise `.PasswordRequiredException` is thrown). + + :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the + data block. + :param str filename: name of the file to read. + :param str password: + an optional password to use to decrypt the key file, if it's + encrypted. + :return: data blob (`str`) that makes up the private key. + + :raises: ``IOError`` -- if there was an error reading the file. + :raises: `.PasswordRequiredException` -- if the private key file is + encrypted, and ``password`` is ``None``. + :raises: `.SSHException` -- if the key file is invalid. + """ + with open(filename, "r") as f: + data = self._read_private_key(tag, f, password) + return data + + def _read_private_key(self, tag, f, password=None): + lines = f.readlines() + + # find the BEGIN tag + start = 0 + m = self.BEGIN_TAG.match(lines[start]) + line_range = len(lines) - 1 + while start < line_range and not m: + start += 1 + m = self.BEGIN_TAG.match(lines[start]) + start += 1 + keytype = m.group(1) if m else None + if start >= len(lines) or keytype is None: + raise SSHException("not a valid {} private key file".format(tag)) + + # find the END tag + end = start + m = self.END_TAG.match(lines[end]) + while end < line_range and not m: + end += 1 + m = self.END_TAG.match(lines[end]) + + if keytype == tag: + data = self._read_private_key_pem(lines, end, password) + pkformat = self._PRIVATE_KEY_FORMAT_ORIGINAL + elif keytype == "OPENSSH": + data = self._read_private_key_openssh(lines[start:end], password) + pkformat = self._PRIVATE_KEY_FORMAT_OPENSSH + else: + raise SSHException( + "encountered {} key, expected {} key".format(keytype, tag) + ) + + return pkformat, data + + def _got_bad_key_format_id(self, id_): + err = "{}._read_private_key() spat out an unknown key format id '{}'" + raise SSHException(err.format(self.__class__.__name__, id_)) + + def _read_private_key_pem(self, lines, end, password): + start = 0 + # parse any headers first + headers = {} + start += 1 + while start < len(lines): + line = lines[start].split(": ") + if len(line) == 1: + break + headers[line[0].lower()] = line[1].strip() + start += 1 + # if we trudged to the end of the file, just try to cope. + try: + data = decodebytes(b("".join(lines[start:end]))) + except base64.binascii.Error as e: + raise SSHException("base64 decoding error: {}".format(e)) + if "proc-type" not in headers: + # unencryped: done + return data + # encrypted keyfile: will need a password + proc_type = headers["proc-type"] + if proc_type != "4,ENCRYPTED": + raise SSHException( + 'Unknown private key structure "{}"'.format(proc_type) + ) + try: + encryption_type, saltstr = headers["dek-info"].split(",") + except: + raise SSHException("Can't parse DEK-info in private key file") + if encryption_type not in self._CIPHER_TABLE: + raise SSHException( + 'Unknown private key cipher "{}"'.format(encryption_type) + ) + # if no password was passed in, + # raise an exception pointing out that we need one + if password is None: + raise PasswordRequiredException("Private key file is encrypted") + cipher = self._CIPHER_TABLE[encryption_type]["cipher"] + keysize = self._CIPHER_TABLE[encryption_type]["keysize"] + mode = self._CIPHER_TABLE[encryption_type]["mode"] + salt = unhexlify(b(saltstr)) + key = util.generate_key_bytes(md5, salt, password, keysize) + decryptor = Cipher( + cipher(key), mode(salt), backend=default_backend() + ).decryptor() + return decryptor.update(data) + decryptor.finalize() + + def _read_private_key_openssh(self, lines, password): + """ + Read the new OpenSSH SSH2 private key format available + since OpenSSH version 6.5 + Reference: + https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key + """ + try: + data = decodebytes(b("".join(lines))) + except base64.binascii.Error as e: + raise SSHException("base64 decoding error: {}".format(e)) + + # read data struct + auth_magic = data[:15] + if auth_magic != OPENSSH_AUTH_MAGIC: + raise SSHException("unexpected OpenSSH key header encountered") + + cstruct = self._uint32_cstruct_unpack(data[15:], "sssur") + cipher, kdfname, kdf_options, num_pubkeys, remainder = cstruct + # For now, just support 1 key. + if num_pubkeys > 1: + raise SSHException( + "unsupported: private keyfile has multiple keys" + ) + pubkey, privkey_blob = self._uint32_cstruct_unpack(remainder, "ss") + + if kdfname == b("bcrypt"): + if cipher == b("aes256-cbc"): + mode = modes.CBC + elif cipher == b("aes256-ctr"): + mode = modes.CTR + else: + raise SSHException( + "unknown cipher `{}` used in private key file".format( + cipher.decode("utf-8") + ) + ) + # Encrypted private key. + # If no password was passed in, raise an exception pointing + # out that we need one + if password is None: + raise PasswordRequiredException( + "private key file is encrypted" + ) + + # Unpack salt and rounds from kdfoptions + salt, rounds = self._uint32_cstruct_unpack(kdf_options, "su") + + # run bcrypt kdf to derive key and iv/nonce (32 + 16 bytes) + key_iv = bcrypt.kdf( + b(password), + b(salt), + 48, + rounds, + # We can't control how many rounds are on disk, so no sense + # warning about it. + ignore_few_rounds=True, + ) + key = key_iv[:32] + iv = key_iv[32:] + + # decrypt private key blob + decryptor = Cipher( + algorithms.AES(key), mode(iv), default_backend() + ).decryptor() + decrypted_privkey = decryptor.update(privkey_blob) + decrypted_privkey += decryptor.finalize() + elif cipher == b("none") and kdfname == b("none"): + # Unencrypted private key + decrypted_privkey = privkey_blob + else: + raise SSHException( + "unknown cipher or kdf used in private key file" + ) + + # Unpack private key and verify checkints + cstruct = self._uint32_cstruct_unpack(decrypted_privkey, "uusr") + checkint1, checkint2, keytype, keydata = cstruct + + if checkint1 != checkint2: + raise SSHException( + "OpenSSH private key file checkints do not match" + ) + + return _unpad_openssh(keydata) + + def _uint32_cstruct_unpack(self, data, strformat): + """ + Used to read new OpenSSH private key format. + Unpacks a c data structure containing a mix of 32-bit uints and + variable length strings prefixed by 32-bit uint size field, + according to the specified format. Returns the unpacked vars + in a tuple. + Format strings: + s - denotes a string + i - denotes a long integer, encoded as a byte string + u - denotes a 32-bit unsigned integer + r - the remainder of the input string, returned as a string + """ + arr = [] + idx = 0 + try: + for f in strformat: + if f == "s": + # string + s_size = struct.unpack(">L", data[idx : idx + 4])[0] + idx += 4 + s = data[idx : idx + s_size] + idx += s_size + arr.append(s) + if f == "i": + # long integer + s_size = struct.unpack(">L", data[idx : idx + 4])[0] + idx += 4 + s = data[idx : idx + s_size] + idx += s_size + i = util.inflate_long(s, True) + arr.append(i) + elif f == "u": + # 32-bit unsigned int + u = struct.unpack(">L", data[idx : idx + 4])[0] + idx += 4 + arr.append(u) + elif f == "r": + # remainder as string + s = data[idx:] + arr.append(s) + break + except Exception as e: + # PKey-consuming code frequently wants to save-and-skip-over issues + # with loading keys, and uses SSHException as the (really friggin + # awful) signal for this. So for now...we do this. + raise SSHException(str(e)) + return tuple(arr) + + def _write_private_key_file(self, filename, key, format, password=None): + """ + Write an SSH2-format private key file in a form that can be read by + paramiko or openssh. If no password is given, the key is written in + a trivially-encoded format (base64) which is completely insecure. If + a password is given, DES-EDE3-CBC is used. + + :param str tag: + ``"RSA"`` or ``"DSA"``, the tag used to mark the data block. + :param filename: name of the file to write. + :param str data: data blob that makes up the private key. + :param str password: an optional password to use to encrypt the file. + + :raises: ``IOError`` -- if there was an error writing the file. + """ + # Ensure that we create new key files directly with a user-only mode, + # instead of opening, writing, then chmodding, which leaves us open to + # CVE-2022-24302. + # NOTE: O_TRUNC is a noop on new files, and O_CREAT is a noop on + # existing files, so using all 3 in both cases is fine. Ditto the use + # of the 'mode' argument; it should be safe to give even for existing + # files (though it will not act like a chmod in that case). + kwargs = dict(flags=os.O_WRONLY | os.O_TRUNC | os.O_CREAT, mode=o600) + # NOTE: yea, you still gotta inform the FLO that it is in "write" mode + with os.fdopen(os.open(filename, **kwargs), mode="w") as f: + # TODO 3.0: remove the now redundant chmod + os.chmod(filename, o600) + self._write_private_key(f, key, format, password=password) + + def _write_private_key(self, f, key, format, password=None): + if password is None: + encryption = serialization.NoEncryption() + else: + encryption = serialization.BestAvailableEncryption(b(password)) + + f.write( + key.private_bytes( + serialization.Encoding.PEM, format, encryption + ).decode() + ) + + def _check_type_and_load_cert(self, msg, key_type, cert_type): + """ + Perform message type-checking & optional certificate loading. + + This includes fast-forwarding cert ``msg`` objects past the nonce, so + that the subsequent fields are the key numbers; thus the caller may + expect to treat the message as key material afterwards either way. + + The obtained key type is returned for classes which need to know what + it was (e.g. ECDSA.) + """ + # Normalization; most classes have a single key type and give a string, + # but eg ECDSA is a 1:N mapping. + key_types = key_type + cert_types = cert_type + if isinstance(key_type, string_types): + key_types = [key_types] + if isinstance(cert_types, string_types): + cert_types = [cert_types] + # Can't do much with no message, that should've been handled elsewhere + if msg is None: + raise SSHException("Key object may not be empty") + # First field is always key type, in either kind of object. (make sure + # we rewind before grabbing it - sometimes caller had to do their own + # introspection first!) + msg.rewind() + type_ = msg.get_text() + # Regular public key - nothing special to do besides the implicit + # type check. + if type_ in key_types: + pass + # OpenSSH-compatible certificate - store full copy as .public_blob + # (so signing works correctly) and then fast-forward past the + # nonce. + elif type_ in cert_types: + # This seems the cleanest way to 'clone' an already-being-read + # message; they're *IO objects at heart and their .getvalue() + # always returns the full value regardless of pointer position. + self.load_certificate(Message(msg.asbytes())) + # Read out nonce as it comes before the public numbers. + # TODO: usefully interpret it & other non-public-number fields + # (requires going back into per-type subclasses.) + msg.get_string() + else: + err = "Invalid key (class: {}, data type: {}" + raise SSHException(err.format(self.__class__.__name__, type_)) + + def load_certificate(self, value): + """ + Supplement the private key contents with data loaded from an OpenSSH + public key (``.pub``) or certificate (``-cert.pub``) file, a string + containing such a file, or a `.Message` object. + + The .pub contents adds no real value, since the private key + file includes sufficient information to derive the public + key info. For certificates, however, this can be used on + the client side to offer authentication requests to the server + based on certificate instead of raw public key. + + See: + https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys + + Note: very little effort is made to validate the certificate contents, + that is for the server to decide if it is good enough to authenticate + successfully. + """ + if isinstance(value, Message): + constructor = "from_message" + elif os.path.isfile(value): + constructor = "from_file" + else: + constructor = "from_string" + blob = getattr(PublicBlob, constructor)(value) + if not blob.key_type.startswith(self.get_name()): + err = "PublicBlob type {} incompatible with key type {}" + raise ValueError(err.format(blob.key_type, self.get_name())) + self.public_blob = blob +``` + +## `paramiko/pkey.py` — `function:PKey._write_private_key_file` (lines 546-573) + +```python + def _write_private_key_file(self, filename, key, format, password=None): + """ + Write an SSH2-format private key file in a form that can be read by + paramiko or openssh. If no password is given, the key is written in + a trivially-encoded format (base64) which is completely insecure. If + a password is given, DES-EDE3-CBC is used. + + :param str tag: + ``"RSA"`` or ``"DSA"``, the tag used to mark the data block. + :param filename: name of the file to write. + :param str data: data blob that makes up the private key. + :param str password: an optional password to use to encrypt the file. + + :raises: ``IOError`` -- if there was an error writing the file. + """ + # Ensure that we create new key files directly with a user-only mode, + # instead of opening, writing, then chmodding, which leaves us open to + # CVE-2022-24302. + # NOTE: O_TRUNC is a noop on new files, and O_CREAT is a noop on + # existing files, so using all 3 in both cases is fine. Ditto the use + # of the 'mode' argument; it should be safe to give even for existing + # files (though it will not act like a chmod in that case). + kwargs = dict(flags=os.O_WRONLY | os.O_TRUNC | os.O_CREAT, mode=o600) + # NOTE: yea, you still gotta inform the FLO that it is in "write" mode + with os.fdopen(os.open(filename, **kwargs), mode="w") as f: + # TODO 3.0: remove the now redundant chmod + os.chmod(filename, o600) + self._write_private_key(f, key, format, password=password) +``` + +## `tests/test_pkey.py` — `class:KeyTest` (lines 140-754) + +```python +class KeyTest(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def assert_keyfile_is_encrypted(self, keyfile): + """ + A quick check that filename looks like an encrypted key. + """ + with open(keyfile, "r") as fh: + self.assertEqual( + fh.readline()[:-1], "-----BEGIN RSA PRIVATE KEY-----" + ) + self.assertEqual(fh.readline()[:-1], "Proc-Type: 4,ENCRYPTED") + self.assertEqual(fh.readline()[0:10], "DEK-Info: ") + + def test_generate_key_bytes(self): + key = util.generate_key_bytes(md5, x1234, "happy birthday", 30) + exp = b"\x61\xE1\xF2\x72\xF4\xC1\xC4\x56\x15\x86\xBD\x32\x24\x98\xC0\xE9\x24\x67\x27\x80\xF4\x7B\xB3\x7D\xDA\x7D\x54\x01\x9E\x64" # noqa + self.assertEqual(exp, key) + + def test_load_rsa(self): + key = RSAKey.from_private_key_file(_support("test_rsa.key")) + self.assertEqual("ssh-rsa", key.get_name()) + exp_rsa = b(FINGER_RSA.split()[1].replace(":", "")) + my_rsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_rsa, my_rsa) + self.assertEqual(PUB_RSA.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) + + s = StringIO() + key.write_private_key(s) + self.assertEqual(RSA_PRIVATE_OUT, s.getvalue()) + s.seek(0) + key2 = RSAKey.from_private_key(s) + self.assertEqual(key, key2) + + def test_load_rsa_transmutes_crypto_exceptions(self): + # TODO: nix unittest for pytest + for exception in (TypeError("onoz"), UnsupportedAlgorithm("oops")): + with patch( + "paramiko.rsakey.serialization.load_der_private_key" + ) as loader: + loader.side_effect = exception + with pytest.raises(SSHException, match=str(exception)): + RSAKey.from_private_key_file(_support("test_rsa.key")) + + def test_load_rsa_password(self): + key = RSAKey.from_private_key_file( + _support("test_rsa_password.key"), "television" + ) + self.assertEqual("ssh-rsa", key.get_name()) + exp_rsa = b(FINGER_RSA.split()[1].replace(":", "")) + my_rsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_rsa, my_rsa) + self.assertEqual(PUB_RSA.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) + + def test_load_dss(self): + key = DSSKey.from_private_key_file(_support("test_dss.key")) + self.assertEqual("ssh-dss", key.get_name()) + exp_dss = b(FINGER_DSS.split()[1].replace(":", "")) + my_dss = hexlify(key.get_fingerprint()) + self.assertEqual(exp_dss, my_dss) + self.assertEqual(PUB_DSS.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) + + s = StringIO() + key.write_private_key(s) + self.assertEqual(DSS_PRIVATE_OUT, s.getvalue()) + s.seek(0) + key2 = DSSKey.from_private_key(s) + self.assertEqual(key, key2) + + def test_load_dss_password(self): + key = DSSKey.from_private_key_file( + _support("test_dss_password.key"), "television" + ) + self.assertEqual("ssh-dss", key.get_name()) + exp_dss = b(FINGER_DSS.split()[1].replace(":", "")) + my_dss = hexlify(key.get_fingerprint()) + self.assertEqual(exp_dss, my_dss) + self.assertEqual(PUB_DSS.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) + + def test_compare_rsa(self): + # verify that the private & public keys compare equal + key = RSAKey.from_private_key_file(_support("test_rsa.key")) + self.assertEqual(key, key) + pub = RSAKey(data=key.asbytes()) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) + + def test_compare_dss(self): + # verify that the private & public keys compare equal + key = DSSKey.from_private_key_file(_support("test_dss.key")) + self.assertEqual(key, key) + pub = DSSKey(data=key.asbytes()) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) + + def _sign_and_verify_rsa(self, algorithm, saved_sig): + key = RSAKey.from_private_key_file(_support("test_rsa.key")) + msg = key.sign_ssh_data(b"ice weasels", algorithm) + assert isinstance(msg, Message) + msg.rewind() + assert msg.get_text() == algorithm + expected = bytes().join( + [byte_chr(int(x, 16)) for x in saved_sig.split(":")] + ) + assert msg.get_binary() == expected + msg.rewind() + pub = RSAKey(data=key.asbytes()) + self.assertTrue(pub.verify_ssh_sig(b"ice weasels", msg)) + + def test_sign_and_verify_ssh_rsa(self): + self._sign_and_verify_rsa("ssh-rsa", SIGNED_RSA) + + def test_sign_and_verify_rsa_sha2_512(self): + self._sign_and_verify_rsa("rsa-sha2-512", SIGNED_RSA_512) + + def test_sign_and_verify_rsa_sha2_256(self): + self._sign_and_verify_rsa("rsa-sha2-256", SIGNED_RSA_256) + + def test_sign_dss(self): + # verify that the dss private key can sign and verify + key = DSSKey.from_private_key_file(_support("test_dss.key")) + msg = key.sign_ssh_data(b"ice weasels") + self.assertTrue(type(msg) is Message) + msg.rewind() + self.assertEqual("ssh-dss", msg.get_text()) + # can't do the same test as we do for RSA, because DSS signatures + # are usually different each time. but we can test verification + # anyway so it's ok. + self.assertEqual(40, len(msg.get_binary())) + msg.rewind() + pub = DSSKey(data=key.asbytes()) + self.assertTrue(pub.verify_ssh_sig(b"ice weasels", msg)) + + def test_generate_rsa(self): + key = RSAKey.generate(1024) + msg = key.sign_ssh_data(b"jerri blank") + msg.rewind() + self.assertTrue(key.verify_ssh_sig(b"jerri blank", msg)) + + def test_generate_dss(self): + key = DSSKey.generate(1024) + msg = key.sign_ssh_data(b"jerri blank") + msg.rewind() + self.assertTrue(key.verify_ssh_sig(b"jerri blank", msg)) + + def test_generate_ecdsa(self): + key = ECDSAKey.generate() + msg = key.sign_ssh_data(b"jerri blank") + msg.rewind() + self.assertTrue(key.verify_ssh_sig(b"jerri blank", msg)) + self.assertEqual(key.get_bits(), 256) + self.assertEqual(key.get_name(), "ecdsa-sha2-nistp256") + + key = ECDSAKey.generate(bits=256) + msg = key.sign_ssh_data(b"jerri blank") + msg.rewind() + self.assertTrue(key.verify_ssh_sig(b"jerri blank", msg)) + self.assertEqual(key.get_bits(), 256) + self.assertEqual(key.get_name(), "ecdsa-sha2-nistp256") + + key = ECDSAKey.generate(bits=384) + msg = key.sign_ssh_data(b"jerri blank") + msg.rewind() + self.assertTrue(key.verify_ssh_sig(b"jerri blank", msg)) + self.assertEqual(key.get_bits(), 384) + self.assertEqual(key.get_name(), "ecdsa-sha2-nistp384") + + key = ECDSAKey.generate(bits=521) + msg = key.sign_ssh_data(b"jerri blank") + msg.rewind() + self.assertTrue(key.verify_ssh_sig(b"jerri blank", msg)) + self.assertEqual(key.get_bits(), 521) + self.assertEqual(key.get_name(), "ecdsa-sha2-nistp521") + + def test_load_ecdsa_256(self): + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_256.key")) + self.assertEqual("ecdsa-sha2-nistp256", key.get_name()) + exp_ecdsa = b(FINGER_ECDSA_256.split()[1].replace(":", "")) + my_ecdsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA_256.split()[1], key.get_base64()) + self.assertEqual(256, key.get_bits()) + + s = StringIO() + key.write_private_key(s) + self.assertEqual(ECDSA_PRIVATE_OUT_256, s.getvalue()) + s.seek(0) + key2 = ECDSAKey.from_private_key(s) + self.assertEqual(key, key2) + + def test_load_ecdsa_password_256(self): + key = ECDSAKey.from_private_key_file( + _support("test_ecdsa_password_256.key"), b"television" + ) + self.assertEqual("ecdsa-sha2-nistp256", key.get_name()) + exp_ecdsa = b(FINGER_ECDSA_256.split()[1].replace(":", "")) + my_ecdsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA_256.split()[1], key.get_base64()) + self.assertEqual(256, key.get_bits()) + + def test_compare_ecdsa_256(self): + # verify that the private & public keys compare equal + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_256.key")) + self.assertEqual(key, key) + pub = ECDSAKey(data=key.asbytes()) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) + + def test_sign_ecdsa_256(self): + # verify that the rsa private key can sign and verify + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_256.key")) + msg = key.sign_ssh_data(b"ice weasels") + self.assertTrue(type(msg) is Message) + msg.rewind() + self.assertEqual("ecdsa-sha2-nistp256", msg.get_text()) + # ECDSA signatures, like DSS signatures, tend to be different + # each time, so we can't compare against a "known correct" + # signature. + # Even the length of the signature can change. + + msg.rewind() + pub = ECDSAKey(data=key.asbytes()) + self.assertTrue(pub.verify_ssh_sig(b"ice weasels", msg)) + + def test_load_ecdsa_384(self): + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_384.key")) + self.assertEqual("ecdsa-sha2-nistp384", key.get_name()) + exp_ecdsa = b(FINGER_ECDSA_384.split()[1].replace(":", "")) + my_ecdsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA_384.split()[1], key.get_base64()) + self.assertEqual(384, key.get_bits()) + + s = StringIO() + key.write_private_key(s) + self.assertEqual(ECDSA_PRIVATE_OUT_384, s.getvalue()) + s.seek(0) + key2 = ECDSAKey.from_private_key(s) + self.assertEqual(key, key2) + + def test_load_ecdsa_password_384(self): + key = ECDSAKey.from_private_key_file( + _support("test_ecdsa_password_384.key"), b"television" + ) + self.assertEqual("ecdsa-sha2-nistp384", key.get_name()) + exp_ecdsa = b(FINGER_ECDSA_384.split()[1].replace(":", "")) + my_ecdsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA_384.split()[1], key.get_base64()) + self.assertEqual(384, key.get_bits()) + + def test_load_ecdsa_transmutes_crypto_exceptions(self): + path = _support("test_ecdsa_256.key") + # TODO: nix unittest for pytest + for exception in (TypeError("onoz"), UnsupportedAlgorithm("oops")): + with patch( + "paramiko.ecdsakey.serialization.load_der_private_key" + ) as loader: + loader.side_effect = exception + with pytest.raises(SSHException, match=str(exception)): + ECDSAKey.from_private_key_file(path) + + def test_compare_ecdsa_384(self): + # verify that the private & public keys compare equal + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_384.key")) + self.assertEqual(key, key) + pub = ECDSAKey(data=key.asbytes()) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) + + def test_sign_ecdsa_384(self): + # verify that the rsa private key can sign and verify + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_384.key")) + msg = key.sign_ssh_data(b"ice weasels") + self.assertTrue(type(msg) is Message) + msg.rewind() + self.assertEqual("ecdsa-sha2-nistp384", msg.get_text()) + # ECDSA signatures, like DSS signatures, tend to be different + # each time, so we can't compare against a "known correct" + # signature. + # Even the length of the signature can change. + + msg.rewind() + pub = ECDSAKey(data=key.asbytes()) + self.assertTrue(pub.verify_ssh_sig(b"ice weasels", msg)) + + def test_load_ecdsa_521(self): + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_521.key")) + self.assertEqual("ecdsa-sha2-nistp521", key.get_name()) + exp_ecdsa = b(FINGER_ECDSA_521.split()[1].replace(":", "")) + my_ecdsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA_521.split()[1], key.get_base64()) + self.assertEqual(521, key.get_bits()) + + s = StringIO() + key.write_private_key(s) + # Different versions of OpenSSL (SSLeay versions 0x1000100f and + # 0x1000207f for instance) use different apparently valid (as far as + # ssh-keygen is concerned) padding. So we can't check the actual value + # of the pem encoded key. + s.seek(0) + key2 = ECDSAKey.from_private_key(s) + self.assertEqual(key, key2) + + def test_load_ecdsa_password_521(self): + key = ECDSAKey.from_private_key_file( + _support("test_ecdsa_password_521.key"), b"television" + ) + self.assertEqual("ecdsa-sha2-nistp521", key.get_name()) + exp_ecdsa = b(FINGER_ECDSA_521.split()[1].replace(":", "")) + my_ecdsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA_521.split()[1], key.get_base64()) + self.assertEqual(521, key.get_bits()) + + def test_compare_ecdsa_521(self): + # verify that the private & public keys compare equal + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_521.key")) + self.assertEqual(key, key) + pub = ECDSAKey(data=key.asbytes()) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) + + def test_sign_ecdsa_521(self): + # verify that the rsa private key can sign and verify + key = ECDSAKey.from_private_key_file(_support("test_ecdsa_521.key")) + msg = key.sign_ssh_data(b"ice weasels") + self.assertTrue(type(msg) is Message) + msg.rewind() + self.assertEqual("ecdsa-sha2-nistp521", msg.get_text()) + # ECDSA signatures, like DSS signatures, tend to be different + # each time, so we can't compare against a "known correct" + # signature. + # Even the length of the signature can change. + + msg.rewind() + pub = ECDSAKey(data=key.asbytes()) + self.assertTrue(pub.verify_ssh_sig(b"ice weasels", msg)) + + def test_load_openssh_format_RSA_key(self): + key = RSAKey.from_private_key_file( + _support("test_rsa_openssh.key"), b"television" + ) + self.assertEqual("ssh-rsa", key.get_name()) + self.assertEqual(PUB_RSA_2K_OPENSSH.split()[1], key.get_base64()) + self.assertEqual(2048, key.get_bits()) + exp_rsa = b(FINGER_RSA_2K_OPENSSH.split()[1].replace(":", "")) + my_rsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_rsa, my_rsa) + + def test_loading_openssh_RSA_keys_uses_correct_p_q(self): + # Re #1723 - not the most elegant test but given how deep it is... + with patch( + "paramiko.rsakey.rsa.RSAPrivateNumbers", wraps=RSAPrivateNumbers + ) as spy: + # Load key + RSAKey.from_private_key_file( + _support("test_rsa_openssh.key"), b"television" + ) + # Ensure spy saw the correct P and Q values as derived from + # hardcoded test private key value + kwargs = spy.call_args[1] + assert kwargs["p"] == RSA_2K_OPENSSH_P + assert kwargs["q"] == RSA_2K_OPENSSH_Q + + def test_load_openssh_format_DSS_key(self): + key = DSSKey.from_private_key_file( + _support("test_dss_openssh.key"), b"television" + ) + self.assertEqual("ssh-dss", key.get_name()) + self.assertEqual(PUB_DSS_1K_OPENSSH.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) + exp_rsa = b(FINGER_DSS_1K_OPENSSH.split()[1].replace(":", "")) + my_rsa = hexlify(key.get_fingerprint()) + self.assertEqual(exp_rsa, my_rsa) + + def test_load_openssh_format_EC_key(self): + key = ECDSAKey.from_private_key_file( + _support("test_ecdsa_384_openssh.key"), b"television" + ) + self.assertEqual("ecdsa-sha2-nistp384", key.get_name()) + self.assertEqual(PUB_EC_384_OPENSSH.split()[1], key.get_base64()) + self.assertEqual(384, key.get_bits()) + exp_fp = b(FINGER_EC_384_OPENSSH.split()[1].replace(":", "")) + my_fp = hexlify(key.get_fingerprint()) + self.assertEqual(exp_fp, my_fp) + + def test_salt_size(self): + # Read an existing encrypted private key + file_ = _support("test_rsa_password.key") + password = "television" + newfile = file_ + ".new" + newpassword = "radio" + key = RSAKey(filename=file_, password=password) + # Write out a newly re-encrypted copy with a new password. + # When the bug under test exists, this will ValueError. + try: + key.write_private_key_file(newfile, password=newpassword) + self.assert_keyfile_is_encrypted(newfile) + # Verify the inner key data still matches (when no ValueError) + key2 = RSAKey(filename=newfile, password=newpassword) + self.assertEqual(key, key2) + finally: + os.remove(newfile) + + def test_load_openssh_format_RSA_nopad(self): + # check just not exploding with 'Invalid key' + RSAKey.from_private_key_file(_support("test_rsa_openssh_nopad.key")) + + def test_stringification(self): + key = RSAKey.from_private_key_file(_support("test_rsa.key")) + comparable = TEST_KEY_BYTESTR_2 if PY2 else TEST_KEY_BYTESTR_3 + self.assertEqual(str(key), comparable) + + def test_ed25519(self): + key1 = Ed25519Key.from_private_key_file(_support("test_ed25519.key")) + key2 = Ed25519Key.from_private_key_file( + _support("test_ed25519_password.key"), b"abc123" + ) + self.assertNotEqual(key1.asbytes(), key2.asbytes()) + + def test_ed25519_funky_padding(self): + # Proves #1306 by just not exploding with 'Invalid key'. + Ed25519Key.from_private_key_file( + _support("test_ed25519-funky-padding.key") + ) + + def test_ed25519_funky_padding_with_passphrase(self): + # Proves #1306 by just not exploding with 'Invalid key'. + Ed25519Key.from_private_key_file( + _support("test_ed25519-funky-padding_password.key"), b"asdf" + ) + + def test_ed25519_compare(self): + # verify that the private & public keys compare equal + key = Ed25519Key.from_private_key_file(_support("test_ed25519.key")) + self.assertEqual(key, key) + pub = Ed25519Key(data=key.asbytes()) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) + + # No point testing on systems that never exhibited the bug originally + @pytest.mark.skipif( + not is_low_entropy(), reason="Not a low-entropy system" + ) + def test_ed25519_32bit_collision(self): + # Re: 2021.10.19 security report email: two different private keys + # which Paramiko compared as equal on low-entropy platforms. + original = Ed25519Key.from_private_key_file( + _support("badhash_key1.ed25519.key") + ) + generated = Ed25519Key.from_private_key_file( + _support("badhash_key2.ed25519.key") + ) + assert original != generated + + def keys(self): + for key_class, filename in [ + (RSAKey, "test_rsa.key"), + (DSSKey, "test_dss.key"), + (ECDSAKey, "test_ecdsa_256.key"), + (Ed25519Key, "test_ed25519.key"), + ]: + key1 = key_class.from_private_key_file(_support(filename)) + key2 = key_class.from_private_key_file(_support(filename)) + yield key1, key2 + + def test_keys_are_comparable(self): + for key1, key2 in self.keys(): + assert key1 == key2 + + def test_keys_are_hashable(self): + # NOTE: this isn't a great test due to hashseed randomization under + # Python 3 preventing use of static values, but it does still prove + # that __hash__ is implemented/doesn't explode & works across instances + for key1, key2 in self.keys(): + assert hash(key1) == hash(key2) + + def test_ed25519_nonbytes_password(self): + # https://github.com/paramiko/paramiko/issues/1039 + Ed25519Key.from_private_key_file( + _support("test_ed25519_password.key"), + # NOTE: not a bytes. Amusingly, the test above for same key DOES + # explicitly cast to bytes...code smell! + "abc123", + ) + # No exception -> it's good. Meh. + + def test_ed25519_load_from_file_obj(self): + with open(_support("test_ed25519.key")) as pkey_fileobj: + key = Ed25519Key.from_private_key(pkey_fileobj) + self.assertEqual(key, key) + self.assertTrue(key.can_sign()) + + def test_keyfile_is_actually_encrypted(self): + # Read an existing encrypted private key + file_ = _support("test_rsa_password.key") + password = "television" + newfile = file_ + ".new" + newpassword = "radio" + key = RSAKey(filename=file_, password=password) + # Write out a newly re-encrypted copy with a new password. + # When the bug under test exists, this will ValueError. + try: + key.write_private_key_file(newfile, password=newpassword) + self.assert_keyfile_is_encrypted(newfile) + finally: + os.remove(newfile) + + def test_certificates(self): + # NOTE: we also test 'live' use of cert auth for all key types in + # test_client.py; this and nearby cert tests are more about the gritty + # details. + # PKey.load_certificate + key_path = _support(os.path.join("cert_support", "test_rsa.key")) + key = RSAKey.from_private_key_file(key_path) + self.assertTrue(key.public_blob is None) + cert_path = _support( + os.path.join("cert_support", "test_rsa.key-cert.pub") + ) + key.load_certificate(cert_path) + self.assertTrue(key.public_blob is not None) + self.assertEqual( + key.public_blob.key_type, "ssh-rsa-cert-v01@openssh.com" + ) + self.assertEqual(key.public_blob.comment, "test_rsa.key.pub") + # Delve into blob contents, for test purposes + msg = Message(key.public_blob.key_blob) + self.assertEqual(msg.get_text(), "ssh-rsa-cert-v01@openssh.com") + msg.get_string() + e = msg.get_mpint() + n = msg.get_mpint() + self.assertEqual(e, key.public_numbers.e) + self.assertEqual(n, key.public_numbers.n) + # Serial number + self.assertEqual(msg.get_int64(), 1234) + + # Prevented from loading certificate that doesn't match + key_path = _support(os.path.join("cert_support", "test_ed25519.key")) + key1 = Ed25519Key.from_private_key_file(key_path) + self.assertRaises( + ValueError, + key1.load_certificate, + _support("test_rsa.key-cert.pub"), + ) + + @patch("paramiko.pkey.os") + def _test_keyfile_race(self, os_, exists): + # Re: CVE-2022-24302 + password = "television" + newpassword = "radio" + source = _support("test_ecdsa_384.key") + new = source + ".new" + # Mock setup + os_.path.exists.return_value = exists + # Attach os flag values to mock + for attr, value in vars(os).items(): + if attr.startswith("O_"): + setattr(os_, attr, value) + # Load fixture key + key = ECDSAKey(filename=source, password=password) + key._write_private_key = Mock() + # Write out in new location + key.write_private_key_file(new, password=newpassword) + # Expected open via os module + os_.open.assert_called_once_with(new, flags=os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=o600) + os_.fdopen.assert_called_once_with(os_.open.return_value, mode="w") + # Old chmod still around for backwards compat + os_.chmod.assert_called_once_with(new, o600) + assert ( + key._write_private_key.call_args[0][0] + == os_.fdopen.return_value.__enter__.return_value + ) + + def test_new_keyfiles_avoid_file_descriptor_race_on_chmod(self): + self._test_keyfile_race(exists=False) + + def test_existing_keyfiles_still_work_ok(self): + self._test_keyfile_race(exists=True) + + def test_new_keyfiles_avoid_descriptor_race_integration(self): + # Integration-style version of above + password = "television" + newpassword = "radio" + source = _support("test_ecdsa_384.key") + new = source + ".new" + # Load fixture key + key = ECDSAKey(filename=source, password=password) + try: + # Write out in new location + key.write_private_key_file(new, password=newpassword) + # Test mode + assert stat.S_IMODE(os.stat(new).st_mode) == o600 + # Prove can open with new password + reloaded = ECDSAKey(filename=new, password=newpassword) + assert reloaded == key + finally: + if os.path.exists(new): + os.unlink(new) +``` + +## `tests/test_pkey.py` — `function:KeyTest._test_keyfile_race` (lines 702-728) + +```python + def _test_keyfile_race(self, os_, exists): + # Re: CVE-2022-24302 + password = "television" + newpassword = "radio" + source = _support("test_ecdsa_384.key") + new = source + ".new" + # Mock setup + os_.path.exists.return_value = exists + # Attach os flag values to mock + for attr, value in vars(os).items(): + if attr.startswith("O_"): + setattr(os_, attr, value) + # Load fixture key + key = ECDSAKey(filename=source, password=password) + key._write_private_key = Mock() + # Write out in new location + key.write_private_key_file(new, password=newpassword) + # Expected open via os module + os_.open.assert_called_once_with(new, flags=os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=o600) + os_.fdopen.assert_called_once_with(os_.open.return_value, mode="w") + # Old chmod still around for backwards compat + os_.chmod.assert_called_once_with(new, o600) + assert ( + key._write_private_key.call_args[0][0] + == os_.fdopen.return_value.__enter__.return_value + ) +``` + +## `tests/test_pkey.py` — `function:KeyTest.test_new_keyfiles_avoid_file_descriptor_race_on_chmod` (lines 730-731) + +```python + def test_new_keyfiles_avoid_file_descriptor_race_on_chmod(self): + self._test_keyfile_race(exists=False) +``` + +## `tests/test_pkey.py` — `function:KeyTest.test_existing_keyfiles_still_work_ok` (lines 733-734) + +```python + def test_existing_keyfiles_still_work_ok(self): + self._test_keyfile_race(exists=True) +``` + +## `tests/test_pkey.py` — `function:KeyTest.test_new_keyfiles_avoid_descriptor_race_integration` (lines 736-754) + +```python + def test_new_keyfiles_avoid_descriptor_race_integration(self): + # Integration-style version of above + password = "television" + newpassword = "radio" + source = _support("test_ecdsa_384.key") + new = source + ".new" + # Load fixture key + key = ECDSAKey(filename=source, password=password) + try: + # Write out in new location + key.write_private_key_file(new, password=newpassword) + # Test mode + assert stat.S_IMODE(os.stat(new).st_mode) == o600 + # Prove can open with new password + reloaded = ECDSAKey(filename=new, password=newpassword) + assert reloaded == key + finally: + if os.path.exists(new): + os.unlink(new) +``` + +## `tests/test_pkey.py` — `module:@26` (lines 26-26) + +```python +import stat +``` + +## `tests/test_pkey.py` — `module:@40` (lines 40-40) + +```python +from paramiko.common import o600 +``` + +## `tests/test_pkey.py` — `module:@44` (lines 44-44) + +```python +from mock import patch, Mock +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..b29fd258641b62fbb330ebdba0b5659ace67da35 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/pre_context.md @@ -0,0 +1,639 @@ +# Patch-overlapping Python context before the fix + +## `paramiko/pkey.py` — `class:PKey` (lines 62-653) + +```python +class PKey(object): + """ + Base class for public keys. + """ + + # known encryption types for private key files: + _CIPHER_TABLE = { + "AES-128-CBC": { + "cipher": algorithms.AES, + "keysize": 16, + "blocksize": 16, + "mode": modes.CBC, + }, + "AES-256-CBC": { + "cipher": algorithms.AES, + "keysize": 32, + "blocksize": 16, + "mode": modes.CBC, + }, + "DES-EDE3-CBC": { + "cipher": algorithms.TripleDES, + "keysize": 24, + "blocksize": 8, + "mode": modes.CBC, + }, + } + _PRIVATE_KEY_FORMAT_ORIGINAL = 1 + _PRIVATE_KEY_FORMAT_OPENSSH = 2 + BEGIN_TAG = re.compile( + r"^-{5}BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$" + ) + END_TAG = re.compile(r"^-{5}END (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$") + + def __init__(self, msg=None, data=None): + """ + Create a new instance of this public key type. If ``msg`` is given, + the key's public part(s) will be filled in from the message. If + ``data`` is given, the key's public part(s) will be filled in from + the string. + + :param .Message msg: + an optional SSH `.Message` containing a public key of this type. + :param str data: an optional string containing a public key + of this type + + :raises: `.SSHException` -- + if a key cannot be created from the ``data`` or ``msg`` given, or + no key was passed in. + """ + pass + + def asbytes(self): + """ + Return a string of an SSH `.Message` made up of the public part(s) of + this key. This string is suitable for passing to `__init__` to + re-create the key object later. + """ + return bytes() + + def __str__(self): + return self.asbytes() + + # noinspection PyUnresolvedReferences + # TODO: The comparison functions should be removed as per: + # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons + def __cmp__(self, other): + """ + Compare this key to another. Returns 0 if this key is equivalent to + the given key, or non-0 if they are different. Only the public parts + of the key are compared, so a public key will compare equal to its + corresponding private key. + + :param .PKey other: key to compare to. + """ + hs = hash(self) + ho = hash(other) + if hs != ho: + return cmp(hs, ho) # noqa + return cmp(self.asbytes(), other.asbytes()) # noqa + + def __eq__(self, other): + return self._fields == other._fields + + def __hash__(self): + return hash(self._fields) + + @property + def _fields(self): + raise NotImplementedError + + def get_name(self): + """ + Return the name of this private key implementation. + + :return: + name of this private key type, in SSH terminology, as a `str` (for + example, ``"ssh-rsa"``). + """ + return "" + + def get_bits(self): + """ + Return the number of significant bits in this key. This is useful + for judging the relative security of a key. + + :return: bits in the key (as an `int`) + """ + return 0 + + def can_sign(self): + """ + Return ``True`` if this key has the private part necessary for signing + data. + """ + return False + + def get_fingerprint(self): + """ + Return an MD5 fingerprint of the public part of this key. Nothing + secret is revealed. + + :return: + a 16-byte `string ` (binary) of the MD5 fingerprint, in SSH + format. + """ + return md5(self.asbytes()).digest() + + def get_base64(self): + """ + Return a base64 string containing the public part of this key. Nothing + secret is revealed. This format is compatible with that used to store + public key files or recognized host keys. + + :return: a base64 `string ` containing the public part of the key. + """ + return u(encodebytes(self.asbytes())).replace("\n", "") + + def sign_ssh_data(self, data, algorithm=None): + """ + Sign a blob of data with this private key, and return a `.Message` + representing an SSH signature message. + + :param str data: + the data to sign. + :param str algorithm: + the signature algorithm to use, if different from the key's + internal name. Default: ``None``. + :return: an SSH signature `message <.Message>`. + + .. versionchanged:: 2.9 + Added the ``algorithm`` kwarg. + """ + return bytes() + + def verify_ssh_sig(self, data, msg): + """ + Given a blob of data, and an SSH message representing a signature of + that data, verify that it was signed with this key. + + :param str data: the data that was signed. + :param .Message msg: an SSH signature message + :return: + ``True`` if the signature verifies correctly; ``False`` otherwise. + """ + return False + + @classmethod + def from_private_key_file(cls, filename, password=None): + """ + Create a key object by reading a private key file. If the private + key is encrypted and ``password`` is not ``None``, the given password + will be used to decrypt the key (otherwise `.PasswordRequiredException` + is thrown). Through the magic of Python, this factory method will + exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but + is useless on the abstract PKey class. + + :param str filename: name of the file to read + :param str password: + an optional password to use to decrypt the key file, if it's + encrypted + :return: a new `.PKey` based on the given private key + + :raises: ``IOError`` -- if there was an error reading the file + :raises: `.PasswordRequiredException` -- if the private key file is + encrypted, and ``password`` is ``None`` + :raises: `.SSHException` -- if the key file is invalid + """ + key = cls(filename=filename, password=password) + return key + + @classmethod + def from_private_key(cls, file_obj, password=None): + """ + Create a key object by reading a private key from a file (or file-like) + object. If the private key is encrypted and ``password`` is not + ``None``, the given password will be used to decrypt the key (otherwise + `.PasswordRequiredException` is thrown). + + :param file_obj: the file-like object to read from + :param str password: + an optional password to use to decrypt the key, if it's encrypted + :return: a new `.PKey` based on the given private key + + :raises: ``IOError`` -- if there was an error reading the key + :raises: `.PasswordRequiredException` -- + if the private key file is encrypted, and ``password`` is ``None`` + :raises: `.SSHException` -- if the key file is invalid + """ + key = cls(file_obj=file_obj, password=password) + return key + + def write_private_key_file(self, filename, password=None): + """ + Write private key contents into a file. If the password is not + ``None``, the key is encrypted before writing. + + :param str filename: name of the file to write + :param str password: + an optional password to use to encrypt the key file + + :raises: ``IOError`` -- if there was an error writing the file + :raises: `.SSHException` -- if the key is invalid + """ + raise Exception("Not implemented in PKey") + + def write_private_key(self, file_obj, password=None): + """ + Write private key contents into a file (or file-like) object. If the + password is not ``None``, the key is encrypted before writing. + + :param file_obj: the file-like object to write into + :param str password: an optional password to use to encrypt the key + + :raises: ``IOError`` -- if there was an error writing to the file + :raises: `.SSHException` -- if the key is invalid + """ + raise Exception("Not implemented in PKey") + + def _read_private_key_file(self, tag, filename, password=None): + """ + Read an SSH2-format private key file, looking for a string of the type + ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we + find, and return it as a string. If the private key is encrypted and + ``password`` is not ``None``, the given password will be used to + decrypt the key (otherwise `.PasswordRequiredException` is thrown). + + :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the + data block. + :param str filename: name of the file to read. + :param str password: + an optional password to use to decrypt the key file, if it's + encrypted. + :return: data blob (`str`) that makes up the private key. + + :raises: ``IOError`` -- if there was an error reading the file. + :raises: `.PasswordRequiredException` -- if the private key file is + encrypted, and ``password`` is ``None``. + :raises: `.SSHException` -- if the key file is invalid. + """ + with open(filename, "r") as f: + data = self._read_private_key(tag, f, password) + return data + + def _read_private_key(self, tag, f, password=None): + lines = f.readlines() + + # find the BEGIN tag + start = 0 + m = self.BEGIN_TAG.match(lines[start]) + line_range = len(lines) - 1 + while start < line_range and not m: + start += 1 + m = self.BEGIN_TAG.match(lines[start]) + start += 1 + keytype = m.group(1) if m else None + if start >= len(lines) or keytype is None: + raise SSHException("not a valid {} private key file".format(tag)) + + # find the END tag + end = start + m = self.END_TAG.match(lines[end]) + while end < line_range and not m: + end += 1 + m = self.END_TAG.match(lines[end]) + + if keytype == tag: + data = self._read_private_key_pem(lines, end, password) + pkformat = self._PRIVATE_KEY_FORMAT_ORIGINAL + elif keytype == "OPENSSH": + data = self._read_private_key_openssh(lines[start:end], password) + pkformat = self._PRIVATE_KEY_FORMAT_OPENSSH + else: + raise SSHException( + "encountered {} key, expected {} key".format(keytype, tag) + ) + + return pkformat, data + + def _got_bad_key_format_id(self, id_): + err = "{}._read_private_key() spat out an unknown key format id '{}'" + raise SSHException(err.format(self.__class__.__name__, id_)) + + def _read_private_key_pem(self, lines, end, password): + start = 0 + # parse any headers first + headers = {} + start += 1 + while start < len(lines): + line = lines[start].split(": ") + if len(line) == 1: + break + headers[line[0].lower()] = line[1].strip() + start += 1 + # if we trudged to the end of the file, just try to cope. + try: + data = decodebytes(b("".join(lines[start:end]))) + except base64.binascii.Error as e: + raise SSHException("base64 decoding error: {}".format(e)) + if "proc-type" not in headers: + # unencryped: done + return data + # encrypted keyfile: will need a password + proc_type = headers["proc-type"] + if proc_type != "4,ENCRYPTED": + raise SSHException( + 'Unknown private key structure "{}"'.format(proc_type) + ) + try: + encryption_type, saltstr = headers["dek-info"].split(",") + except: + raise SSHException("Can't parse DEK-info in private key file") + if encryption_type not in self._CIPHER_TABLE: + raise SSHException( + 'Unknown private key cipher "{}"'.format(encryption_type) + ) + # if no password was passed in, + # raise an exception pointing out that we need one + if password is None: + raise PasswordRequiredException("Private key file is encrypted") + cipher = self._CIPHER_TABLE[encryption_type]["cipher"] + keysize = self._CIPHER_TABLE[encryption_type]["keysize"] + mode = self._CIPHER_TABLE[encryption_type]["mode"] + salt = unhexlify(b(saltstr)) + key = util.generate_key_bytes(md5, salt, password, keysize) + decryptor = Cipher( + cipher(key), mode(salt), backend=default_backend() + ).decryptor() + return decryptor.update(data) + decryptor.finalize() + + def _read_private_key_openssh(self, lines, password): + """ + Read the new OpenSSH SSH2 private key format available + since OpenSSH version 6.5 + Reference: + https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key + """ + try: + data = decodebytes(b("".join(lines))) + except base64.binascii.Error as e: + raise SSHException("base64 decoding error: {}".format(e)) + + # read data struct + auth_magic = data[:15] + if auth_magic != OPENSSH_AUTH_MAGIC: + raise SSHException("unexpected OpenSSH key header encountered") + + cstruct = self._uint32_cstruct_unpack(data[15:], "sssur") + cipher, kdfname, kdf_options, num_pubkeys, remainder = cstruct + # For now, just support 1 key. + if num_pubkeys > 1: + raise SSHException( + "unsupported: private keyfile has multiple keys" + ) + pubkey, privkey_blob = self._uint32_cstruct_unpack(remainder, "ss") + + if kdfname == b("bcrypt"): + if cipher == b("aes256-cbc"): + mode = modes.CBC + elif cipher == b("aes256-ctr"): + mode = modes.CTR + else: + raise SSHException( + "unknown cipher `{}` used in private key file".format( + cipher.decode("utf-8") + ) + ) + # Encrypted private key. + # If no password was passed in, raise an exception pointing + # out that we need one + if password is None: + raise PasswordRequiredException( + "private key file is encrypted" + ) + + # Unpack salt and rounds from kdfoptions + salt, rounds = self._uint32_cstruct_unpack(kdf_options, "su") + + # run bcrypt kdf to derive key and iv/nonce (32 + 16 bytes) + key_iv = bcrypt.kdf( + b(password), + b(salt), + 48, + rounds, + # We can't control how many rounds are on disk, so no sense + # warning about it. + ignore_few_rounds=True, + ) + key = key_iv[:32] + iv = key_iv[32:] + + # decrypt private key blob + decryptor = Cipher( + algorithms.AES(key), mode(iv), default_backend() + ).decryptor() + decrypted_privkey = decryptor.update(privkey_blob) + decrypted_privkey += decryptor.finalize() + elif cipher == b("none") and kdfname == b("none"): + # Unencrypted private key + decrypted_privkey = privkey_blob + else: + raise SSHException( + "unknown cipher or kdf used in private key file" + ) + + # Unpack private key and verify checkints + cstruct = self._uint32_cstruct_unpack(decrypted_privkey, "uusr") + checkint1, checkint2, keytype, keydata = cstruct + + if checkint1 != checkint2: + raise SSHException( + "OpenSSH private key file checkints do not match" + ) + + return _unpad_openssh(keydata) + + def _uint32_cstruct_unpack(self, data, strformat): + """ + Used to read new OpenSSH private key format. + Unpacks a c data structure containing a mix of 32-bit uints and + variable length strings prefixed by 32-bit uint size field, + according to the specified format. Returns the unpacked vars + in a tuple. + Format strings: + s - denotes a string + i - denotes a long integer, encoded as a byte string + u - denotes a 32-bit unsigned integer + r - the remainder of the input string, returned as a string + """ + arr = [] + idx = 0 + try: + for f in strformat: + if f == "s": + # string + s_size = struct.unpack(">L", data[idx : idx + 4])[0] + idx += 4 + s = data[idx : idx + s_size] + idx += s_size + arr.append(s) + if f == "i": + # long integer + s_size = struct.unpack(">L", data[idx : idx + 4])[0] + idx += 4 + s = data[idx : idx + s_size] + idx += s_size + i = util.inflate_long(s, True) + arr.append(i) + elif f == "u": + # 32-bit unsigned int + u = struct.unpack(">L", data[idx : idx + 4])[0] + idx += 4 + arr.append(u) + elif f == "r": + # remainder as string + s = data[idx:] + arr.append(s) + break + except Exception as e: + # PKey-consuming code frequently wants to save-and-skip-over issues + # with loading keys, and uses SSHException as the (really friggin + # awful) signal for this. So for now...we do this. + raise SSHException(str(e)) + return tuple(arr) + + def _write_private_key_file(self, filename, key, format, password=None): + """ + Write an SSH2-format private key file in a form that can be read by + paramiko or openssh. If no password is given, the key is written in + a trivially-encoded format (base64) which is completely insecure. If + a password is given, DES-EDE3-CBC is used. + + :param str tag: + ``"RSA"`` or ``"DSA"``, the tag used to mark the data block. + :param filename: name of the file to write. + :param str data: data blob that makes up the private key. + :param str password: an optional password to use to encrypt the file. + + :raises: ``IOError`` -- if there was an error writing the file. + """ + with open(filename, "w") as f: + os.chmod(filename, o600) + self._write_private_key(f, key, format, password=password) + + def _write_private_key(self, f, key, format, password=None): + if password is None: + encryption = serialization.NoEncryption() + else: + encryption = serialization.BestAvailableEncryption(b(password)) + + f.write( + key.private_bytes( + serialization.Encoding.PEM, format, encryption + ).decode() + ) + + def _check_type_and_load_cert(self, msg, key_type, cert_type): + """ + Perform message type-checking & optional certificate loading. + + This includes fast-forwarding cert ``msg`` objects past the nonce, so + that the subsequent fields are the key numbers; thus the caller may + expect to treat the message as key material afterwards either way. + + The obtained key type is returned for classes which need to know what + it was (e.g. ECDSA.) + """ + # Normalization; most classes have a single key type and give a string, + # but eg ECDSA is a 1:N mapping. + key_types = key_type + cert_types = cert_type + if isinstance(key_type, string_types): + key_types = [key_types] + if isinstance(cert_types, string_types): + cert_types = [cert_types] + # Can't do much with no message, that should've been handled elsewhere + if msg is None: + raise SSHException("Key object may not be empty") + # First field is always key type, in either kind of object. (make sure + # we rewind before grabbing it - sometimes caller had to do their own + # introspection first!) + msg.rewind() + type_ = msg.get_text() + # Regular public key - nothing special to do besides the implicit + # type check. + if type_ in key_types: + pass + # OpenSSH-compatible certificate - store full copy as .public_blob + # (so signing works correctly) and then fast-forward past the + # nonce. + elif type_ in cert_types: + # This seems the cleanest way to 'clone' an already-being-read + # message; they're *IO objects at heart and their .getvalue() + # always returns the full value regardless of pointer position. + self.load_certificate(Message(msg.asbytes())) + # Read out nonce as it comes before the public numbers. + # TODO: usefully interpret it & other non-public-number fields + # (requires going back into per-type subclasses.) + msg.get_string() + else: + err = "Invalid key (class: {}, data type: {}" + raise SSHException(err.format(self.__class__.__name__, type_)) + + def load_certificate(self, value): + """ + Supplement the private key contents with data loaded from an OpenSSH + public key (``.pub``) or certificate (``-cert.pub``) file, a string + containing such a file, or a `.Message` object. + + The .pub contents adds no real value, since the private key + file includes sufficient information to derive the public + key info. For certificates, however, this can be used on + the client side to offer authentication requests to the server + based on certificate instead of raw public key. + + See: + https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys + + Note: very little effort is made to validate the certificate contents, + that is for the server to decide if it is good enough to authenticate + successfully. + """ + if isinstance(value, Message): + constructor = "from_message" + elif os.path.isfile(value): + constructor = "from_file" + else: + constructor = "from_string" + blob = getattr(PublicBlob, constructor)(value) + if not blob.key_type.startswith(self.get_name()): + err = "PublicBlob type {} incompatible with key type {}" + raise ValueError(err.format(blob.key_type, self.get_name())) + self.public_blob = blob +``` + +## `paramiko/pkey.py` — `function:PKey._write_private_key_file` (lines 546-563) + +```python + def _write_private_key_file(self, filename, key, format, password=None): + """ + Write an SSH2-format private key file in a form that can be read by + paramiko or openssh. If no password is given, the key is written in + a trivially-encoded format (base64) which is completely insecure. If + a password is given, DES-EDE3-CBC is used. + + :param str tag: + ``"RSA"`` or ``"DSA"``, the tag used to mark the data block. + :param filename: name of the file to write. + :param str data: data blob that makes up the private key. + :param str password: an optional password to use to encrypt the file. + + :raises: ``IOError`` -- if there was an error writing the file. + """ + with open(filename, "w") as f: + os.chmod(filename, o600) + self._write_private_key(f, key, format, password=password) +``` + +## `tests/test_pkey.py` — `module:@26` (lines 26-26) + +```python +from binascii import hexlify +``` + +## `tests/test_pkey.py` — `module:@42` (lines 42-42) + +```python +from mock import patch +``` + +## `tests/test_pkey.py` — `module:@43` (lines 43-43) + +```python +import pytest +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6a37db73a4a41bd7fdc132cddf3af7b1145115f6 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/task.json @@ -0,0 +1,58 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-bf4aded7c76d99f9ef84", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-bf4aded7c76d99f9ef84", + "project_id": "pyvul__paramiko__paramiko", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "paramiko/pkey.py", + "tests/test_pkey.py" + ], + "patch_units": { + "before": [ + "class:PKey", + "function:PKey._write_private_key_file", + "module:@26", + "module:@42", + "module:@43" + ], + "after": [ + "class:PKey", + "function:PKey._write_private_key_file", + "class:KeyTest", + "function:KeyTest._test_keyfile_race", + "function:KeyTest.test_new_keyfiles_avoid_file_descriptor_race_on_chmod", + "function:KeyTest.test_existing_keyfiles_still_work_ok", + "function:KeyTest.test_new_keyfiles_avoid_descriptor_race_integration", + "module:@26", + "module:@40", + "module:@44" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/473a61d6d5f4fbd16aa0679010715d7fbf101331c0a698aeb81ad0f0d1912d9f/database", + "cache_key": "473a61d6d5f4fbd16aa0679010715d7fbf101331c0a698aeb81ad0f0d1912d9f", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/dd0b49ac6eafbab3961d79b42dd7811c8f730a3ed3aa1ed448100c839dc8f157/database", + "cache_key": "dd0b49ac6eafbab3961d79b42dd7811c8f730a3ed3aa1ed448100c839dc8f157", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/3101c97a8e7df02eac3c6652b60fa2432b3a78a3e58af20e9ac886e123832167/database", + "cache_key": "3101c97a8e7df02eac3c6652b60fa2432b3a78a3e58af20e9ac886e123832167", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-bf4aded7c76d99f9ef84/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-bf4aded7c76d99f9ef84/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-bf4aded7c76d99f9ef84/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..534a5a26099faf60f2c82911c01003f98c81f6cf --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/patch.diff @@ -0,0 +1,93 @@ +diff --git a/nltk/tokenize/punkt.py b/nltk/tokenize/punkt.py +index a08ff4c90..54937b9ec 100644 +--- a/nltk/tokenize/punkt.py ++++ b/nltk/tokenize/punkt.py +@@ -266,7 +266,6 @@ class PunktLanguageVars: + return self._word_tokenizer_re().findall(s) + + _period_context_fmt = r""" +- \S* # some word material + %(SentEndChars)s # a potential sentence ending + (?=(?P + %(NonWord)s # either other punctuation +@@ -1284,8 +1283,7 @@ class PunktSentenceTokenizer(PunktBaseClass, TokenizerI): + See format_debug_decision() to help make this output readable. + """ + +- for match in self._lang_vars.period_context_re().finditer(text): +- decision_text = match.group() + match.group("after_tok") ++ for match, decision_text in self._match_potential_end_contexts(text): + tokens = self._tokenize_words(decision_text) + tokens = list(self._annotate_first_pass(tokens)) + while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars): +@@ -1333,10 +1331,68 @@ class PunktSentenceTokenizer(PunktBaseClass, TokenizerI): + """ + return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] + ++ def _match_potential_end_contexts(self, text): ++ """ ++ Given a text, find the matches of potential sentence breaks, ++ alongside the contexts surrounding these sentence breaks. ++ ++ Since the fix for the ReDOS discovered in issue #2866, we no longer match ++ the word before a potential end of sentence token. Instead, we use a separate ++ regex for this. As a consequence, `finditer`'s desire to find non-overlapping ++ matches no longer aids us in finding the single longest match. ++ Where previously, we could use:: ++ ++ >>> pst = PunktSentenceTokenizer() ++ >>> text = "Very bad acting!!! I promise." ++ >>> list(pst._lang_vars.period_context_re().finditer(text)) # doctest: +SKIP ++ [] ++ ++ Now we have to find the word before (i.e. 'acting') separately, and `finditer` ++ returns:: ++ ++ >>> pst = PunktSentenceTokenizer() ++ >>> text = "Very bad acting!!! I promise." ++ >>> list(pst._lang_vars.period_context_re().finditer(text)) # doctest: +NORMALIZE_WHITESPACE ++ [, ++ , ++ ] ++ ++ So, we need to find the word before the match from right to left, and then manually remove ++ the overlaps. That is what this method does:: ++ ++ >>> pst = PunktSentenceTokenizer() ++ >>> text = "Very bad acting!!! I promise." ++ >>> pst._match_potential_end_contexts(text) ++ [(, 'acting!!! I')] ++ ++ :param text: String of one or more sentences ++ :type text: str ++ :return: List of match-context tuples. ++ :rtype: List[Tuple[re.Match, str]] ++ """ ++ before_words = {} ++ matches = [] ++ for match in reversed(list(self._lang_vars.period_context_re().finditer(text))): ++ # Ignore matches that have already been captured by matches to the right of this match ++ if matches and match.end() > before_start: ++ continue ++ # Find the word before the current match ++ split = text[: match.start()].rsplit(maxsplit=1) ++ before_start = len(split[0]) if len(split) == 2 else 0 ++ before_words[match] = split[-1] ++ matches.append(match) ++ ++ return [ ++ ( ++ match, ++ before_words[match] + match.group() + match.group("after_tok"), ++ ) ++ for match in matches[::-1] ++ ] ++ + def _slices_from_text(self, text): + last_break = 0 +- for match in self._lang_vars.period_context_re().finditer(text): +- context = match.group() + match.group("after_tok") ++ for match, context in self._match_potential_end_contexts(text): + if self.text_contains_sentbreak(context): + yield slice(last_break, match.end()) + if match.group("next_tok"): diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..26435aaea5c1cfde78c69d741bf51fad9a7d9269 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/post_context.md @@ -0,0 +1,701 @@ +# Patch-overlapping Python context after the fix + +## `nltk/tokenize/punkt.py` — `class:PunktLanguageVars` (lines 182-293) + +```python +class PunktLanguageVars: + """ + Stores variables, mostly regular expressions, which may be + language-dependent for correct application of the algorithm. + An extension of this class may modify its properties to suit + a language other than English; an instance can then be passed + as an argument to PunktSentenceTokenizer and PunktTrainer + constructors. + """ + + __slots__ = ("_re_period_context", "_re_word_tokenizer") + + def __getstate__(self): + # All modifications to the class are performed by inheritance. + # Non-default parameters to be pickled must be defined in the inherited + # class. + return 1 + + def __setstate__(self, state): + return 1 + + sent_end_chars = (".", "?", "!") + """Characters which are candidates for sentence boundaries""" + + @property + def _re_sent_end_chars(self): + return "[%s]" % re.escape("".join(self.sent_end_chars)) + + internal_punctuation = ",:;" # might want to extend this.. + """sentence internal punctuation, which indicates an abbreviation if + preceded by a period-final token.""" + + re_boundary_realignment = re.compile(r'["\')\]}]+?(?:\s+|(?=--)|$)', re.MULTILINE) + """Used to realign punctuation that should be included in a sentence + although it follows the period (or ?, !).""" + + _re_word_start = r"[^\(\"\`{\[:;&\#\*@\)}\]\-,]" + """Excludes some characters from starting word tokens""" + + @property + def _re_non_word_chars(self): + return r"(?:[)\";}\]\*:@\'\({\[%s])" % re.escape( + "".join(set(self.sent_end_chars) - {"."}) + ) + + """Characters that cannot appear within words""" + + _re_multi_char_punct = r"(?:\-{2,}|\.{2,}|(?:\.\s){2,}\.)" + """Hyphen and ellipsis are multi-character punctuation""" + + _word_tokenize_fmt = r"""( + %(MultiChar)s + | + (?=%(WordStart)s)\S+? # Accept word characters until end is found + (?= # Sequences marking a word's end + \s| # White-space + $| # End-of-string + %(NonWord)s|%(MultiChar)s| # Punctuation + ,(?=$|\s|%(NonWord)s|%(MultiChar)s) # Comma if at end of word + ) + | + \S + )""" + """Format of a regular expression to split punctuation from words, + excluding period.""" + + def _word_tokenizer_re(self): + """Compiles and returns a regular expression for word tokenization""" + try: + return self._re_word_tokenizer + except AttributeError: + self._re_word_tokenizer = re.compile( + self._word_tokenize_fmt + % { + "NonWord": self._re_non_word_chars, + "MultiChar": self._re_multi_char_punct, + "WordStart": self._re_word_start, + }, + re.UNICODE | re.VERBOSE, + ) + return self._re_word_tokenizer + + def word_tokenize(self, s): + """Tokenize a string to split off punctuation other than periods""" + return self._word_tokenizer_re().findall(s) + + _period_context_fmt = r""" + %(SentEndChars)s # a potential sentence ending + (?=(?P + %(NonWord)s # either other punctuation + | + \s+(?P\S+) # or whitespace and some other token + ))""" + """Format of a regular expression to find contexts including possible + sentence boundaries. Matches token which the possible sentence boundary + ends, and matches the following token within a lookahead expression.""" + + def period_context_re(self): + """Compiles and returns a regular expression to find contexts + including possible sentence boundaries.""" + try: + return self._re_period_context + except: + self._re_period_context = re.compile( + self._period_context_fmt + % { + "NonWord": self._re_non_word_chars, + "SentEndChars": self._re_sent_end_chars, + }, + re.UNICODE | re.VERBOSE, + ) + return self._re_period_context +``` + +## `nltk/tokenize/punkt.py` — `class:PunktSentenceTokenizer` (lines 1235-1691) + +```python +class PunktSentenceTokenizer(PunktBaseClass, TokenizerI): + """ + A sentence tokenizer which uses an unsupervised algorithm to build + a model for abbreviation words, collocations, and words that start + sentences; and then uses that model to find sentence boundaries. + This approach has been shown to work well for many European + languages. + """ + + def __init__( + self, train_text=None, verbose=False, lang_vars=None, token_cls=PunktToken + ): + """ + train_text can either be the sole training text for this sentence + boundary detector, or can be a PunktParameters object. + """ + PunktBaseClass.__init__(self, lang_vars=lang_vars, token_cls=token_cls) + + if train_text: + self._params = self.train(train_text, verbose) + + def train(self, train_text, verbose=False): + """ + Derives parameters from a given training text, or uses the parameters + given. Repeated calls to this method destroy previous parameters. For + incremental training, instantiate a separate PunktTrainer instance. + """ + if not isinstance(train_text, str): + return train_text + return PunktTrainer( + train_text, lang_vars=self._lang_vars, token_cls=self._Token + ).get_params() + + # //////////////////////////////////////////////////////////// + # { Tokenization + # //////////////////////////////////////////////////////////// + + def tokenize(self, text, realign_boundaries=True): + """ + Given a text, returns a list of the sentences in that text. + """ + return list(self.sentences_from_text(text, realign_boundaries)) + + def debug_decisions(self, text): + """ + Classifies candidate periods as sentence breaks, yielding a dict for + each that may be used to understand why the decision was made. + + See format_debug_decision() to help make this output readable. + """ + + for match, decision_text in self._match_potential_end_contexts(text): + tokens = self._tokenize_words(decision_text) + tokens = list(self._annotate_first_pass(tokens)) + while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars): + tokens.pop(0) + yield { + "period_index": match.end() - 1, + "text": decision_text, + "type1": tokens[0].type, + "type2": tokens[1].type, + "type1_in_abbrs": bool(tokens[0].abbr), + "type1_is_initial": bool(tokens[0].is_initial), + "type2_is_sent_starter": tokens[1].type_no_sentperiod + in self._params.sent_starters, + "type2_ortho_heuristic": self._ortho_heuristic(tokens[1]), + "type2_ortho_contexts": set( + self._params._debug_ortho_context(tokens[1].type_no_sentperiod) + ), + "collocation": ( + tokens[0].type_no_sentperiod, + tokens[1].type_no_sentperiod, + ) + in self._params.collocations, + "reason": self._second_pass_annotation(tokens[0], tokens[1]) + or REASON_DEFAULT_DECISION, + "break_decision": tokens[0].sentbreak, + } + + def span_tokenize(self, text, realign_boundaries=True): + """ + Given a text, generates (start, end) spans of sentences + in the text. + """ + slices = self._slices_from_text(text) + if realign_boundaries: + slices = self._realign_boundaries(text, slices) + for sentence in slices: + yield (sentence.start, sentence.stop) + + def sentences_from_text(self, text, realign_boundaries=True): + """ + Given a text, generates the sentences in that text by only + testing candidate sentence breaks. If realign_boundaries is + True, includes in the sentence closing punctuation that + follows the period. + """ + return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] + + def _match_potential_end_contexts(self, text): + """ + Given a text, find the matches of potential sentence breaks, + alongside the contexts surrounding these sentence breaks. + + Since the fix for the ReDOS discovered in issue #2866, we no longer match + the word before a potential end of sentence token. Instead, we use a separate + regex for this. As a consequence, `finditer`'s desire to find non-overlapping + matches no longer aids us in finding the single longest match. + Where previously, we could use:: + + >>> pst = PunktSentenceTokenizer() + >>> text = "Very bad acting!!! I promise." + >>> list(pst._lang_vars.period_context_re().finditer(text)) # doctest: +SKIP + [] + + Now we have to find the word before (i.e. 'acting') separately, and `finditer` + returns:: + + >>> pst = PunktSentenceTokenizer() + >>> text = "Very bad acting!!! I promise." + >>> list(pst._lang_vars.period_context_re().finditer(text)) # doctest: +NORMALIZE_WHITESPACE + [, + , + ] + + So, we need to find the word before the match from right to left, and then manually remove + the overlaps. That is what this method does:: + + >>> pst = PunktSentenceTokenizer() + >>> text = "Very bad acting!!! I promise." + >>> pst._match_potential_end_contexts(text) + [(, 'acting!!! I')] + + :param text: String of one or more sentences + :type text: str + :return: List of match-context tuples. + :rtype: List[Tuple[re.Match, str]] + """ + before_words = {} + matches = [] + for match in reversed(list(self._lang_vars.period_context_re().finditer(text))): + # Ignore matches that have already been captured by matches to the right of this match + if matches and match.end() > before_start: + continue + # Find the word before the current match + split = text[: match.start()].rsplit(maxsplit=1) + before_start = len(split[0]) if len(split) == 2 else 0 + before_words[match] = split[-1] + matches.append(match) + + return [ + ( + match, + before_words[match] + match.group() + match.group("after_tok"), + ) + for match in matches[::-1] + ] + + def _slices_from_text(self, text): + last_break = 0 + for match, context in self._match_potential_end_contexts(text): + if self.text_contains_sentbreak(context): + yield slice(last_break, match.end()) + if match.group("next_tok"): + # next sentence starts after whitespace + last_break = match.start("next_tok") + else: + # next sentence starts at following punctuation + last_break = match.end() + # The last sentence should not contain trailing whitespace. + yield slice(last_break, len(text.rstrip())) + + def _realign_boundaries(self, text, slices): + """ + Attempts to realign punctuation that falls after the period but + should otherwise be included in the same sentence. + + For example: "(Sent1.) Sent2." will otherwise be split as:: + + ["(Sent1.", ") Sent1."]. + + This method will produce:: + + ["(Sent1.)", "Sent2."]. + """ + realign = 0 + for sentence1, sentence2 in _pair_iter(slices): + sentence1 = slice(sentence1.start + realign, sentence1.stop) + if not sentence2: + if text[sentence1]: + yield sentence1 + continue + + m = self._lang_vars.re_boundary_realignment.match(text[sentence2]) + if m: + yield slice(sentence1.start, sentence2.start + len(m.group(0).rstrip())) + realign = m.end() + else: + realign = 0 + if text[sentence1]: + yield sentence1 + + def text_contains_sentbreak(self, text): + """ + Returns True if the given text includes a sentence break. + """ + found = False # used to ignore last token + for tok in self._annotate_tokens(self._tokenize_words(text)): + if found: + return True + if tok.sentbreak: + found = True + return False + + def sentences_from_text_legacy(self, text): + """ + Given a text, generates the sentences in that text. Annotates all + tokens, rather than just those with possible sentence breaks. Should + produce the same results as ``sentences_from_text``. + """ + tokens = self._annotate_tokens(self._tokenize_words(text)) + return self._build_sentence_list(text, tokens) + + def sentences_from_tokens(self, tokens): + """ + Given a sequence of tokens, generates lists of tokens, each list + corresponding to a sentence. + """ + tokens = iter(self._annotate_tokens(self._Token(t) for t in tokens)) + sentence = [] + for aug_tok in tokens: + sentence.append(aug_tok.tok) + if aug_tok.sentbreak: + yield sentence + sentence = [] + if sentence: + yield sentence + + def _annotate_tokens(self, tokens): + """ + Given a set of tokens augmented with markers for line-start and + paragraph-start, returns an iterator through those tokens with full + annotation including predicted sentence breaks. + """ + # Make a preliminary pass through the document, marking likely + # sentence breaks, abbreviations, and ellipsis tokens. + tokens = self._annotate_first_pass(tokens) + + # Make a second pass through the document, using token context + # information to change our preliminary decisions about where + # sentence breaks, abbreviations, and ellipsis occurs. + tokens = self._annotate_second_pass(tokens) + + ## [XX] TESTING + # tokens = list(tokens) + # self.dump(tokens) + + return tokens + + def _build_sentence_list(self, text, tokens): + """ + Given the original text and the list of augmented word tokens, + construct and return a tokenized list of sentence strings. + """ + # Most of the work here is making sure that we put the right + # pieces of whitespace back in all the right places. + + # Our position in the source text, used to keep track of which + # whitespace to add: + pos = 0 + + # A regular expression that finds pieces of whitespace: + white_space_regexp = re.compile(r"\s*") + + sentence = "" + for aug_tok in tokens: + tok = aug_tok.tok + + # Find the whitespace before this token, and update pos. + white_space = white_space_regexp.match(text, pos).group() + pos += len(white_space) + + # Some of the rules used by the punkt word tokenizer + # strip whitespace out of the text, resulting in tokens + # that contain whitespace in the source text. If our + # token doesn't match, see if adding whitespace helps. + # If so, then use the version with whitespace. + if text[pos : pos + len(tok)] != tok: + pat = r"\s*".join(re.escape(c) for c in tok) + m = re.compile(pat).match(text, pos) + if m: + tok = m.group() + + # Move our position pointer to the end of the token. + assert text[pos : pos + len(tok)] == tok + pos += len(tok) + + # Add this token. If it's not at the beginning of the + # sentence, then include any whitespace that separated it + # from the previous token. + if sentence: + sentence += white_space + sentence += tok + + # If we're at a sentence break, then start a new sentence. + if aug_tok.sentbreak: + yield sentence + sentence = "" + + # If the last sentence is empty, discard it. + if sentence: + yield sentence + + # [XX] TESTING + def dump(self, tokens): + print("writing to /tmp/punkt.new...") + with open("/tmp/punkt.new", "w") as outfile: + for aug_tok in tokens: + if aug_tok.parastart: + outfile.write("\n\n") + elif aug_tok.linestart: + outfile.write("\n") + else: + outfile.write(" ") + + outfile.write(str(aug_tok)) + + # //////////////////////////////////////////////////////////// + # { Customization Variables + # //////////////////////////////////////////////////////////// + + PUNCTUATION = tuple(";:,.!?") + + # //////////////////////////////////////////////////////////// + # { Annotation Procedures + # //////////////////////////////////////////////////////////// + + def _annotate_second_pass(self, tokens): + """ + Performs a token-based classification (section 4) over the given + tokens, making use of the orthographic heuristic (4.1.1), collocation + heuristic (4.1.2) and frequent sentence starter heuristic (4.1.3). + """ + for token1, token2 in _pair_iter(tokens): + self._second_pass_annotation(token1, token2) + yield token1 + + def _second_pass_annotation(self, aug_tok1, aug_tok2): + """ + Performs token-based classification over a pair of contiguous tokens + updating the first. + """ + # Is it the last token? We can't do anything then. + if not aug_tok2: + return + + if not aug_tok1.period_final: + # We only care about words ending in periods. + return + typ = aug_tok1.type_no_period + next_typ = aug_tok2.type_no_sentperiod + tok_is_initial = aug_tok1.is_initial + + # [4.1.2. Collocation Heuristic] If there's a + # collocation between the word before and after the + # period, then label tok as an abbreviation and NOT + # a sentence break. Note that collocations with + # frequent sentence starters as their second word are + # excluded in training. + if (typ, next_typ) in self._params.collocations: + aug_tok1.sentbreak = False + aug_tok1.abbr = True + return REASON_KNOWN_COLLOCATION + + # [4.2. Token-Based Reclassification of Abbreviations] If + # the token is an abbreviation or an ellipsis, then decide + # whether we should *also* classify it as a sentbreak. + if (aug_tok1.abbr or aug_tok1.ellipsis) and (not tok_is_initial): + # [4.1.1. Orthographic Heuristic] Check if there's + # orthogrpahic evidence about whether the next word + # starts a sentence or not. + is_sent_starter = self._ortho_heuristic(aug_tok2) + if is_sent_starter == True: + aug_tok1.sentbreak = True + return REASON_ABBR_WITH_ORTHOGRAPHIC_HEURISTIC + + # [4.1.3. Frequent Sentence Starter Heruistic] If the + # next word is capitalized, and is a member of the + # frequent-sentence-starters list, then label tok as a + # sentence break. + if aug_tok2.first_upper and next_typ in self._params.sent_starters: + aug_tok1.sentbreak = True + return REASON_ABBR_WITH_SENTENCE_STARTER + + # [4.3. Token-Based Detection of Initials and Ordinals] + # Check if any initials or ordinals tokens that are marked + # as sentbreaks should be reclassified as abbreviations. + if tok_is_initial or typ == "##number##": + + # [4.1.1. Orthographic Heuristic] Check if there's + # orthogrpahic evidence about whether the next word + # starts a sentence or not. + is_sent_starter = self._ortho_heuristic(aug_tok2) + + if is_sent_starter == False: + aug_tok1.sentbreak = False + aug_tok1.abbr = True + if tok_is_initial: + return REASON_INITIAL_WITH_ORTHOGRAPHIC_HEURISTIC + return REASON_NUMBER_WITH_ORTHOGRAPHIC_HEURISTIC + + # Special heuristic for initials: if orthogrpahic + # heuristic is unknown, and next word is always + # capitalized, then mark as abbrev (eg: J. Bach). + if ( + is_sent_starter == "unknown" + and tok_is_initial + and aug_tok2.first_upper + and not (self._params.ortho_context[next_typ] & _ORTHO_LC) + ): + aug_tok1.sentbreak = False + aug_tok1.abbr = True + return REASON_INITIAL_WITH_SPECIAL_ORTHOGRAPHIC_HEURISTIC + + return + + def _ortho_heuristic(self, aug_tok): + """ + Decide whether the given token is the first token in a sentence. + """ + # Sentences don't start with punctuation marks: + if aug_tok.tok in self.PUNCTUATION: + return False + + ortho_context = self._params.ortho_context[aug_tok.type_no_sentperiod] + + # If the word is capitalized, occurs at least once with a + # lower case first letter, and never occurs with an upper case + # first letter sentence-internally, then it's a sentence starter. + if ( + aug_tok.first_upper + and (ortho_context & _ORTHO_LC) + and not (ortho_context & _ORTHO_MID_UC) + ): + return True + + # If the word is lower case, and either (a) we've seen it used + # with upper case, or (b) we've never seen it used + # sentence-initially with lower case, then it's not a sentence + # starter. + if aug_tok.first_lower and ( + (ortho_context & _ORTHO_UC) or not (ortho_context & _ORTHO_BEG_LC) + ): + return False + + # Otherwise, we're not sure. + return "unknown" +``` + +## `nltk/tokenize/punkt.py` — `function:PunktSentenceTokenizer.debug_decisions` (lines 1278-1312) + +```python + def debug_decisions(self, text): + """ + Classifies candidate periods as sentence breaks, yielding a dict for + each that may be used to understand why the decision was made. + + See format_debug_decision() to help make this output readable. + """ + + for match, decision_text in self._match_potential_end_contexts(text): + tokens = self._tokenize_words(decision_text) + tokens = list(self._annotate_first_pass(tokens)) + while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars): + tokens.pop(0) + yield { + "period_index": match.end() - 1, + "text": decision_text, + "type1": tokens[0].type, + "type2": tokens[1].type, + "type1_in_abbrs": bool(tokens[0].abbr), + "type1_is_initial": bool(tokens[0].is_initial), + "type2_is_sent_starter": tokens[1].type_no_sentperiod + in self._params.sent_starters, + "type2_ortho_heuristic": self._ortho_heuristic(tokens[1]), + "type2_ortho_contexts": set( + self._params._debug_ortho_context(tokens[1].type_no_sentperiod) + ), + "collocation": ( + tokens[0].type_no_sentperiod, + tokens[1].type_no_sentperiod, + ) + in self._params.collocations, + "reason": self._second_pass_annotation(tokens[0], tokens[1]) + or REASON_DEFAULT_DECISION, + "break_decision": tokens[0].sentbreak, + } +``` + +## `nltk/tokenize/punkt.py` — `function:PunktSentenceTokenizer._match_potential_end_contexts` (lines 1334-1391) + +```python + def _match_potential_end_contexts(self, text): + """ + Given a text, find the matches of potential sentence breaks, + alongside the contexts surrounding these sentence breaks. + + Since the fix for the ReDOS discovered in issue #2866, we no longer match + the word before a potential end of sentence token. Instead, we use a separate + regex for this. As a consequence, `finditer`'s desire to find non-overlapping + matches no longer aids us in finding the single longest match. + Where previously, we could use:: + + >>> pst = PunktSentenceTokenizer() + >>> text = "Very bad acting!!! I promise." + >>> list(pst._lang_vars.period_context_re().finditer(text)) # doctest: +SKIP + [] + + Now we have to find the word before (i.e. 'acting') separately, and `finditer` + returns:: + + >>> pst = PunktSentenceTokenizer() + >>> text = "Very bad acting!!! I promise." + >>> list(pst._lang_vars.period_context_re().finditer(text)) # doctest: +NORMALIZE_WHITESPACE + [, + , + ] + + So, we need to find the word before the match from right to left, and then manually remove + the overlaps. That is what this method does:: + + >>> pst = PunktSentenceTokenizer() + >>> text = "Very bad acting!!! I promise." + >>> pst._match_potential_end_contexts(text) + [(, 'acting!!! I')] + + :param text: String of one or more sentences + :type text: str + :return: List of match-context tuples. + :rtype: List[Tuple[re.Match, str]] + """ + before_words = {} + matches = [] + for match in reversed(list(self._lang_vars.period_context_re().finditer(text))): + # Ignore matches that have already been captured by matches to the right of this match + if matches and match.end() > before_start: + continue + # Find the word before the current match + split = text[: match.start()].rsplit(maxsplit=1) + before_start = len(split[0]) if len(split) == 2 else 0 + before_words[match] = split[-1] + matches.append(match) + + return [ + ( + match, + before_words[match] + match.group() + match.group("after_tok"), + ) + for match in matches[::-1] + ] +``` + +## `nltk/tokenize/punkt.py` — `function:PunktSentenceTokenizer._slices_from_text` (lines 1393-1405) + +```python + def _slices_from_text(self, text): + last_break = 0 + for match, context in self._match_potential_end_contexts(text): + if self.text_contains_sentbreak(context): + yield slice(last_break, match.end()) + if match.group("next_tok"): + # next sentence starts after whitespace + last_break = match.start("next_tok") + else: + # next sentence starts at following punctuation + last_break = match.end() + # The last sentence should not contain trailing whitespace. + yield slice(last_break, len(text.rstrip())) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..fb40f53fb461dcde53c35ee2716facc8c2bdacb1 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/pre_context.md @@ -0,0 +1,584 @@ +# Patch-overlapping Python context before the fix + +## `nltk/tokenize/punkt.py` — `class:PunktLanguageVars` (lines 182-294) + +```python +class PunktLanguageVars: + """ + Stores variables, mostly regular expressions, which may be + language-dependent for correct application of the algorithm. + An extension of this class may modify its properties to suit + a language other than English; an instance can then be passed + as an argument to PunktSentenceTokenizer and PunktTrainer + constructors. + """ + + __slots__ = ("_re_period_context", "_re_word_tokenizer") + + def __getstate__(self): + # All modifications to the class are performed by inheritance. + # Non-default parameters to be pickled must be defined in the inherited + # class. + return 1 + + def __setstate__(self, state): + return 1 + + sent_end_chars = (".", "?", "!") + """Characters which are candidates for sentence boundaries""" + + @property + def _re_sent_end_chars(self): + return "[%s]" % re.escape("".join(self.sent_end_chars)) + + internal_punctuation = ",:;" # might want to extend this.. + """sentence internal punctuation, which indicates an abbreviation if + preceded by a period-final token.""" + + re_boundary_realignment = re.compile(r'["\')\]}]+?(?:\s+|(?=--)|$)', re.MULTILINE) + """Used to realign punctuation that should be included in a sentence + although it follows the period (or ?, !).""" + + _re_word_start = r"[^\(\"\`{\[:;&\#\*@\)}\]\-,]" + """Excludes some characters from starting word tokens""" + + @property + def _re_non_word_chars(self): + return r"(?:[)\";}\]\*:@\'\({\[%s])" % re.escape( + "".join(set(self.sent_end_chars) - {"."}) + ) + + """Characters that cannot appear within words""" + + _re_multi_char_punct = r"(?:\-{2,}|\.{2,}|(?:\.\s){2,}\.)" + """Hyphen and ellipsis are multi-character punctuation""" + + _word_tokenize_fmt = r"""( + %(MultiChar)s + | + (?=%(WordStart)s)\S+? # Accept word characters until end is found + (?= # Sequences marking a word's end + \s| # White-space + $| # End-of-string + %(NonWord)s|%(MultiChar)s| # Punctuation + ,(?=$|\s|%(NonWord)s|%(MultiChar)s) # Comma if at end of word + ) + | + \S + )""" + """Format of a regular expression to split punctuation from words, + excluding period.""" + + def _word_tokenizer_re(self): + """Compiles and returns a regular expression for word tokenization""" + try: + return self._re_word_tokenizer + except AttributeError: + self._re_word_tokenizer = re.compile( + self._word_tokenize_fmt + % { + "NonWord": self._re_non_word_chars, + "MultiChar": self._re_multi_char_punct, + "WordStart": self._re_word_start, + }, + re.UNICODE | re.VERBOSE, + ) + return self._re_word_tokenizer + + def word_tokenize(self, s): + """Tokenize a string to split off punctuation other than periods""" + return self._word_tokenizer_re().findall(s) + + _period_context_fmt = r""" + \S* # some word material + %(SentEndChars)s # a potential sentence ending + (?=(?P + %(NonWord)s # either other punctuation + | + \s+(?P\S+) # or whitespace and some other token + ))""" + """Format of a regular expression to find contexts including possible + sentence boundaries. Matches token which the possible sentence boundary + ends, and matches the following token within a lookahead expression.""" + + def period_context_re(self): + """Compiles and returns a regular expression to find contexts + including possible sentence boundaries.""" + try: + return self._re_period_context + except: + self._re_period_context = re.compile( + self._period_context_fmt + % { + "NonWord": self._re_non_word_chars, + "SentEndChars": self._re_sent_end_chars, + }, + re.UNICODE | re.VERBOSE, + ) + return self._re_period_context +``` + +## `nltk/tokenize/punkt.py` — `class:PunktSentenceTokenizer` (lines 1236-1635) + +```python +class PunktSentenceTokenizer(PunktBaseClass, TokenizerI): + """ + A sentence tokenizer which uses an unsupervised algorithm to build + a model for abbreviation words, collocations, and words that start + sentences; and then uses that model to find sentence boundaries. + This approach has been shown to work well for many European + languages. + """ + + def __init__( + self, train_text=None, verbose=False, lang_vars=None, token_cls=PunktToken + ): + """ + train_text can either be the sole training text for this sentence + boundary detector, or can be a PunktParameters object. + """ + PunktBaseClass.__init__(self, lang_vars=lang_vars, token_cls=token_cls) + + if train_text: + self._params = self.train(train_text, verbose) + + def train(self, train_text, verbose=False): + """ + Derives parameters from a given training text, or uses the parameters + given. Repeated calls to this method destroy previous parameters. For + incremental training, instantiate a separate PunktTrainer instance. + """ + if not isinstance(train_text, str): + return train_text + return PunktTrainer( + train_text, lang_vars=self._lang_vars, token_cls=self._Token + ).get_params() + + # //////////////////////////////////////////////////////////// + # { Tokenization + # //////////////////////////////////////////////////////////// + + def tokenize(self, text, realign_boundaries=True): + """ + Given a text, returns a list of the sentences in that text. + """ + return list(self.sentences_from_text(text, realign_boundaries)) + + def debug_decisions(self, text): + """ + Classifies candidate periods as sentence breaks, yielding a dict for + each that may be used to understand why the decision was made. + + See format_debug_decision() to help make this output readable. + """ + + for match in self._lang_vars.period_context_re().finditer(text): + decision_text = match.group() + match.group("after_tok") + tokens = self._tokenize_words(decision_text) + tokens = list(self._annotate_first_pass(tokens)) + while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars): + tokens.pop(0) + yield { + "period_index": match.end() - 1, + "text": decision_text, + "type1": tokens[0].type, + "type2": tokens[1].type, + "type1_in_abbrs": bool(tokens[0].abbr), + "type1_is_initial": bool(tokens[0].is_initial), + "type2_is_sent_starter": tokens[1].type_no_sentperiod + in self._params.sent_starters, + "type2_ortho_heuristic": self._ortho_heuristic(tokens[1]), + "type2_ortho_contexts": set( + self._params._debug_ortho_context(tokens[1].type_no_sentperiod) + ), + "collocation": ( + tokens[0].type_no_sentperiod, + tokens[1].type_no_sentperiod, + ) + in self._params.collocations, + "reason": self._second_pass_annotation(tokens[0], tokens[1]) + or REASON_DEFAULT_DECISION, + "break_decision": tokens[0].sentbreak, + } + + def span_tokenize(self, text, realign_boundaries=True): + """ + Given a text, generates (start, end) spans of sentences + in the text. + """ + slices = self._slices_from_text(text) + if realign_boundaries: + slices = self._realign_boundaries(text, slices) + for sentence in slices: + yield (sentence.start, sentence.stop) + + def sentences_from_text(self, text, realign_boundaries=True): + """ + Given a text, generates the sentences in that text by only + testing candidate sentence breaks. If realign_boundaries is + True, includes in the sentence closing punctuation that + follows the period. + """ + return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] + + def _slices_from_text(self, text): + last_break = 0 + for match in self._lang_vars.period_context_re().finditer(text): + context = match.group() + match.group("after_tok") + if self.text_contains_sentbreak(context): + yield slice(last_break, match.end()) + if match.group("next_tok"): + # next sentence starts after whitespace + last_break = match.start("next_tok") + else: + # next sentence starts at following punctuation + last_break = match.end() + # The last sentence should not contain trailing whitespace. + yield slice(last_break, len(text.rstrip())) + + def _realign_boundaries(self, text, slices): + """ + Attempts to realign punctuation that falls after the period but + should otherwise be included in the same sentence. + + For example: "(Sent1.) Sent2." will otherwise be split as:: + + ["(Sent1.", ") Sent1."]. + + This method will produce:: + + ["(Sent1.)", "Sent2."]. + """ + realign = 0 + for sentence1, sentence2 in _pair_iter(slices): + sentence1 = slice(sentence1.start + realign, sentence1.stop) + if not sentence2: + if text[sentence1]: + yield sentence1 + continue + + m = self._lang_vars.re_boundary_realignment.match(text[sentence2]) + if m: + yield slice(sentence1.start, sentence2.start + len(m.group(0).rstrip())) + realign = m.end() + else: + realign = 0 + if text[sentence1]: + yield sentence1 + + def text_contains_sentbreak(self, text): + """ + Returns True if the given text includes a sentence break. + """ + found = False # used to ignore last token + for tok in self._annotate_tokens(self._tokenize_words(text)): + if found: + return True + if tok.sentbreak: + found = True + return False + + def sentences_from_text_legacy(self, text): + """ + Given a text, generates the sentences in that text. Annotates all + tokens, rather than just those with possible sentence breaks. Should + produce the same results as ``sentences_from_text``. + """ + tokens = self._annotate_tokens(self._tokenize_words(text)) + return self._build_sentence_list(text, tokens) + + def sentences_from_tokens(self, tokens): + """ + Given a sequence of tokens, generates lists of tokens, each list + corresponding to a sentence. + """ + tokens = iter(self._annotate_tokens(self._Token(t) for t in tokens)) + sentence = [] + for aug_tok in tokens: + sentence.append(aug_tok.tok) + if aug_tok.sentbreak: + yield sentence + sentence = [] + if sentence: + yield sentence + + def _annotate_tokens(self, tokens): + """ + Given a set of tokens augmented with markers for line-start and + paragraph-start, returns an iterator through those tokens with full + annotation including predicted sentence breaks. + """ + # Make a preliminary pass through the document, marking likely + # sentence breaks, abbreviations, and ellipsis tokens. + tokens = self._annotate_first_pass(tokens) + + # Make a second pass through the document, using token context + # information to change our preliminary decisions about where + # sentence breaks, abbreviations, and ellipsis occurs. + tokens = self._annotate_second_pass(tokens) + + ## [XX] TESTING + # tokens = list(tokens) + # self.dump(tokens) + + return tokens + + def _build_sentence_list(self, text, tokens): + """ + Given the original text and the list of augmented word tokens, + construct and return a tokenized list of sentence strings. + """ + # Most of the work here is making sure that we put the right + # pieces of whitespace back in all the right places. + + # Our position in the source text, used to keep track of which + # whitespace to add: + pos = 0 + + # A regular expression that finds pieces of whitespace: + white_space_regexp = re.compile(r"\s*") + + sentence = "" + for aug_tok in tokens: + tok = aug_tok.tok + + # Find the whitespace before this token, and update pos. + white_space = white_space_regexp.match(text, pos).group() + pos += len(white_space) + + # Some of the rules used by the punkt word tokenizer + # strip whitespace out of the text, resulting in tokens + # that contain whitespace in the source text. If our + # token doesn't match, see if adding whitespace helps. + # If so, then use the version with whitespace. + if text[pos : pos + len(tok)] != tok: + pat = r"\s*".join(re.escape(c) for c in tok) + m = re.compile(pat).match(text, pos) + if m: + tok = m.group() + + # Move our position pointer to the end of the token. + assert text[pos : pos + len(tok)] == tok + pos += len(tok) + + # Add this token. If it's not at the beginning of the + # sentence, then include any whitespace that separated it + # from the previous token. + if sentence: + sentence += white_space + sentence += tok + + # If we're at a sentence break, then start a new sentence. + if aug_tok.sentbreak: + yield sentence + sentence = "" + + # If the last sentence is empty, discard it. + if sentence: + yield sentence + + # [XX] TESTING + def dump(self, tokens): + print("writing to /tmp/punkt.new...") + with open("/tmp/punkt.new", "w") as outfile: + for aug_tok in tokens: + if aug_tok.parastart: + outfile.write("\n\n") + elif aug_tok.linestart: + outfile.write("\n") + else: + outfile.write(" ") + + outfile.write(str(aug_tok)) + + # //////////////////////////////////////////////////////////// + # { Customization Variables + # //////////////////////////////////////////////////////////// + + PUNCTUATION = tuple(";:,.!?") + + # //////////////////////////////////////////////////////////// + # { Annotation Procedures + # //////////////////////////////////////////////////////////// + + def _annotate_second_pass(self, tokens): + """ + Performs a token-based classification (section 4) over the given + tokens, making use of the orthographic heuristic (4.1.1), collocation + heuristic (4.1.2) and frequent sentence starter heuristic (4.1.3). + """ + for token1, token2 in _pair_iter(tokens): + self._second_pass_annotation(token1, token2) + yield token1 + + def _second_pass_annotation(self, aug_tok1, aug_tok2): + """ + Performs token-based classification over a pair of contiguous tokens + updating the first. + """ + # Is it the last token? We can't do anything then. + if not aug_tok2: + return + + if not aug_tok1.period_final: + # We only care about words ending in periods. + return + typ = aug_tok1.type_no_period + next_typ = aug_tok2.type_no_sentperiod + tok_is_initial = aug_tok1.is_initial + + # [4.1.2. Collocation Heuristic] If there's a + # collocation between the word before and after the + # period, then label tok as an abbreviation and NOT + # a sentence break. Note that collocations with + # frequent sentence starters as their second word are + # excluded in training. + if (typ, next_typ) in self._params.collocations: + aug_tok1.sentbreak = False + aug_tok1.abbr = True + return REASON_KNOWN_COLLOCATION + + # [4.2. Token-Based Reclassification of Abbreviations] If + # the token is an abbreviation or an ellipsis, then decide + # whether we should *also* classify it as a sentbreak. + if (aug_tok1.abbr or aug_tok1.ellipsis) and (not tok_is_initial): + # [4.1.1. Orthographic Heuristic] Check if there's + # orthogrpahic evidence about whether the next word + # starts a sentence or not. + is_sent_starter = self._ortho_heuristic(aug_tok2) + if is_sent_starter == True: + aug_tok1.sentbreak = True + return REASON_ABBR_WITH_ORTHOGRAPHIC_HEURISTIC + + # [4.1.3. Frequent Sentence Starter Heruistic] If the + # next word is capitalized, and is a member of the + # frequent-sentence-starters list, then label tok as a + # sentence break. + if aug_tok2.first_upper and next_typ in self._params.sent_starters: + aug_tok1.sentbreak = True + return REASON_ABBR_WITH_SENTENCE_STARTER + + # [4.3. Token-Based Detection of Initials and Ordinals] + # Check if any initials or ordinals tokens that are marked + # as sentbreaks should be reclassified as abbreviations. + if tok_is_initial or typ == "##number##": + + # [4.1.1. Orthographic Heuristic] Check if there's + # orthogrpahic evidence about whether the next word + # starts a sentence or not. + is_sent_starter = self._ortho_heuristic(aug_tok2) + + if is_sent_starter == False: + aug_tok1.sentbreak = False + aug_tok1.abbr = True + if tok_is_initial: + return REASON_INITIAL_WITH_ORTHOGRAPHIC_HEURISTIC + return REASON_NUMBER_WITH_ORTHOGRAPHIC_HEURISTIC + + # Special heuristic for initials: if orthogrpahic + # heuristic is unknown, and next word is always + # capitalized, then mark as abbrev (eg: J. Bach). + if ( + is_sent_starter == "unknown" + and tok_is_initial + and aug_tok2.first_upper + and not (self._params.ortho_context[next_typ] & _ORTHO_LC) + ): + aug_tok1.sentbreak = False + aug_tok1.abbr = True + return REASON_INITIAL_WITH_SPECIAL_ORTHOGRAPHIC_HEURISTIC + + return + + def _ortho_heuristic(self, aug_tok): + """ + Decide whether the given token is the first token in a sentence. + """ + # Sentences don't start with punctuation marks: + if aug_tok.tok in self.PUNCTUATION: + return False + + ortho_context = self._params.ortho_context[aug_tok.type_no_sentperiod] + + # If the word is capitalized, occurs at least once with a + # lower case first letter, and never occurs with an upper case + # first letter sentence-internally, then it's a sentence starter. + if ( + aug_tok.first_upper + and (ortho_context & _ORTHO_LC) + and not (ortho_context & _ORTHO_MID_UC) + ): + return True + + # If the word is lower case, and either (a) we've seen it used + # with upper case, or (b) we've never seen it used + # sentence-initially with lower case, then it's not a sentence + # starter. + if aug_tok.first_lower and ( + (ortho_context & _ORTHO_UC) or not (ortho_context & _ORTHO_BEG_LC) + ): + return False + + # Otherwise, we're not sure. + return "unknown" +``` + +## `nltk/tokenize/punkt.py` — `function:PunktSentenceTokenizer.debug_decisions` (lines 1279-1314) + +```python + def debug_decisions(self, text): + """ + Classifies candidate periods as sentence breaks, yielding a dict for + each that may be used to understand why the decision was made. + + See format_debug_decision() to help make this output readable. + """ + + for match in self._lang_vars.period_context_re().finditer(text): + decision_text = match.group() + match.group("after_tok") + tokens = self._tokenize_words(decision_text) + tokens = list(self._annotate_first_pass(tokens)) + while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars): + tokens.pop(0) + yield { + "period_index": match.end() - 1, + "text": decision_text, + "type1": tokens[0].type, + "type2": tokens[1].type, + "type1_in_abbrs": bool(tokens[0].abbr), + "type1_is_initial": bool(tokens[0].is_initial), + "type2_is_sent_starter": tokens[1].type_no_sentperiod + in self._params.sent_starters, + "type2_ortho_heuristic": self._ortho_heuristic(tokens[1]), + "type2_ortho_contexts": set( + self._params._debug_ortho_context(tokens[1].type_no_sentperiod) + ), + "collocation": ( + tokens[0].type_no_sentperiod, + tokens[1].type_no_sentperiod, + ) + in self._params.collocations, + "reason": self._second_pass_annotation(tokens[0], tokens[1]) + or REASON_DEFAULT_DECISION, + "break_decision": tokens[0].sentbreak, + } +``` + +## `nltk/tokenize/punkt.py` — `function:PunktSentenceTokenizer._slices_from_text` (lines 1336-1349) + +```python + def _slices_from_text(self, text): + last_break = 0 + for match in self._lang_vars.period_context_re().finditer(text): + context = match.group() + match.group("after_tok") + if self.text_contains_sentbreak(context): + yield slice(last_break, match.end()) + if match.group("next_tok"): + # next sentence starts after whitespace + last_break = match.start("next_tok") + else: + # next sentence starts at following punctuation + last_break = match.end() + # The last sentence should not contain trailing whitespace. + yield slice(last_break, len(text.rstrip())) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5bf1c5d333ca7c4082772e1ebcfdab21049bb732 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-c4ca067f7fd871d25376", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-c4ca067f7fd871d25376", + "project_id": "pyvul__nltk__nltk", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "nltk/tokenize/punkt.py" + ], + "patch_units": { + "before": [ + "class:PunktLanguageVars", + "class:PunktSentenceTokenizer", + "function:PunktSentenceTokenizer.debug_decisions", + "function:PunktSentenceTokenizer._slices_from_text" + ], + "after": [ + "class:PunktLanguageVars", + "class:PunktSentenceTokenizer", + "function:PunktSentenceTokenizer.debug_decisions", + "function:PunktSentenceTokenizer._match_potential_end_contexts", + "function:PunktSentenceTokenizer._slices_from_text" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/9901612cc127b3c906d04b484c87fd01474c1f5e7b9a4e0d91eb5ae3e3a77bb6/database", + "cache_key": "9901612cc127b3c906d04b484c87fd01474c1f5e7b9a4e0d91eb5ae3e3a77bb6", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/1253f8fc7c8d63a799f044ff9b3b36fa32e8f781c7ed2ed5205970fc469d7db8/database", + "cache_key": "1253f8fc7c8d63a799f044ff9b3b36fa32e8f781c7ed2ed5205970fc469d7db8", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/21d7eb9a5eb34814a348edb20d658a2784a90c48b02f7325f0b22d3e91b3f5eb/database", + "cache_key": "21d7eb9a5eb34814a348edb20d658a2784a90c48b02f7325f0b22d3e91b3f5eb", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-c4ca067f7fd871d25376/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-c4ca067f7fd871d25376/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c4ca067f7fd871d25376/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bf263b4d86ff2085e01d768a0f6014d91f1494b8 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/patch.diff @@ -0,0 +1,13 @@ +diff --git a/src/transformers/utils/hub.py b/src/transformers/utils/hub.py +index 58aac59d24..335547f2b8 100644 +--- a/src/transformers/utils/hub.py ++++ b/src/transformers/utils/hub.py +@@ -578,7 +578,7 @@ def download_url(url, proxies=None): + " that this is not compatible with the caching system (your file will be downloaded at each execution) or" + " multiple processes (each process will download the file in a different temporary file)." + ) +- tmp_file = tempfile.mktemp() ++ tmp_file = tempfile.mkstemp()[1] + with open(tmp_file, "wb") as f: + http_get(url, f, proxies=proxies) + return tmp_file diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..773f7006e617866156179a34e56a29cb7678e983 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/post_context.md @@ -0,0 +1,30 @@ +# Patch-overlapping Python context after the fix + +## `src/transformers/utils/hub.py` — `function:download_url` (lines 561-584) + +```python +def download_url(url, proxies=None): + """ + Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is + for deprecated behavior allowing to download config/models with a single url instead of using the Hub. + + Args: + url (`str`): The url of the file to download. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + + Returns: + `str`: The location of the temporary file where the url was downloaded. + """ + warnings.warn( + f"Using `from_pretrained` with the url of a file (here {url}) is deprecated and won't be possible anymore in" + " v5 of Transformers. You should host your file on the Hub (hf.co) instead and use the repository ID. Note" + " that this is not compatible with the caching system (your file will be downloaded at each execution) or" + " multiple processes (each process will download the file in a different temporary file)." + ) + tmp_file = tempfile.mkstemp()[1] + with open(tmp_file, "wb") as f: + http_get(url, f, proxies=proxies) + return tmp_file +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..bdfb057be36129dedc90080d4f48e8e260c6432a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/pre_context.md @@ -0,0 +1,30 @@ +# Patch-overlapping Python context before the fix + +## `src/transformers/utils/hub.py` — `function:download_url` (lines 561-584) + +```python +def download_url(url, proxies=None): + """ + Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is + for deprecated behavior allowing to download config/models with a single url instead of using the Hub. + + Args: + url (`str`): The url of the file to download. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + + Returns: + `str`: The location of the temporary file where the url was downloaded. + """ + warnings.warn( + f"Using `from_pretrained` with the url of a file (here {url}) is deprecated and won't be possible anymore in" + " v5 of Transformers. You should host your file on the Hub (hf.co) instead and use the repository ID. Note" + " that this is not compatible with the caching system (your file will be downloaded at each execution) or" + " multiple processes (each process will download the file in a different temporary file)." + ) + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get(url, f, proxies=proxies) + return tmp_file +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9ca3a06cfdfb678bccb72b243bf351b6f44f9990 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/task.json @@ -0,0 +1,44 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-c52f0447bb0aa65cf9a4", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-c52f0447bb0aa65cf9a4", + "project_id": "pyvul__huggingface__transformers", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "src/transformers/utils/hub.py" + ], + "patch_units": { + "before": [ + "function:download_url" + ], + "after": [ + "function:download_url" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/81cf494d65a4193983b2e8ae4deeb3826fb74dd695cda772cae37072631bb968/database", + "cache_key": "81cf494d65a4193983b2e8ae4deeb3826fb74dd695cda772cae37072631bb968", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/ce3a3e419c116565aeabc5c1e6797392b9dd51353579091d3bc0307d5e30b70b/database", + "cache_key": "ce3a3e419c116565aeabc5c1e6797392b9dd51353579091d3bc0307d5e30b70b", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/0f697ed6bf748d0fb4d12d6aaef902c635a128d02d15997015bd35c0903dff85/database", + "cache_key": "0f697ed6bf748d0fb4d12d6aaef902c635a128d02d15997015bd35c0903dff85", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-c52f0447bb0aa65cf9a4/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-c52f0447bb0aa65cf9a4/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-c52f0447bb0aa65cf9a4/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..11a0bacdc2e564b8a031e19864dac8a54cacb930 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/patch.diff @@ -0,0 +1,152 @@ +diff --git a/README.md b/README.md +index 8d357d64..a4294793 100644 +--- a/README.md ++++ b/README.md +@@ -115,6 +115,7 @@ Professional support for Rdiffweb is available by contacting [IKUS Soft](https:/ + * Sent email notification to user when a new SSH Key get added - credit to [Nehal Pillai](https://www.linkedin.com/in/nehal-pillai-02a854172) + * Ratelimit "Resend code to my email" in Two-Factor Authentication view - credit to [Nehal Pillai](https://www.linkedin.com/in/nehal-pillai-02a854172) + * Username are not case-insensitive - credits to [raiders0786](https://www.linkedin.com/in/chirag-agrawal-770488144/) ++* Make sure that all ssh keys are unique, regardless of the user - credit to [Nehal Pillai](https://www.linkedin.com/in/nehal-pillai-02a854172) + + Breaking changes: + +diff --git a/rdiffweb/core/model/__init__.py b/rdiffweb/core/model/__init__.py +index df13f84c..1c7e3636 100644 +--- a/rdiffweb/core/model/__init__.py ++++ b/rdiffweb/core/model/__init__.py +@@ -19,12 +19,12 @@ import logging + import sys + + import cherrypy +-from sqlalchemy import event ++from sqlalchemy import event, func + from sqlalchemy.exc import IntegrityError + + from ._repo import RepoObject # noqa + from ._session import DbSession, SessionObject # noqa +-from ._sshkey import SshKey # noqa ++from ._sshkey import SshKey, sshkey_fingerprint_index # noqa + from ._token import Token # noqa + from ._user import DuplicateSSHKeyError, UserObject, user_username_index # noqa + +@@ -137,3 +137,22 @@ def db_after_create(target, connection, **kw): + logger.error(msg) + print(msg, file=sys.stderr) + raise SystemExit(12) ++ ++ # Fix SSH Key uniqueness - since 2.5.4 ++ if not _index_exists(connection, 'sshkey_fingerprint_index'): ++ duplicate_sshkeys = ( ++ SshKey.query.with_entities(SshKey.fingerprint) ++ .group_by(SshKey.fingerprint) ++ .having(func.count(SshKey.fingerprint) > 1) ++ ).all() ++ try: ++ sshkey_fingerprint_index.create() ++ except IntegrityError: ++ msg = ( ++ 'Failure to upgrade your database to make SSH Keys unique. ' ++ 'You must downgrade and deleted duplicate SSH Keys. ' ++ '%s' % '\n'.join([str(k) for k in duplicate_sshkeys]), ++ ) ++ logger.error(msg) ++ print(msg, file=sys.stderr) ++ raise SystemExit(12) +diff --git a/rdiffweb/core/model/_sshkey.py b/rdiffweb/core/model/_sshkey.py +index 38421943..48b671b8 100644 +--- a/rdiffweb/core/model/_sshkey.py ++++ b/rdiffweb/core/model/_sshkey.py +@@ -16,7 +16,7 @@ + # along with this program. If not, see . + + import cherrypy +-from sqlalchemy import Column, Integer, Text ++from sqlalchemy import Column, Index, Integer, Text + + Base = cherrypy.tools.db.get_base() + +@@ -27,3 +27,7 @@ class SshKey(Base): + fingerprint = Column('Fingerprint', Text) + key = Column('Key', Text, unique=True, primary_key=True) + userid = Column('UserID', Integer, nullable=False) ++ ++ ++# Make finger print unique ++sshkey_fingerprint_index = Index('sshkey_fingerprint_index', SshKey.fingerprint, unique=True) +diff --git a/rdiffweb/core/model/_user.py b/rdiffweb/core/model/_user.py +index 9b06363c..a448aac3 100644 +--- a/rdiffweb/core/model/_user.py ++++ b/rdiffweb/core/model/_user.py +@@ -159,7 +159,7 @@ class UserObject(Base): + assert key + key = authorizedkeys.check_publickey(key) + +- # Remove option, replace comments. ++ # Remove option & Remove comment for SQL storage + key = authorizedkeys.AuthorizedKey( + options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment + ) +@@ -176,7 +176,8 @@ class UserObject(Base): + # Also look in database. + logger.info("add key [%s] to [%s] database", key, self.username) + try: +- SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()).add().flush() ++ sshkey = SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()) ++ sshkey.add().flush() + except IntegrityError: + raise DuplicateSSHKeyError( + _("Duplicate key. This key already exists or is associated to another user.") +diff --git a/rdiffweb/core/model/tests/test_user.py b/rdiffweb/core/model/tests/test_user.py +index 569ac52a..401d5de3 100644 +--- a/rdiffweb/core/model/tests/test_user.py ++++ b/rdiffweb/core/model/tests/test_user.py +@@ -325,15 +325,47 @@ class UserObjectTest(rdiffweb.test.WebCase): + def test_add_authorizedkey_duplicate(self): + # Read the pub key + key = self._read_ssh_key() +- # Add the key to the user ++ # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() +- # Add the same key ++ ++ # When adding the same identical key. ++ # Then an error is raised + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key) + userobj.commit() + ++ def test_add_authorizedkey_duplicate_new_comment(self): ++ # Read the pub key ++ key = self._read_ssh_key() ++ # Given a user with a SSH Key ++ userobj = UserObject.get_user(self.USERNAME) ++ userobj.add_authorizedkey(key) ++ userobj.commit() ++ ++ # When adding the same key with a different comment ++ # Then an error is raised ++ with self.assertRaises(DuplicateSSHKeyError): ++ userobj.add_authorizedkey(key, comment="new comment") ++ userobj.commit() ++ ++ def test_add_authorizedkey_duplicate_new_user(self): ++ # Read the pub key ++ key = self._read_ssh_key() ++ # Given a user with a SSH Key ++ userobj = UserObject.get_user(self.USERNAME) ++ userobj.add_authorizedkey(key) ++ userobj.commit() ++ ++ # When adding the same key to a different user ++ # Then an error is raised ++ newuser = UserObject.add_user("newuser") ++ newuser.commit() ++ with self.assertRaises(DuplicateSSHKeyError): ++ newuser.add_authorizedkey(key, comment="new comment") ++ newuser.commit() ++ + def test_add_authorizedkey_with_file(self): + """ + Add an ssh key for a user with an authorizedkey file. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..fe0979c21f769a4202ab29e585f48e84608f1604 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/post_context.md @@ -0,0 +1,1050 @@ +# Patch-overlapping Python context after the fix + +## `rdiffweb/core/model/__init__.py` — `function:db_after_create` (lines 70-158) + +```python +def db_after_create(target, connection, **kw): + """ + Called on database creation to update database schema. + """ + + if getattr(connection, '_transaction', None): + connection._transaction.commit() + + # Add repo's Encoding + _column_add(connection, RepoObject.__table__.c.Encoding) + _column_add(connection, RepoObject.__table__.c.keepdays) + + # Create column for roles using "isadmin" column. Keep the + # original column in case we need to revert to previous version. + if not _column_exists(connection, UserObject.__table__.c.role): + _column_add(connection, UserObject.__table__.c.role) + UserObject.query.filter(UserObject._is_admin == 1).update({UserObject.role: UserObject.ADMIN_ROLE}) + + # Add user's fullname column + _column_add(connection, UserObject.__table__.c.fullname) + + # Add user's mfa column + _column_add(connection, UserObject.__table__.c.mfa) + + # Re-create session table if Number column is missing + if not _column_exists(connection, SessionObject.__table__.c.Number): + SessionObject.__table__.drop() + SessionObject.__table__.create() + + if getattr(connection, '_transaction', None): + connection._transaction.commit() + + # Remove preceding and leading slash (/) generated by previous + # versions. Also rename '.' to '' + result = RepoObject.query.all() + for row in result: + if row.repopath.startswith('/') or row.repopath.endswith('/'): + row.repopath = row.repopath.strip('/') + row.commit() + if row.repopath == '.': + row.repopath = '' + row.commit() + # Remove duplicates and nested repositories. + result = RepoObject.query.order_by(RepoObject.userid, RepoObject.repopath).all() + prev_repo = (None, None) + for row in result: + if prev_repo[0] == row.userid and (prev_repo[1] == row.repopath or row.repopath.startswith(prev_repo[1] + '/')): + row.delete() + else: + prev_repo = (row.userid, row.repopath) + + # Fix username case insensitive unique + if not _index_exists(connection, 'user_username_index'): + duplicate_users = ( + UserObject.query.with_entities(func.lower(UserObject.username)) + .group_by(func.lower(UserObject.username)) + .having(func.count(UserObject.username) > 1) + ).all() + try: + user_username_index.create() + except IntegrityError: + msg = ( + 'Failure to upgrade your database to make Username case insensitive. ' + 'You must downgrade and deleted duplicate Username. ' + '%s' % '\n'.join([str(k) for k in duplicate_users]), + ) + logger.error(msg) + print(msg, file=sys.stderr) + raise SystemExit(12) + + # Fix SSH Key uniqueness - since 2.5.4 + if not _index_exists(connection, 'sshkey_fingerprint_index'): + duplicate_sshkeys = ( + SshKey.query.with_entities(SshKey.fingerprint) + .group_by(SshKey.fingerprint) + .having(func.count(SshKey.fingerprint) > 1) + ).all() + try: + sshkey_fingerprint_index.create() + except IntegrityError: + msg = ( + 'Failure to upgrade your database to make SSH Keys unique. ' + 'You must downgrade and deleted duplicate SSH Keys. ' + '%s' % '\n'.join([str(k) for k in duplicate_sshkeys]), + ) + logger.error(msg) + print(msg, file=sys.stderr) + raise SystemExit(12) +``` + +## `rdiffweb/core/model/__init__.py` — `module:@22` (lines 22-22) + +```python +from sqlalchemy import event, func +``` + +## `rdiffweb/core/model/__init__.py` — `module:@27` (lines 27-27) + +```python +from ._sshkey import SshKey, sshkey_fingerprint_index # noqa +``` + +## `rdiffweb/core/model/_sshkey.py` — `module:@19` (lines 19-19) + +```python +from sqlalchemy import Column, Index, Integer, Text +``` + +## `rdiffweb/core/model/_sshkey.py` — `module:@33` (lines 33-33) + +```python +sshkey_fingerprint_index = Index('sshkey_fingerprint_index', SshKey.fingerprint, unique=True) +``` + +## `rdiffweb/core/model/_user.py` — `class:UserObject` (lines 54-414) + +```python +class UserObject(Base): + __tablename__ = 'users' + __table_args__ = {'sqlite_autoincrement': True} + + # Value for role. + ADMIN_ROLE = 0 + MAINTAINER_ROLE = 5 + USER_ROLE = 10 + ROLES = { + 'admin': ADMIN_ROLE, + 'maintainer': MAINTAINER_ROLE, + 'user': USER_ROLE, + } + # Value for mfa field + DISABLED_MFA = 0 + ENABLED_MFA = 1 + + # Regex pattern to be used for validation. + PATTERN_EMAIL = r"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" + PATTERN_FULLNAME = r"""[^!"#$%&()*+,./:;<=>?@[\]_{|}~]+$""" + PATTERN_USERNAME = r"[a-zA-Z0-9_.\-]+$" + + userid = Column('UserID', Integer, primary_key=True) + username = Column('Username', String, nullable=False) + hash_password = Column('Password', String, nullable=False, default="") + user_root = Column('UserRoot', String, nullable=False, default="") + _is_admin = deferred( + Column( + 'IsAdmin', + SmallInteger, + nullable=False, + server_default="0", + doc="DEPRECATED This column is replaced by 'role'", + ) + ) + email = Column('UserEmail', String, nullable=False, default="") + restore_format = deferred( + Column( + 'RestoreFormat', + SmallInteger, + nullable=False, + server_default="1", + doc="DEPRECATED This column is not used anymore", + ) + ) + role = Column('role', SmallInteger, nullable=False, server_default=str(USER_ROLE), default=USER_ROLE) + fullname = Column('fullname', String, nullable=False, default="") + mfa = Column('mfa', SmallInteger, nullable=False, default=DISABLED_MFA) + repo_objs = relationship( + 'RepoObject', + foreign_keys='UserObject.userid', + primaryjoin='UserObject.userid == RepoObject.userid', + uselist=True, + lazy=True, + order_by=lambda: RepoObject.repopath, + ) + + @classmethod + def get_user(cls, user): + """Return a user object with username case-insensitive""" + return UserObject.query.filter(func.lower(UserObject.username) == user.lower()).first() + + @classmethod + def create_admin_user(cls, default_username, default_password): + # Check if admin user exists. If not, created it. + userobj = UserObject.get_user(default_username) + if not userobj: + userobj = cls.add_user(default_username, role=UserObject.ADMIN_ROLE, user_root='/backups') + userobj.hash_password = hash_password('admin123') + # Also make sure to update the password with latest value from config file. + if default_password: + if default_password.startswith('{SSHA}') or default_password.startswith('$argon2'): + userobj.hash_password = default_password + else: + userobj.hash_password = hash_password(default_password) + userobj.add() + return userobj + + @classmethod + def add_user(cls, username, password=None, role=USER_ROLE, **attrs): + """ + Used to add a new user with an optional password. + """ + assert password is None or isinstance(password, str) + # Check if user already exists. + if UserObject.get_user(username): + raise ValueError(_("User %s already exists." % (username,))) + + # Find a database where to add the user + logger.info("adding new user [%s]", username) + userobj = UserObject( + username=username, + hash_password=hash_password(password) if password else '', + role=role, + **attrs, + ).add() + # Return user object + return userobj + + def add_authorizedkey(self, key, comment=None): + """ + Add the given key to the user. Adding the key to his `authorized_keys` + file if it exists and adding it to database. + """ + # Parse and validate ssh key + assert key + key = authorizedkeys.check_publickey(key) + + # Remove option & Remove comment for SQL storage + key = authorizedkeys.AuthorizedKey( + options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment + ) + + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + with open(filename, mode="r+", encoding='utf-8') as fh: + if authorizedkeys.exists(fh, key): + raise DuplicateSSHKeyError(_("SSH key already exists")) + logger.info("add key [%s] to [%s] authorized_keys", key, self.username) + authorizedkeys.add(fh, key) + else: + # Also look in database. + logger.info("add key [%s] to [%s] database", key, self.username) + try: + sshkey = SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()) + sshkey.add().flush() + except IntegrityError: + raise DuplicateSSHKeyError( + _("Duplicate key. This key already exists or is associated to another user.") + ) + cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True}) + cherrypy.engine.publish('authorizedkey_added', self, fingerprint=key.fingerprint, comment=comment) + + def add_access_token(self, name, expiration_time=None, length=16): + """ + Create a new access token. Return the un-encrypted value of the token. + """ + assert name + assert length >= 8 + # Generate a random token + token = ''.join(secrets.choice(string.ascii_lowercase) for i in range(length)) + # Store hash token + try: + Token( + userid=self.userid, name=name, hash_token=hash_password(token), expiration_time=expiration_time + ).add().flush() + except IntegrityError: + raise ValueError(_("Duplicate token name: %s") % name) + cherrypy.engine.publish('access_token_added', self, name) + return token + + def valid_user_root(self): + """ + Check if the current user_root is valid and readable + """ + try: + return os.access(self.user_root, os.F_OK) and os.path.isdir(self.user_root) + except Exception: + return False + + def delete(self, *args, **kwargs): + cfg = cherrypy.tree.apps[''].cfg + if self.username == cfg.admin_user: + raise ValueError(_("can't delete admin user")) + # FIXME This should be deleted by cascade + SshKey.query.filter(SshKey.userid == self.userid).delete() + RepoObject.query.filter(RepoObject.userid == self.userid).delete() + Token.query.filter(Token.userid == self.userid).delete() + # Delete ourself + return Base.delete(self) + + def delete_authorizedkey(self, fingerprint): + """ + Remove the given key from the user. Remove the key from his + `authorized_keys` file if it exists and from database database. + """ + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + with open(filename, mode='r+', encoding='utf-8') as fh: + logger.info("removing key [%s] from [%s] authorized_keys", fingerprint, self.username) + authorizedkeys.remove(fh, fingerprint) + else: + # Also look in database. + logger.info("removing key [%s] from [%s] database", fingerprint, self.username) + SshKey.query.filter(and_(SshKey.userid == self.userid, SshKey.fingerprint == fingerprint)).delete() + cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True}) + + def delete_access_token(self, name): + assert name + if not Token.query.filter(Token.userid == self.userid, Token.name == name).delete(): + raise ValueError(_("token name doesn't exists: %s") % name) + + @property + def disk_usage(self): + # Skip if user_root is invalid. + if not self.user_root or not os.path.exists(self.user_root): + return 0 + values = cherrypy.engine.publish('get_disk_usage', self) + # Return the first not None value + return next((v for v in values if v is not None), 0) + + @property + def disk_quota(self): + # Skip if user_root is invalid. + if not self.user_root or not os.path.exists(self.user_root): + return 0 + values = cherrypy.engine.publish('get_disk_quota', self) + # Return the first not None value + return next((v for v in values if v is not None), 0) + + @disk_quota.setter + def disk_quota(self, value): + # Skip if user_root is invalid. + if not self.user_root or not os.path.exists(self.user_root): + return + cherrypy.engine.publish('set_disk_quota', self, value) + + @property + def authorizedkeys(self): + """ + Return an iterator on the authorized key. Either from his + `authorized_keys` file if it exists or from database. + """ + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + for k in authorizedkeys.read(filename): + yield k + + # Also look in database. + for record in SshKey.query.filter(SshKey.userid == self.userid).all(): + yield authorizedkeys.check_publickey(record.key) + + def refresh_repos(self, delete=False): + """ + Return list of repositories object to reflect the filesystem folders. + + Return a RepoObject for each sub directories under `user_root` with `rdiff-backup-data`. + """ + # Update the repositories by walking in the directory tree. + def _onerror(unused): + logger.error('error updating user [%s] repos' % self.username, exc_info=1) + + # Get application config + cfg = cherrypy.tree.apps[''].cfg + + dirty = False + records = RepoObject.query.filter(RepoObject.userid == self.userid).order_by(RepoObject.repopath).all() + user_root = os.fsencode(self.user_root) + for root, dirs, unused_files in os.walk(user_root, _onerror): + for name in dirs.copy(): + if name.startswith(b'.'): + dirs.remove(name) + if b'rdiff-backup-data' in dirs: + repopath = os.path.relpath(root, start=user_root) + del dirs[:] + # Handle special scenario when the repo is the + # user_root + repopath = b'' if repopath == b'.' else repopath + + # Check if repo path exists. + record_match = next((record for record in records if record.repopath == os.fsdecode(repopath)), None) + if not record_match: + # Add repository to database. + RepoObject(user=self, repopath=os.fsdecode(repopath)).add() + dirty = True + else: + records.remove(record_match) + if root.count(SEP) - user_root.count(SEP) >= cfg.max_depth: + del dirs[:] + # If enabled, remove entried from database + if delete: + for record in records: + RepoObject.query.filter(RepoObject.repoid == record.repoid).delete() + return dirty + + @hybrid_property + def is_admin(self): + return self.role is not None and self.role <= self.ADMIN_ROLE + + @hybrid_property + def is_ldap(self): + return self.hash_password is None or self.hash_password == '' + + @is_ldap.expression + def is_ldap(cls): + return or_(cls.hash_password.is_(None), cls.hash_password == '') + + @hybrid_property + def is_maintainer(self): + return self.role is not None and self.role <= self.MAINTAINER_ROLE + + def set_password(self, password): + """ + Change the user's password. Raise a ValueError if the username or + the password are invalid. + """ + assert isinstance(password, str) + if not password: + raise ValueError("password can't be empty") + cfg = cherrypy.tree.apps[''].cfg + + # Cannot update admin-password if defined + if self.username == cfg.admin_user and cfg.admin_password: + raise ValueError(_("can't update admin-password defined in configuration file")) + + # Check password length + if cfg.password_min_length > len(password) or len(password) > cfg.password_max_length: + raise ValueError( + _('Password must have between %(min)d and %(max)d characters.') + % {'min': cfg.password_min_length, 'max': cfg.password_max_length} + ) + + # Verify password score using zxcvbn + stats = zxcvbn(password) + if stats.get('score') < cfg.password_score: + msg = _('Password too weak.') + warning = stats.get('feedback', {}).get('warning') + suggestions = stats.get('feedback', {}).get('suggestions') + if warning: + msg += ' ' + warning + if suggestions: + msg += ' ' + ' '.join(suggestions) + raise ValueError(msg) + + # Store password + logger.info("updating user password [%s] and revoke sessions", self.username) + self.hash_password = hash_password(password) + + # Revoke other session to force re-login + session_id = cherrypy.serving.session.id if hasattr(cherrypy.serving, 'session') else None + SessionObject.query.filter( + SessionObject.username == self.username, + SessionObject.id != session_id, + ).delete() + + def __eq__(self, other): + return type(self) == type(other) and inspect(self).key == inspect(other).key + + @validates('username') + def validates_username(self, key, value): + if self.username: + raise ValueError('Username cannot be modified.') + return value + + def validate_access_token(self, token): + """ + Check if the given token matches. + """ + for access_token in Token.query.all(): + if access_token.is_expired: + continue + if check_password(token, access_token.hash_token): + # When it matches, return the record. + return access_token + return False + + def validate_password(self, password): + return check_password(password, self.hash_password) +``` + +## `rdiffweb/core/model/_user.py` — `function:UserObject.add_authorizedkey` (lines 153-186) + +```python + def add_authorizedkey(self, key, comment=None): + """ + Add the given key to the user. Adding the key to his `authorized_keys` + file if it exists and adding it to database. + """ + # Parse and validate ssh key + assert key + key = authorizedkeys.check_publickey(key) + + # Remove option & Remove comment for SQL storage + key = authorizedkeys.AuthorizedKey( + options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment + ) + + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + with open(filename, mode="r+", encoding='utf-8') as fh: + if authorizedkeys.exists(fh, key): + raise DuplicateSSHKeyError(_("SSH key already exists")) + logger.info("add key [%s] to [%s] authorized_keys", key, self.username) + authorizedkeys.add(fh, key) + else: + # Also look in database. + logger.info("add key [%s] to [%s] database", key, self.username) + try: + sshkey = SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()) + sshkey.add().flush() + except IntegrityError: + raise DuplicateSSHKeyError( + _("Duplicate key. This key already exists or is associated to another user.") + ) + cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True}) + cherrypy.engine.publish('authorizedkey_added', self, fingerprint=key.fingerprint, comment=comment) +``` + +## `rdiffweb/core/model/tests/test_user.py` — `class:UserObjectTest` (lines 38-503) + +```python +class UserObjectTest(rdiffweb.test.WebCase): + def _read_ssh_key(self): + """Readthe pub key from test packages""" + filename = pkg_resources.resource_filename('rdiffweb.core.tests', 'test_publickey_ssh_rsa.pub') + with open(filename, 'r', encoding='utf8') as f: + return f.readline() + + def _read_authorized_keys(self): + """Read the content of test_authorized_keys""" + filename = pkg_resources.resource_filename('rdiffweb.core.tests', 'test_authorized_keys') + with open(filename, 'r', encoding='utf8') as f: + return f.read() + + def setUp(self): + super().setUp() + self.listener = MagicMock() + cherrypy.engine.subscribe('access_token_added', self.listener.access_token_added, priority=50) + cherrypy.engine.subscribe('queue_mail', self.listener.queue_mail, priority=50) + cherrypy.engine.subscribe('user_added', self.listener.user_added, priority=50) + cherrypy.engine.subscribe('user_attr_changed', self.listener.user_attr_changed, priority=50) + cherrypy.engine.subscribe('user_deleted', self.listener.user_deleted, priority=50) + cherrypy.engine.subscribe('user_login', self.listener.user_login, priority=50) + cherrypy.engine.subscribe('user_password_changed', self.listener.user_password_changed, priority=50) + + def tearDown(self): + cherrypy.engine.unsubscribe('access_token_added', self.listener.access_token_added) + cherrypy.engine.unsubscribe('queue_mail', self.listener.queue_mail) + cherrypy.engine.unsubscribe('user_added', self.listener.user_added) + cherrypy.engine.unsubscribe('user_attr_changed', self.listener.user_attr_changed) + cherrypy.engine.unsubscribe('user_deleted', self.listener.user_deleted) + cherrypy.engine.unsubscribe('user_login', self.listener.user_login) + cherrypy.engine.unsubscribe('user_password_changed', self.listener.user_password_changed) + return super().tearDown() + + def test_add_user(self): + """Add user to database.""" + userobj = UserObject.add_user('joe') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('joe')) + # Check if listener called + self.listener.user_added.assert_called_once_with(userobj) + + def test_add_user_updated_by_listener(self): + """Add user to database.""" + # Given a listener with side effet + def change_user_obj(userobj): + userobj.user_root = '/new/value' + + self.listener.user_added.side_effect = change_user_obj + # When adding user + userobj = UserObject.add_user('joe') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('joe')) + # Then lister get called + self.listener.user_added.assert_called_once_with(userobj) + # Then object was updated by listener + self.assertEqual('/new/value', userobj.user_root) + + def test_add_user_with_duplicate(self): + """Add user to database.""" + user = UserObject.add_user('denise') + user.commit() + self.listener.user_added.reset_mock() + with self.assertRaises(ValueError): + UserObject.add_user('denise') + # Check if listener called + self.listener.user_added.assert_not_called() + + def test_add_user_with_duplicate_caseinsensitive(self): + """Add user to database.""" + user = UserObject.add_user('denise') + user.commit() + self.listener.user_added.reset_mock() + with self.assertRaises(ValueError): + UserObject.add_user('dEnIse') + # Check if listener called + self.listener.user_added.assert_not_called() + + def test_add_user_with_password(self): + """Add user to database with password.""" + userobj = UserObject.add_user('jo', 'password') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('jo')) + # Check if listener called + self.listener.user_added.assert_called_once_with(userobj) + + def test_delete_admin_user(self): + # Trying to delete admin user should raise an error. + userobj = UserObject.get_user('admin') + with self.assertRaises(ValueError): + userobj.delete() + + def test_users(self): + # Check admin exists + self.assertEqual(1, UserObject.query.count()) + # Create user. + user = UserObject.add_user('annik') + user.commit() + users = UserObject.query.all() + self.assertEqual(2, len(users)) + self.assertEqual('annik', users[1].username) + # Then 2 user exists + self.assertEqual(2, UserObject.query.count()) + + def test_get_user(self): + # Create new user + user = UserObject.add_user('bernie', 'my-password') + user.user_root = self.testcases + user.role = UserObject.ADMIN_ROLE + user.email = 'bernie@gmail.com' + user.refresh_repos() + user.commit() + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in user.repo_objs])) + user.repo_objs[0].maxage = -1 + user.repo_objs[1].maxage = 3 + user.commit() + + # Get user record. + obj = UserObject.get_user('bernie') + self.assertIsNotNone(obj) + self.assertEqual('bernie', obj.username) + self.assertEqual('bernie@gmail.com', obj.email) + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in obj.repo_objs])) + self.assertEqual(self.testcases, obj.user_root) + self.assertEqual(True, obj.is_admin) + self.assertEqual(UserObject.ADMIN_ROLE, obj.role) + + # Get repo object + self.assertEqual('broker-repo', obj.repo_objs[0].name) + self.assertEqual(-1, obj.repo_objs[0].maxage) + self.assertEqual('testcases', obj.repo_objs[1].name) + self.assertEqual(3, obj.repo_objs[1].maxage) + + def test_get_user_case_insensitive(self): + userobj1 = UserObject.get_user(self.USERNAME) + userobj2 = UserObject.get_user(self.USERNAME.lower()) + userobj3 = UserObject.get_user(self.USERNAME.upper()) + self.assertEqual(userobj1, userobj2) + self.assertEqual(userobj2, userobj3) + + def test_get_user_with_invalid_user(self): + self.assertIsNone(UserObject.get_user('invalid')) + + def test_get_set(self): + user = UserObject.add_user('larry', 'password') + user.add().commit() + + self.assertEqual('', user.email) + self.assertEqual([], user.repo_objs) + self.assertEqual('', user.user_root) + self.assertEqual(False, user.is_admin) + self.assertEqual(UserObject.USER_ROLE, user.role) + + user.user_root = self.testcases + user.refresh_repos() + user.commit() + self.listener.user_attr_changed.assert_called_with(user, {'user_root': ('', self.testcases)}) + self.listener.user_attr_changed.reset_mock() + user = UserObject.get_user('larry') + user.role = UserObject.ADMIN_ROLE + user.commit() + self.listener.user_attr_changed.assert_called_with( + user, {'role': (UserObject.USER_ROLE, UserObject.ADMIN_ROLE)} + ) + self.listener.user_attr_changed.reset_mock() + user = UserObject.get_user('larry') + user.email = 'larry@gmail.com' + user.commit() + self.listener.user_attr_changed.assert_called_with(user, {'email': ('', 'larry@gmail.com')}) + self.listener.user_attr_changed.reset_mock() + + self.assertEqual('larry@gmail.com', user.email) + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in user.repo_objs])) + self.assertEqual(self.testcases, user.user_root) + self.assertEqual(True, user.is_admin) + self.assertEqual(UserObject.ADMIN_ROLE, user.role) + + def test_set_role_null(self): + # Given a user + user = UserObject.add_user('annik', 'password') + user.add().commit() + # When trying to set the role to null + user.role = None + # Then an exception is raised + with self.assertRaises(Exception): + user.add().commit() + + @parameterized.expand( + [ + (-1, True), + (0, True), + (5, False), + (10, False), + (15, False), + ] + ) + def test_is_admin(self, role, expected_is_admin): + # Given a user + user = UserObject.add_user('annik', 'password') + # When setting the role value + user.role = role + user.commit() + # Then the is_admin value get updated too + self.assertEqual(expected_is_admin, user.is_admin) + + @parameterized.expand( + [ + (-1, True), + (0, True), + (5, True), + (10, False), + (15, False), + ] + ) + def test_is_maintainer(self, role, expected_is_maintainer): + # Given a user + user = UserObject.add_user('annik', 'password') + # When setting the role value + user.role = role + user.commit() + # Then the is_admin value get updated too + self.assertEqual(expected_is_maintainer, user.is_maintainer) + + def test_set_password_update(self): + # Given a user in database with a password + userobj = UserObject.add_user('annik', 'password') + userobj.commit() + self.listener.user_password_changed.reset_mock() + # When updating the user's password + userobj.set_password('new_password') + userobj.commit() + # Then password is SSHA + self.assertTrue(check_password('new_password', userobj.hash_password)) + # Check if listener called + self.listener.user_password_changed.assert_called_once_with(userobj) + + def test_delete_user(self): + # Given an existing user in database + userobj = UserObject.add_user('vicky') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('vicky')) + # When deleting that user + userobj.delete() + userobj.commit() + # Then user it no longer in database + self.assertIsNone(UserObject.get_user('vicky')) + # Then listner was called + self.listener.user_deleted.assert_called_once_with('vicky') + + def test_set_password_empty(self): + """Expect error when trying to update password of invalid user.""" + userobj = UserObject.add_user('john') + userobj.commit() + with self.assertRaises(ValueError): + self.assertFalse(userobj.set_password('')) + + def test_disk_quota(self): + """ + Just make a call to the function. + """ + userobj = UserObject.get_user(self.USERNAME) + userobj.disk_quota + + def test_disk_usage(self): + """ + Just make a call to the function. + """ + userobj = UserObject.get_user(self.USERNAME) + disk_usage = userobj.disk_usage + self.assertIsInstance(disk_usage, int) + + def test_add_authorizedkey_without_file(self): + """ + Add an ssh key for a user without an authorizedkey file. + """ + # Read the pub key + key = self._read_ssh_key() + # Add the key to the user + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # validate + keys = list(userobj.authorizedkeys) + self.assertEqual(1, len(keys), "expecting one key") + self.assertEqual("3c:99:ed:a7:82:a8:71:09:2c:15:3d:78:4a:8c:11:99", keys[0].fingerprint) + + def test_add_authorizedkey_duplicate(self): + # Read the pub key + key = self._read_ssh_key() + # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # When adding the same identical key. + # Then an error is raised + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key) + userobj.commit() + + def test_add_authorizedkey_duplicate_new_comment(self): + # Read the pub key + key = self._read_ssh_key() + # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # When adding the same key with a different comment + # Then an error is raised + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key, comment="new comment") + userobj.commit() + + def test_add_authorizedkey_duplicate_new_user(self): + # Read the pub key + key = self._read_ssh_key() + # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # When adding the same key to a different user + # Then an error is raised + newuser = UserObject.add_user("newuser") + newuser.commit() + with self.assertRaises(DuplicateSSHKeyError): + newuser.add_authorizedkey(key, comment="new comment") + newuser.commit() + + def test_add_authorizedkey_with_file(self): + """ + Add an ssh key for a user with an authorizedkey file. + """ + userobj = UserObject.get_user(self.USERNAME) + + # Create empty authorized_keys file + os.mkdir(os.path.join(userobj.user_root, '.ssh')) + filename = os.path.join(userobj.user_root, '.ssh', 'authorized_keys') + open(filename, 'a').close() + + # Read the pub key + key = self._read_ssh_key() + userobj.add_authorizedkey(key) + userobj.commit() + + # Validate + with open(filename, 'r') as fh: + self.assertEqual(key, fh.read()) + + def test_delete_authorizedkey_without_file(self): + """ + Remove an ssh key for a user without authorizedkey file. + """ + # Update user with ssh keys. + data = self._read_authorized_keys() + userobj = UserObject.get_user(self.USERNAME) + for k in authorizedkeys.read(StringIO(data)): + try: + userobj.add_authorizedkey(k.getvalue()) + except ValueError: + # Some ssh key in the testing file are not valid. + pass + + # Get the keys + keys = list(userobj.authorizedkeys) + self.assertEqual(2, len(keys)) + + # Remove a key + userobj.delete_authorizedkey("9a:f1:69:3c:bc:5a:cd:02:5e:33:bc:cd:c0:01:eb:4c") + userobj.commit() + + # Validate + keys = list(userobj.authorizedkeys) + self.assertEqual(1, len(keys)) + + def test_delete_authorizedkey_with_file(self): + """ + Remove an ssh key for a user with authorizedkey file. + """ + # Create authorized_keys file + data = self._read_authorized_keys() + userobj = UserObject.get_user(self.USERNAME) + os.mkdir(os.path.join(userobj.user_root, '.ssh')) + filename = os.path.join(userobj.user_root, '.ssh', 'authorized_keys') + with open(filename, 'w') as f: + f.write(data) + + # Get the keys + keys = list(userobj.authorizedkeys) + self.assertEqual(5, len(keys)) + + # Remove a key + userobj.delete_authorizedkey("9a:f1:69:3c:bc:5a:cd:02:5e:33:bc:cd:c0:01:eb:4c") + + # Validate + keys = list(userobj.authorizedkeys) + self.assertEqual(4, len(keys)) + + def test_repo_objs(self): + # Given a user with a list of repositories + userobj = UserObject.get_user(self.USERNAME) + repos = sorted(userobj.repo_objs, key=lambda r: r.name) + self.assertEqual(['broker-repo', 'testcases'], [r.name for r in repos]) + # When deleting a repository empty list + repos[1].delete() + repos[1].commit() + # Then the repository is removed from the list. + self.assertEqual(['broker-repo'], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_without_delete(self): + # Given a user with invalid repositories + userobj = UserObject.get_user(self.USERNAME) + RepoObject.query.delete() + RepoObject(userid=userobj.userid, repopath='invalid').add().commit() + self.assertEqual(['invalid'], sorted([r.name for r in userobj.repo_objs])) + # When updating the repository list without deletion + userobj.refresh_repos() + userobj.commit() + # Then the list invlaid the invalid repo and new repos + self.assertEqual(['broker-repo', 'invalid', 'testcases'], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_with_delete(self): + # Given a user with invalid repositories + userobj = UserObject.get_user(self.USERNAME) + RepoObject.query.delete() + RepoObject(userid=userobj.userid, repopath='invalid').add().commit() + self.assertEqual(['invalid'], sorted([r.name for r in userobj.repo_objs])) + # When updating the repository list without deletion + userobj.refresh_repos(delete=True) + userobj.commit() + # Then the list invlaid the invalid repo and new repos + userobj.expire() + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_with_single_repo(self): + # Given a user with invalid repositories + userobj = UserObject.get_user(self.USERNAME) + userobj.user_root = os.path.join(self.testcases, 'testcases') + # When updating the repository list without deletion + userobj.refresh_repos(delete=True) + userobj.commit() + # Then the list invlaid the invalid repo and new repos + userobj.expire() + self.assertEqual([''], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_with_empty_userroot(self): + # Given a user with valid repositories relative to root + userobj = UserObject.get_user(self.USERNAME) + for repo in userobj.repo_objs: + repo.repopath = self.testcases[1:] + '/' + repo.repopath + repo.add().commit() + userobj.user_root = '/' + userobj.add().commit() + self.assertEqual(['interrupted', 'ok'], sorted([r.status[0] for r in userobj.repo_objs])) + # When updating it's userroot directory to an empty value + userobj.user_root = '' + userobj.add().commit() + UserObject.session.expire_all() + # Then close session + cherrypy.tools.db.on_end_resource() + # Then repo status is "broken" + userobj = UserObject.get_user(self.USERNAME) + self.assertFalse(userobj.valid_user_root()) + self.assertEqual(['failed', 'failed'], [r.status[0] for r in userobj.repo_objs]) +``` + +## `rdiffweb/core/model/tests/test_user.py` — `function:UserObjectTest.test_add_authorizedkey_duplicate` (lines 325-337) + +```python + def test_add_authorizedkey_duplicate(self): + # Read the pub key + key = self._read_ssh_key() + # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # When adding the same identical key. + # Then an error is raised + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key) + userobj.commit() +``` + +## `rdiffweb/core/model/tests/test_user.py` — `function:UserObjectTest.test_add_authorizedkey_duplicate_new_comment` (lines 339-351) + +```python + def test_add_authorizedkey_duplicate_new_comment(self): + # Read the pub key + key = self._read_ssh_key() + # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # When adding the same key with a different comment + # Then an error is raised + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key, comment="new comment") + userobj.commit() +``` + +## `rdiffweb/core/model/tests/test_user.py` — `function:UserObjectTest.test_add_authorizedkey_duplicate_new_user` (lines 353-367) + +```python + def test_add_authorizedkey_duplicate_new_user(self): + # Read the pub key + key = self._read_ssh_key() + # Given a user with a SSH Key + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # When adding the same key to a different user + # Then an error is raised + newuser = UserObject.add_user("newuser") + newuser.commit() + with self.assertRaises(DuplicateSSHKeyError): + newuser.add_authorizedkey(key, comment="new comment") + newuser.commit() +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8009b06c4b9a8cfeae761d06370d29739ea5f937 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/pre_context.md @@ -0,0 +1,913 @@ +# Patch-overlapping Python context before the fix + +## `rdiffweb/core/model/__init__.py` — `module:@22` (lines 22-22) + +```python +from sqlalchemy import event +``` + +## `rdiffweb/core/model/__init__.py` — `module:@23` (lines 23-23) + +```python +from sqlalchemy.exc import IntegrityError +``` + +## `rdiffweb/core/model/__init__.py` — `module:@27` (lines 27-27) + +```python +from ._sshkey import SshKey # noqa +``` + +## `rdiffweb/core/model/__init__.py` — `module:@28` (lines 28-28) + +```python +from ._token import Token # noqa +``` + +## `rdiffweb/core/model/_sshkey.py` — `module:@19` (lines 19-19) + +```python +from sqlalchemy import Column, Integer, Text +``` + +## `rdiffweb/core/model/_user.py` — `class:UserObject` (lines 54-413) + +```python +class UserObject(Base): + __tablename__ = 'users' + __table_args__ = {'sqlite_autoincrement': True} + + # Value for role. + ADMIN_ROLE = 0 + MAINTAINER_ROLE = 5 + USER_ROLE = 10 + ROLES = { + 'admin': ADMIN_ROLE, + 'maintainer': MAINTAINER_ROLE, + 'user': USER_ROLE, + } + # Value for mfa field + DISABLED_MFA = 0 + ENABLED_MFA = 1 + + # Regex pattern to be used for validation. + PATTERN_EMAIL = r"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" + PATTERN_FULLNAME = r"""[^!"#$%&()*+,./:;<=>?@[\]_{|}~]+$""" + PATTERN_USERNAME = r"[a-zA-Z0-9_.\-]+$" + + userid = Column('UserID', Integer, primary_key=True) + username = Column('Username', String, nullable=False) + hash_password = Column('Password', String, nullable=False, default="") + user_root = Column('UserRoot', String, nullable=False, default="") + _is_admin = deferred( + Column( + 'IsAdmin', + SmallInteger, + nullable=False, + server_default="0", + doc="DEPRECATED This column is replaced by 'role'", + ) + ) + email = Column('UserEmail', String, nullable=False, default="") + restore_format = deferred( + Column( + 'RestoreFormat', + SmallInteger, + nullable=False, + server_default="1", + doc="DEPRECATED This column is not used anymore", + ) + ) + role = Column('role', SmallInteger, nullable=False, server_default=str(USER_ROLE), default=USER_ROLE) + fullname = Column('fullname', String, nullable=False, default="") + mfa = Column('mfa', SmallInteger, nullable=False, default=DISABLED_MFA) + repo_objs = relationship( + 'RepoObject', + foreign_keys='UserObject.userid', + primaryjoin='UserObject.userid == RepoObject.userid', + uselist=True, + lazy=True, + order_by=lambda: RepoObject.repopath, + ) + + @classmethod + def get_user(cls, user): + """Return a user object with username case-insensitive""" + return UserObject.query.filter(func.lower(UserObject.username) == user.lower()).first() + + @classmethod + def create_admin_user(cls, default_username, default_password): + # Check if admin user exists. If not, created it. + userobj = UserObject.get_user(default_username) + if not userobj: + userobj = cls.add_user(default_username, role=UserObject.ADMIN_ROLE, user_root='/backups') + userobj.hash_password = hash_password('admin123') + # Also make sure to update the password with latest value from config file. + if default_password: + if default_password.startswith('{SSHA}') or default_password.startswith('$argon2'): + userobj.hash_password = default_password + else: + userobj.hash_password = hash_password(default_password) + userobj.add() + return userobj + + @classmethod + def add_user(cls, username, password=None, role=USER_ROLE, **attrs): + """ + Used to add a new user with an optional password. + """ + assert password is None or isinstance(password, str) + # Check if user already exists. + if UserObject.get_user(username): + raise ValueError(_("User %s already exists." % (username,))) + + # Find a database where to add the user + logger.info("adding new user [%s]", username) + userobj = UserObject( + username=username, + hash_password=hash_password(password) if password else '', + role=role, + **attrs, + ).add() + # Return user object + return userobj + + def add_authorizedkey(self, key, comment=None): + """ + Add the given key to the user. Adding the key to his `authorized_keys` + file if it exists and adding it to database. + """ + # Parse and validate ssh key + assert key + key = authorizedkeys.check_publickey(key) + + # Remove option, replace comments. + key = authorizedkeys.AuthorizedKey( + options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment + ) + + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + with open(filename, mode="r+", encoding='utf-8') as fh: + if authorizedkeys.exists(fh, key): + raise DuplicateSSHKeyError(_("SSH key already exists")) + logger.info("add key [%s] to [%s] authorized_keys", key, self.username) + authorizedkeys.add(fh, key) + else: + # Also look in database. + logger.info("add key [%s] to [%s] database", key, self.username) + try: + SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()).add().flush() + except IntegrityError: + raise DuplicateSSHKeyError( + _("Duplicate key. This key already exists or is associated to another user.") + ) + cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True}) + cherrypy.engine.publish('authorizedkey_added', self, fingerprint=key.fingerprint, comment=comment) + + def add_access_token(self, name, expiration_time=None, length=16): + """ + Create a new access token. Return the un-encrypted value of the token. + """ + assert name + assert length >= 8 + # Generate a random token + token = ''.join(secrets.choice(string.ascii_lowercase) for i in range(length)) + # Store hash token + try: + Token( + userid=self.userid, name=name, hash_token=hash_password(token), expiration_time=expiration_time + ).add().flush() + except IntegrityError: + raise ValueError(_("Duplicate token name: %s") % name) + cherrypy.engine.publish('access_token_added', self, name) + return token + + def valid_user_root(self): + """ + Check if the current user_root is valid and readable + """ + try: + return os.access(self.user_root, os.F_OK) and os.path.isdir(self.user_root) + except Exception: + return False + + def delete(self, *args, **kwargs): + cfg = cherrypy.tree.apps[''].cfg + if self.username == cfg.admin_user: + raise ValueError(_("can't delete admin user")) + # FIXME This should be deleted by cascade + SshKey.query.filter(SshKey.userid == self.userid).delete() + RepoObject.query.filter(RepoObject.userid == self.userid).delete() + Token.query.filter(Token.userid == self.userid).delete() + # Delete ourself + return Base.delete(self) + + def delete_authorizedkey(self, fingerprint): + """ + Remove the given key from the user. Remove the key from his + `authorized_keys` file if it exists and from database database. + """ + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + with open(filename, mode='r+', encoding='utf-8') as fh: + logger.info("removing key [%s] from [%s] authorized_keys", fingerprint, self.username) + authorizedkeys.remove(fh, fingerprint) + else: + # Also look in database. + logger.info("removing key [%s] from [%s] database", fingerprint, self.username) + SshKey.query.filter(and_(SshKey.userid == self.userid, SshKey.fingerprint == fingerprint)).delete() + cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True}) + + def delete_access_token(self, name): + assert name + if not Token.query.filter(Token.userid == self.userid, Token.name == name).delete(): + raise ValueError(_("token name doesn't exists: %s") % name) + + @property + def disk_usage(self): + # Skip if user_root is invalid. + if not self.user_root or not os.path.exists(self.user_root): + return 0 + values = cherrypy.engine.publish('get_disk_usage', self) + # Return the first not None value + return next((v for v in values if v is not None), 0) + + @property + def disk_quota(self): + # Skip if user_root is invalid. + if not self.user_root or not os.path.exists(self.user_root): + return 0 + values = cherrypy.engine.publish('get_disk_quota', self) + # Return the first not None value + return next((v for v in values if v is not None), 0) + + @disk_quota.setter + def disk_quota(self, value): + # Skip if user_root is invalid. + if not self.user_root or not os.path.exists(self.user_root): + return + cherrypy.engine.publish('set_disk_quota', self, value) + + @property + def authorizedkeys(self): + """ + Return an iterator on the authorized key. Either from his + `authorized_keys` file if it exists or from database. + """ + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + for k in authorizedkeys.read(filename): + yield k + + # Also look in database. + for record in SshKey.query.filter(SshKey.userid == self.userid).all(): + yield authorizedkeys.check_publickey(record.key) + + def refresh_repos(self, delete=False): + """ + Return list of repositories object to reflect the filesystem folders. + + Return a RepoObject for each sub directories under `user_root` with `rdiff-backup-data`. + """ + # Update the repositories by walking in the directory tree. + def _onerror(unused): + logger.error('error updating user [%s] repos' % self.username, exc_info=1) + + # Get application config + cfg = cherrypy.tree.apps[''].cfg + + dirty = False + records = RepoObject.query.filter(RepoObject.userid == self.userid).order_by(RepoObject.repopath).all() + user_root = os.fsencode(self.user_root) + for root, dirs, unused_files in os.walk(user_root, _onerror): + for name in dirs.copy(): + if name.startswith(b'.'): + dirs.remove(name) + if b'rdiff-backup-data' in dirs: + repopath = os.path.relpath(root, start=user_root) + del dirs[:] + # Handle special scenario when the repo is the + # user_root + repopath = b'' if repopath == b'.' else repopath + + # Check if repo path exists. + record_match = next((record for record in records if record.repopath == os.fsdecode(repopath)), None) + if not record_match: + # Add repository to database. + RepoObject(user=self, repopath=os.fsdecode(repopath)).add() + dirty = True + else: + records.remove(record_match) + if root.count(SEP) - user_root.count(SEP) >= cfg.max_depth: + del dirs[:] + # If enabled, remove entried from database + if delete: + for record in records: + RepoObject.query.filter(RepoObject.repoid == record.repoid).delete() + return dirty + + @hybrid_property + def is_admin(self): + return self.role is not None and self.role <= self.ADMIN_ROLE + + @hybrid_property + def is_ldap(self): + return self.hash_password is None or self.hash_password == '' + + @is_ldap.expression + def is_ldap(cls): + return or_(cls.hash_password.is_(None), cls.hash_password == '') + + @hybrid_property + def is_maintainer(self): + return self.role is not None and self.role <= self.MAINTAINER_ROLE + + def set_password(self, password): + """ + Change the user's password. Raise a ValueError if the username or + the password are invalid. + """ + assert isinstance(password, str) + if not password: + raise ValueError("password can't be empty") + cfg = cherrypy.tree.apps[''].cfg + + # Cannot update admin-password if defined + if self.username == cfg.admin_user and cfg.admin_password: + raise ValueError(_("can't update admin-password defined in configuration file")) + + # Check password length + if cfg.password_min_length > len(password) or len(password) > cfg.password_max_length: + raise ValueError( + _('Password must have between %(min)d and %(max)d characters.') + % {'min': cfg.password_min_length, 'max': cfg.password_max_length} + ) + + # Verify password score using zxcvbn + stats = zxcvbn(password) + if stats.get('score') < cfg.password_score: + msg = _('Password too weak.') + warning = stats.get('feedback', {}).get('warning') + suggestions = stats.get('feedback', {}).get('suggestions') + if warning: + msg += ' ' + warning + if suggestions: + msg += ' ' + ' '.join(suggestions) + raise ValueError(msg) + + # Store password + logger.info("updating user password [%s] and revoke sessions", self.username) + self.hash_password = hash_password(password) + + # Revoke other session to force re-login + session_id = cherrypy.serving.session.id if hasattr(cherrypy.serving, 'session') else None + SessionObject.query.filter( + SessionObject.username == self.username, + SessionObject.id != session_id, + ).delete() + + def __eq__(self, other): + return type(self) == type(other) and inspect(self).key == inspect(other).key + + @validates('username') + def validates_username(self, key, value): + if self.username: + raise ValueError('Username cannot be modified.') + return value + + def validate_access_token(self, token): + """ + Check if the given token matches. + """ + for access_token in Token.query.all(): + if access_token.is_expired: + continue + if check_password(token, access_token.hash_token): + # When it matches, return the record. + return access_token + return False + + def validate_password(self, password): + return check_password(password, self.hash_password) +``` + +## `rdiffweb/core/model/_user.py` — `function:UserObject.add_authorizedkey` (lines 153-185) + +```python + def add_authorizedkey(self, key, comment=None): + """ + Add the given key to the user. Adding the key to his `authorized_keys` + file if it exists and adding it to database. + """ + # Parse and validate ssh key + assert key + key = authorizedkeys.check_publickey(key) + + # Remove option, replace comments. + key = authorizedkeys.AuthorizedKey( + options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment + ) + + # If a filename exists, use it by default. + filename = os.path.join(self.user_root, '.ssh', 'authorized_keys') + if os.path.isfile(filename): + with open(filename, mode="r+", encoding='utf-8') as fh: + if authorizedkeys.exists(fh, key): + raise DuplicateSSHKeyError(_("SSH key already exists")) + logger.info("add key [%s] to [%s] authorized_keys", key, self.username) + authorizedkeys.add(fh, key) + else: + # Also look in database. + logger.info("add key [%s] to [%s] database", key, self.username) + try: + SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()).add().flush() + except IntegrityError: + raise DuplicateSSHKeyError( + _("Duplicate key. This key already exists or is associated to another user.") + ) + cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True}) + cherrypy.engine.publish('authorizedkey_added', self, fingerprint=key.fingerprint, comment=comment) +``` + +## `rdiffweb/core/model/tests/test_user.py` — `class:UserObjectTest` (lines 38-471) + +```python +class UserObjectTest(rdiffweb.test.WebCase): + def _read_ssh_key(self): + """Readthe pub key from test packages""" + filename = pkg_resources.resource_filename('rdiffweb.core.tests', 'test_publickey_ssh_rsa.pub') + with open(filename, 'r', encoding='utf8') as f: + return f.readline() + + def _read_authorized_keys(self): + """Read the content of test_authorized_keys""" + filename = pkg_resources.resource_filename('rdiffweb.core.tests', 'test_authorized_keys') + with open(filename, 'r', encoding='utf8') as f: + return f.read() + + def setUp(self): + super().setUp() + self.listener = MagicMock() + cherrypy.engine.subscribe('access_token_added', self.listener.access_token_added, priority=50) + cherrypy.engine.subscribe('queue_mail', self.listener.queue_mail, priority=50) + cherrypy.engine.subscribe('user_added', self.listener.user_added, priority=50) + cherrypy.engine.subscribe('user_attr_changed', self.listener.user_attr_changed, priority=50) + cherrypy.engine.subscribe('user_deleted', self.listener.user_deleted, priority=50) + cherrypy.engine.subscribe('user_login', self.listener.user_login, priority=50) + cherrypy.engine.subscribe('user_password_changed', self.listener.user_password_changed, priority=50) + + def tearDown(self): + cherrypy.engine.unsubscribe('access_token_added', self.listener.access_token_added) + cherrypy.engine.unsubscribe('queue_mail', self.listener.queue_mail) + cherrypy.engine.unsubscribe('user_added', self.listener.user_added) + cherrypy.engine.unsubscribe('user_attr_changed', self.listener.user_attr_changed) + cherrypy.engine.unsubscribe('user_deleted', self.listener.user_deleted) + cherrypy.engine.unsubscribe('user_login', self.listener.user_login) + cherrypy.engine.unsubscribe('user_password_changed', self.listener.user_password_changed) + return super().tearDown() + + def test_add_user(self): + """Add user to database.""" + userobj = UserObject.add_user('joe') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('joe')) + # Check if listener called + self.listener.user_added.assert_called_once_with(userobj) + + def test_add_user_updated_by_listener(self): + """Add user to database.""" + # Given a listener with side effet + def change_user_obj(userobj): + userobj.user_root = '/new/value' + + self.listener.user_added.side_effect = change_user_obj + # When adding user + userobj = UserObject.add_user('joe') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('joe')) + # Then lister get called + self.listener.user_added.assert_called_once_with(userobj) + # Then object was updated by listener + self.assertEqual('/new/value', userobj.user_root) + + def test_add_user_with_duplicate(self): + """Add user to database.""" + user = UserObject.add_user('denise') + user.commit() + self.listener.user_added.reset_mock() + with self.assertRaises(ValueError): + UserObject.add_user('denise') + # Check if listener called + self.listener.user_added.assert_not_called() + + def test_add_user_with_duplicate_caseinsensitive(self): + """Add user to database.""" + user = UserObject.add_user('denise') + user.commit() + self.listener.user_added.reset_mock() + with self.assertRaises(ValueError): + UserObject.add_user('dEnIse') + # Check if listener called + self.listener.user_added.assert_not_called() + + def test_add_user_with_password(self): + """Add user to database with password.""" + userobj = UserObject.add_user('jo', 'password') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('jo')) + # Check if listener called + self.listener.user_added.assert_called_once_with(userobj) + + def test_delete_admin_user(self): + # Trying to delete admin user should raise an error. + userobj = UserObject.get_user('admin') + with self.assertRaises(ValueError): + userobj.delete() + + def test_users(self): + # Check admin exists + self.assertEqual(1, UserObject.query.count()) + # Create user. + user = UserObject.add_user('annik') + user.commit() + users = UserObject.query.all() + self.assertEqual(2, len(users)) + self.assertEqual('annik', users[1].username) + # Then 2 user exists + self.assertEqual(2, UserObject.query.count()) + + def test_get_user(self): + # Create new user + user = UserObject.add_user('bernie', 'my-password') + user.user_root = self.testcases + user.role = UserObject.ADMIN_ROLE + user.email = 'bernie@gmail.com' + user.refresh_repos() + user.commit() + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in user.repo_objs])) + user.repo_objs[0].maxage = -1 + user.repo_objs[1].maxage = 3 + user.commit() + + # Get user record. + obj = UserObject.get_user('bernie') + self.assertIsNotNone(obj) + self.assertEqual('bernie', obj.username) + self.assertEqual('bernie@gmail.com', obj.email) + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in obj.repo_objs])) + self.assertEqual(self.testcases, obj.user_root) + self.assertEqual(True, obj.is_admin) + self.assertEqual(UserObject.ADMIN_ROLE, obj.role) + + # Get repo object + self.assertEqual('broker-repo', obj.repo_objs[0].name) + self.assertEqual(-1, obj.repo_objs[0].maxage) + self.assertEqual('testcases', obj.repo_objs[1].name) + self.assertEqual(3, obj.repo_objs[1].maxage) + + def test_get_user_case_insensitive(self): + userobj1 = UserObject.get_user(self.USERNAME) + userobj2 = UserObject.get_user(self.USERNAME.lower()) + userobj3 = UserObject.get_user(self.USERNAME.upper()) + self.assertEqual(userobj1, userobj2) + self.assertEqual(userobj2, userobj3) + + def test_get_user_with_invalid_user(self): + self.assertIsNone(UserObject.get_user('invalid')) + + def test_get_set(self): + user = UserObject.add_user('larry', 'password') + user.add().commit() + + self.assertEqual('', user.email) + self.assertEqual([], user.repo_objs) + self.assertEqual('', user.user_root) + self.assertEqual(False, user.is_admin) + self.assertEqual(UserObject.USER_ROLE, user.role) + + user.user_root = self.testcases + user.refresh_repos() + user.commit() + self.listener.user_attr_changed.assert_called_with(user, {'user_root': ('', self.testcases)}) + self.listener.user_attr_changed.reset_mock() + user = UserObject.get_user('larry') + user.role = UserObject.ADMIN_ROLE + user.commit() + self.listener.user_attr_changed.assert_called_with( + user, {'role': (UserObject.USER_ROLE, UserObject.ADMIN_ROLE)} + ) + self.listener.user_attr_changed.reset_mock() + user = UserObject.get_user('larry') + user.email = 'larry@gmail.com' + user.commit() + self.listener.user_attr_changed.assert_called_with(user, {'email': ('', 'larry@gmail.com')}) + self.listener.user_attr_changed.reset_mock() + + self.assertEqual('larry@gmail.com', user.email) + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in user.repo_objs])) + self.assertEqual(self.testcases, user.user_root) + self.assertEqual(True, user.is_admin) + self.assertEqual(UserObject.ADMIN_ROLE, user.role) + + def test_set_role_null(self): + # Given a user + user = UserObject.add_user('annik', 'password') + user.add().commit() + # When trying to set the role to null + user.role = None + # Then an exception is raised + with self.assertRaises(Exception): + user.add().commit() + + @parameterized.expand( + [ + (-1, True), + (0, True), + (5, False), + (10, False), + (15, False), + ] + ) + def test_is_admin(self, role, expected_is_admin): + # Given a user + user = UserObject.add_user('annik', 'password') + # When setting the role value + user.role = role + user.commit() + # Then the is_admin value get updated too + self.assertEqual(expected_is_admin, user.is_admin) + + @parameterized.expand( + [ + (-1, True), + (0, True), + (5, True), + (10, False), + (15, False), + ] + ) + def test_is_maintainer(self, role, expected_is_maintainer): + # Given a user + user = UserObject.add_user('annik', 'password') + # When setting the role value + user.role = role + user.commit() + # Then the is_admin value get updated too + self.assertEqual(expected_is_maintainer, user.is_maintainer) + + def test_set_password_update(self): + # Given a user in database with a password + userobj = UserObject.add_user('annik', 'password') + userobj.commit() + self.listener.user_password_changed.reset_mock() + # When updating the user's password + userobj.set_password('new_password') + userobj.commit() + # Then password is SSHA + self.assertTrue(check_password('new_password', userobj.hash_password)) + # Check if listener called + self.listener.user_password_changed.assert_called_once_with(userobj) + + def test_delete_user(self): + # Given an existing user in database + userobj = UserObject.add_user('vicky') + userobj.commit() + self.assertIsNotNone(UserObject.get_user('vicky')) + # When deleting that user + userobj.delete() + userobj.commit() + # Then user it no longer in database + self.assertIsNone(UserObject.get_user('vicky')) + # Then listner was called + self.listener.user_deleted.assert_called_once_with('vicky') + + def test_set_password_empty(self): + """Expect error when trying to update password of invalid user.""" + userobj = UserObject.add_user('john') + userobj.commit() + with self.assertRaises(ValueError): + self.assertFalse(userobj.set_password('')) + + def test_disk_quota(self): + """ + Just make a call to the function. + """ + userobj = UserObject.get_user(self.USERNAME) + userobj.disk_quota + + def test_disk_usage(self): + """ + Just make a call to the function. + """ + userobj = UserObject.get_user(self.USERNAME) + disk_usage = userobj.disk_usage + self.assertIsInstance(disk_usage, int) + + def test_add_authorizedkey_without_file(self): + """ + Add an ssh key for a user without an authorizedkey file. + """ + # Read the pub key + key = self._read_ssh_key() + # Add the key to the user + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + + # validate + keys = list(userobj.authorizedkeys) + self.assertEqual(1, len(keys), "expecting one key") + self.assertEqual("3c:99:ed:a7:82:a8:71:09:2c:15:3d:78:4a:8c:11:99", keys[0].fingerprint) + + def test_add_authorizedkey_duplicate(self): + # Read the pub key + key = self._read_ssh_key() + # Add the key to the user + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + # Add the same key + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key) + userobj.commit() + + def test_add_authorizedkey_with_file(self): + """ + Add an ssh key for a user with an authorizedkey file. + """ + userobj = UserObject.get_user(self.USERNAME) + + # Create empty authorized_keys file + os.mkdir(os.path.join(userobj.user_root, '.ssh')) + filename = os.path.join(userobj.user_root, '.ssh', 'authorized_keys') + open(filename, 'a').close() + + # Read the pub key + key = self._read_ssh_key() + userobj.add_authorizedkey(key) + userobj.commit() + + # Validate + with open(filename, 'r') as fh: + self.assertEqual(key, fh.read()) + + def test_delete_authorizedkey_without_file(self): + """ + Remove an ssh key for a user without authorizedkey file. + """ + # Update user with ssh keys. + data = self._read_authorized_keys() + userobj = UserObject.get_user(self.USERNAME) + for k in authorizedkeys.read(StringIO(data)): + try: + userobj.add_authorizedkey(k.getvalue()) + except ValueError: + # Some ssh key in the testing file are not valid. + pass + + # Get the keys + keys = list(userobj.authorizedkeys) + self.assertEqual(2, len(keys)) + + # Remove a key + userobj.delete_authorizedkey("9a:f1:69:3c:bc:5a:cd:02:5e:33:bc:cd:c0:01:eb:4c") + userobj.commit() + + # Validate + keys = list(userobj.authorizedkeys) + self.assertEqual(1, len(keys)) + + def test_delete_authorizedkey_with_file(self): + """ + Remove an ssh key for a user with authorizedkey file. + """ + # Create authorized_keys file + data = self._read_authorized_keys() + userobj = UserObject.get_user(self.USERNAME) + os.mkdir(os.path.join(userobj.user_root, '.ssh')) + filename = os.path.join(userobj.user_root, '.ssh', 'authorized_keys') + with open(filename, 'w') as f: + f.write(data) + + # Get the keys + keys = list(userobj.authorizedkeys) + self.assertEqual(5, len(keys)) + + # Remove a key + userobj.delete_authorizedkey("9a:f1:69:3c:bc:5a:cd:02:5e:33:bc:cd:c0:01:eb:4c") + + # Validate + keys = list(userobj.authorizedkeys) + self.assertEqual(4, len(keys)) + + def test_repo_objs(self): + # Given a user with a list of repositories + userobj = UserObject.get_user(self.USERNAME) + repos = sorted(userobj.repo_objs, key=lambda r: r.name) + self.assertEqual(['broker-repo', 'testcases'], [r.name for r in repos]) + # When deleting a repository empty list + repos[1].delete() + repos[1].commit() + # Then the repository is removed from the list. + self.assertEqual(['broker-repo'], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_without_delete(self): + # Given a user with invalid repositories + userobj = UserObject.get_user(self.USERNAME) + RepoObject.query.delete() + RepoObject(userid=userobj.userid, repopath='invalid').add().commit() + self.assertEqual(['invalid'], sorted([r.name for r in userobj.repo_objs])) + # When updating the repository list without deletion + userobj.refresh_repos() + userobj.commit() + # Then the list invlaid the invalid repo and new repos + self.assertEqual(['broker-repo', 'invalid', 'testcases'], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_with_delete(self): + # Given a user with invalid repositories + userobj = UserObject.get_user(self.USERNAME) + RepoObject.query.delete() + RepoObject(userid=userobj.userid, repopath='invalid').add().commit() + self.assertEqual(['invalid'], sorted([r.name for r in userobj.repo_objs])) + # When updating the repository list without deletion + userobj.refresh_repos(delete=True) + userobj.commit() + # Then the list invlaid the invalid repo and new repos + userobj.expire() + self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_with_single_repo(self): + # Given a user with invalid repositories + userobj = UserObject.get_user(self.USERNAME) + userobj.user_root = os.path.join(self.testcases, 'testcases') + # When updating the repository list without deletion + userobj.refresh_repos(delete=True) + userobj.commit() + # Then the list invlaid the invalid repo and new repos + userobj.expire() + self.assertEqual([''], sorted([r.name for r in userobj.repo_objs])) + + def test_refresh_repos_with_empty_userroot(self): + # Given a user with valid repositories relative to root + userobj = UserObject.get_user(self.USERNAME) + for repo in userobj.repo_objs: + repo.repopath = self.testcases[1:] + '/' + repo.repopath + repo.add().commit() + userobj.user_root = '/' + userobj.add().commit() + self.assertEqual(['interrupted', 'ok'], sorted([r.status[0] for r in userobj.repo_objs])) + # When updating it's userroot directory to an empty value + userobj.user_root = '' + userobj.add().commit() + UserObject.session.expire_all() + # Then close session + cherrypy.tools.db.on_end_resource() + # Then repo status is "broken" + userobj = UserObject.get_user(self.USERNAME) + self.assertFalse(userobj.valid_user_root()) + self.assertEqual(['failed', 'failed'], [r.status[0] for r in userobj.repo_objs]) +``` + +## `rdiffweb/core/model/tests/test_user.py` — `function:UserObjectTest.test_add_authorizedkey_duplicate` (lines 325-335) + +```python + def test_add_authorizedkey_duplicate(self): + # Read the pub key + key = self._read_ssh_key() + # Add the key to the user + userobj = UserObject.get_user(self.USERNAME) + userobj.add_authorizedkey(key) + userobj.commit() + # Add the same key + with self.assertRaises(DuplicateSSHKeyError): + userobj.add_authorizedkey(key) + userobj.commit() +``` + +## `rdiffweb/core/model/tests/test_user.py` — `function:UserObjectTest.test_add_authorizedkey_with_file` (lines 337-355) + +```python + def test_add_authorizedkey_with_file(self): + """ + Add an ssh key for a user with an authorizedkey file. + """ + userobj = UserObject.get_user(self.USERNAME) + + # Create empty authorized_keys file + os.mkdir(os.path.join(userobj.user_root, '.ssh')) + filename = os.path.join(userobj.user_root, '.ssh', 'authorized_keys') + open(filename, 'a').close() + + # Read the pub key + key = self._read_ssh_key() + userobj.add_authorizedkey(key) + userobj.commit() + + # Validate + with open(filename, 'r') as fh: + self.assertEqual(key, fh.read()) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d65201064b28b6a89ce011ba1ee780253d3757a6 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/task.json @@ -0,0 +1,66 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-cb3f3f84ff4550031205", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-cb3f3f84ff4550031205", + "project_id": "pyvul__ikus060__rdiffweb", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "rdiffweb/core/model/__init__.py", + "rdiffweb/core/model/_sshkey.py", + "rdiffweb/core/model/_user.py", + "rdiffweb/core/model/tests/test_user.py" + ], + "patch_units": { + "before": [ + "module:@22", + "module:@23", + "module:@27", + "module:@28", + "module:@19", + "class:UserObject", + "function:UserObject.add_authorizedkey", + "class:UserObjectTest", + "function:UserObjectTest.test_add_authorizedkey_duplicate", + "function:UserObjectTest.test_add_authorizedkey_with_file" + ], + "after": [ + "function:db_after_create", + "module:@22", + "module:@27", + "module:@19", + "module:@33", + "class:UserObject", + "function:UserObject.add_authorizedkey", + "class:UserObjectTest", + "function:UserObjectTest.test_add_authorizedkey_duplicate", + "function:UserObjectTest.test_add_authorizedkey_duplicate_new_comment", + "function:UserObjectTest.test_add_authorizedkey_duplicate_new_user" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/b105431118758d5fc81074acd31302e52ce280c69f32cd7b72199adc30da4c28/database", + "cache_key": "b105431118758d5fc81074acd31302e52ce280c69f32cd7b72199adc30da4c28", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/89a2f292d736abdb3c9f59649bf2ddd0f941069b129ed959e36c371a2b47d422/database", + "cache_key": "89a2f292d736abdb3c9f59649bf2ddd0f941069b129ed959e36c371a2b47d422", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/1b8f80f5c99bf916a656f03c56b87928f4c2202ce53851102eff56ffb3a1c99d/database", + "cache_key": "1b8f80f5c99bf916a656f03c56b87928f4c2202ce53851102eff56ffb3a1c99d", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-cb3f3f84ff4550031205/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-cb3f3f84ff4550031205/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-cb3f3f84ff4550031205/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..43f1a08c2bb887b7a8e4ce9b02477fff1d52b1ca --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/patch.diff @@ -0,0 +1,45 @@ +diff --git a/jupyter_server/base/handlers.py b/jupyter_server/base/handlers.py +index e6e6b3246..b1b783cca 100644 +--- a/jupyter_server/base/handlers.py ++++ b/jupyter_server/base/handlers.py +@@ -10,7 +10,6 @@ import json + import mimetypes + import os + import re +-import traceback + import types + import warnings + from http.client import responses +@@ -748,7 +747,9 @@ class APIHandler(JupyterHandler): + else: + reply["message"] = "Unhandled error" + reply["reason"] = None +- reply["traceback"] = "".join(traceback.format_exception(*exc_info)) ++ # backward-compatibility: traceback field is present, ++ # but always empty ++ reply["traceback"] = "" + self.log.warning("wrote error: %r", reply["message"], exc_info=True) + self.finish(json.dumps(reply)) + +diff --git a/jupyter_server/services/kernels/handlers.py b/jupyter_server/services/kernels/handlers.py +index 2fb753e93..217f0c9cc 100644 +--- a/jupyter_server/services/kernels/handlers.py ++++ b/jupyter_server/services/kernels/handlers.py +@@ -5,7 +5,6 @@ Preliminary documentation at https://github.com/ipython/ipython/wiki/IPEP-16%3A- + # Copyright (c) Jupyter Development Team. + # Distributed under the terms of the Modified BSD License. + import json +-from traceback import format_tb + + try: + from jupyter_client.jsonutil import json_default +@@ -102,8 +101,7 @@ class KernelActionHandler(KernelsAPIHandler): + except Exception as e: + message = "Exception restarting kernel" + self.log.error(message, exc_info=True) +- traceback = format_tb(e.__traceback__) +- self.write(json.dumps({"message": message, "traceback": traceback})) ++ self.write(json.dumps({"message": message, "traceback": ""})) + self.set_status(500) + else: + model = await ensure_async(km.kernel_model(kernel_id)) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..6a67c3c660e81de4beb477ea58191ef384785c87 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/post_context.md @@ -0,0 +1,198 @@ +# Patch-overlapping Python context after the fix + +## `jupyter_server/base/handlers.py` — `class:APIHandler` (lines 725-833) + +```python +class APIHandler(JupyterHandler): + """Base class for API handlers""" + + async def prepare(self) -> None: + """Prepare an API response.""" + await super().prepare() + if not self.check_origin(): + raise web.HTTPError(404) + + def write_error(self, status_code: int, **kwargs: Any) -> None: + """APIHandler errors are JSON, not human pages""" + self.set_header("Content-Type", "application/json") + message = responses.get(status_code, "Unknown HTTP Error") + reply: dict[str, Any] = { + "message": message, + } + exc_info = kwargs.get("exc_info") + if exc_info: + e = exc_info[1] + if isinstance(e, HTTPError): + reply["message"] = e.log_message or message + reply["reason"] = e.reason + else: + reply["message"] = "Unhandled error" + reply["reason"] = None + # backward-compatibility: traceback field is present, + # but always empty + reply["traceback"] = "" + self.log.warning("wrote error: %r", reply["message"], exc_info=True) + self.finish(json.dumps(reply)) + + def get_login_url(self) -> str: + """Get the login url.""" + # if get_login_url is invoked in an API handler, + # that means @web.authenticated is trying to trigger a redirect. + # instead of redirecting, raise 403 instead. + if not self.current_user: + raise web.HTTPError(403) + return super().get_login_url() + + @property + def content_security_policy(self) -> str: + csp = "; ".join( + [ + super().content_security_policy, + "default-src 'none'", + ] + ) + return csp + + # set _track_activity = False on API handlers that shouldn't track activity + _track_activity = True + + def update_api_activity(self) -> None: + """Update last_activity of API requests""" + # record activity of authenticated requests + if ( + self._track_activity + and getattr(self, "_jupyter_current_user", None) + and self.get_argument("no_track_activity", None) is None + ): + self.settings["api_last_activity"] = utcnow() + + def finish(self, *args: Any, **kwargs: Any) -> Future[Any]: + """Finish an API response.""" + self.update_api_activity() + # Allow caller to indicate content-type... + set_content_type = kwargs.pop("set_content_type", "application/json") + self.set_header("Content-Type", set_content_type) + return super().finish(*args, **kwargs) + + def options(self, *args: Any, **kwargs: Any) -> None: + """Get the options.""" + if "Access-Control-Allow-Headers" in self.settings.get("headers", {}): + self.set_header( + "Access-Control-Allow-Headers", + self.settings["headers"]["Access-Control-Allow-Headers"], + ) + else: + self.set_header( + "Access-Control-Allow-Headers", + "accept, content-type, authorization, x-xsrftoken", + ) + self.set_header("Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE, OPTIONS") + + # if authorization header is requested, + # that means the request is token-authenticated. + # avoid browser-side rejection of the preflight request. + # only allow this exception if allow_origin has not been specified + # and Jupyter server authentication is enabled. + # If the token is not valid, the 'real' request will still be rejected. + requested_headers = self.request.headers.get("Access-Control-Request-Headers", "").split( + "," + ) + if ( + requested_headers + and any(h.strip().lower() == "authorization" for h in requested_headers) + and ( + # FIXME: it would be even better to check specifically for token-auth, + # but there is currently no API for this. + self.login_available + ) + and ( + self.allow_origin + or self.allow_origin_pat + or "Access-Control-Allow-Origin" in self.settings.get("headers", {}) + ) + ): + self.set_header("Access-Control-Allow-Origin", self.request.headers.get("Origin", "")) +``` + +## `jupyter_server/base/handlers.py` — `function:APIHandler.write_error` (lines 734-754) + +```python + def write_error(self, status_code: int, **kwargs: Any) -> None: + """APIHandler errors are JSON, not human pages""" + self.set_header("Content-Type", "application/json") + message = responses.get(status_code, "Unknown HTTP Error") + reply: dict[str, Any] = { + "message": message, + } + exc_info = kwargs.get("exc_info") + if exc_info: + e = exc_info[1] + if isinstance(e, HTTPError): + reply["message"] = e.log_message or message + reply["reason"] = e.reason + else: + reply["message"] = "Unhandled error" + reply["reason"] = None + # backward-compatibility: traceback field is present, + # but always empty + reply["traceback"] = "" + self.log.warning("wrote error: %r", reply["message"], exc_info=True) + self.finish(json.dumps(reply)) +``` + +## `jupyter_server/base/handlers.py` — `module:@13` (lines 13-13) + +```python +import types +``` + +## `jupyter_server/services/kernels/handlers.py` — `class:KernelActionHandler` (lines 87-109) + +```python +class KernelActionHandler(KernelsAPIHandler): + """A kernel action API handler.""" + + @web.authenticated + @authorized + async def post(self, kernel_id, action): + """Interrupt or restart a kernel.""" + km = self.kernel_manager + if action == "interrupt": + await ensure_async(km.interrupt_kernel(kernel_id)) # type:ignore[func-returns-value] + self.set_status(204) + if action == "restart": + try: + await km.restart_kernel(kernel_id) + except Exception as e: + message = "Exception restarting kernel" + self.log.error(message, exc_info=True) + self.write(json.dumps({"message": message, "traceback": ""})) + self.set_status(500) + else: + model = await ensure_async(km.kernel_model(kernel_id)) + self.write(json.dumps(model, default=json_default)) + self.finish() +``` + +## `jupyter_server/services/kernels/handlers.py` — `function:KernelActionHandler.post` (lines 90-109) + +```python + async def post(self, kernel_id, action): + """Interrupt or restart a kernel.""" + km = self.kernel_manager + if action == "interrupt": + await ensure_async(km.interrupt_kernel(kernel_id)) # type:ignore[func-returns-value] + self.set_status(204) + if action == "restart": + try: + await km.restart_kernel(kernel_id) + except Exception as e: + message = "Exception restarting kernel" + self.log.error(message, exc_info=True) + self.write(json.dumps({"message": message, "traceback": ""})) + self.set_status(500) + else: + model = await ensure_async(km.kernel_model(kernel_id)) + self.write(json.dumps(model, default=json_default)) + self.finish() +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..34b665135cdc25cee679c733f13500e7d6eae4d3 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/pre_context.md @@ -0,0 +1,202 @@ +# Patch-overlapping Python context before the fix + +## `jupyter_server/base/handlers.py` — `class:APIHandler` (lines 726-832) + +```python +class APIHandler(JupyterHandler): + """Base class for API handlers""" + + async def prepare(self) -> None: + """Prepare an API response.""" + await super().prepare() + if not self.check_origin(): + raise web.HTTPError(404) + + def write_error(self, status_code: int, **kwargs: Any) -> None: + """APIHandler errors are JSON, not human pages""" + self.set_header("Content-Type", "application/json") + message = responses.get(status_code, "Unknown HTTP Error") + reply: dict[str, Any] = { + "message": message, + } + exc_info = kwargs.get("exc_info") + if exc_info: + e = exc_info[1] + if isinstance(e, HTTPError): + reply["message"] = e.log_message or message + reply["reason"] = e.reason + else: + reply["message"] = "Unhandled error" + reply["reason"] = None + reply["traceback"] = "".join(traceback.format_exception(*exc_info)) + self.log.warning("wrote error: %r", reply["message"], exc_info=True) + self.finish(json.dumps(reply)) + + def get_login_url(self) -> str: + """Get the login url.""" + # if get_login_url is invoked in an API handler, + # that means @web.authenticated is trying to trigger a redirect. + # instead of redirecting, raise 403 instead. + if not self.current_user: + raise web.HTTPError(403) + return super().get_login_url() + + @property + def content_security_policy(self) -> str: + csp = "; ".join( + [ + super().content_security_policy, + "default-src 'none'", + ] + ) + return csp + + # set _track_activity = False on API handlers that shouldn't track activity + _track_activity = True + + def update_api_activity(self) -> None: + """Update last_activity of API requests""" + # record activity of authenticated requests + if ( + self._track_activity + and getattr(self, "_jupyter_current_user", None) + and self.get_argument("no_track_activity", None) is None + ): + self.settings["api_last_activity"] = utcnow() + + def finish(self, *args: Any, **kwargs: Any) -> Future[Any]: + """Finish an API response.""" + self.update_api_activity() + # Allow caller to indicate content-type... + set_content_type = kwargs.pop("set_content_type", "application/json") + self.set_header("Content-Type", set_content_type) + return super().finish(*args, **kwargs) + + def options(self, *args: Any, **kwargs: Any) -> None: + """Get the options.""" + if "Access-Control-Allow-Headers" in self.settings.get("headers", {}): + self.set_header( + "Access-Control-Allow-Headers", + self.settings["headers"]["Access-Control-Allow-Headers"], + ) + else: + self.set_header( + "Access-Control-Allow-Headers", + "accept, content-type, authorization, x-xsrftoken", + ) + self.set_header("Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE, OPTIONS") + + # if authorization header is requested, + # that means the request is token-authenticated. + # avoid browser-side rejection of the preflight request. + # only allow this exception if allow_origin has not been specified + # and Jupyter server authentication is enabled. + # If the token is not valid, the 'real' request will still be rejected. + requested_headers = self.request.headers.get("Access-Control-Request-Headers", "").split( + "," + ) + if ( + requested_headers + and any(h.strip().lower() == "authorization" for h in requested_headers) + and ( + # FIXME: it would be even better to check specifically for token-auth, + # but there is currently no API for this. + self.login_available + ) + and ( + self.allow_origin + or self.allow_origin_pat + or "Access-Control-Allow-Origin" in self.settings.get("headers", {}) + ) + ): + self.set_header("Access-Control-Allow-Origin", self.request.headers.get("Origin", "")) +``` + +## `jupyter_server/base/handlers.py` — `function:APIHandler.write_error` (lines 735-753) + +```python + def write_error(self, status_code: int, **kwargs: Any) -> None: + """APIHandler errors are JSON, not human pages""" + self.set_header("Content-Type", "application/json") + message = responses.get(status_code, "Unknown HTTP Error") + reply: dict[str, Any] = { + "message": message, + } + exc_info = kwargs.get("exc_info") + if exc_info: + e = exc_info[1] + if isinstance(e, HTTPError): + reply["message"] = e.log_message or message + reply["reason"] = e.reason + else: + reply["message"] = "Unhandled error" + reply["reason"] = None + reply["traceback"] = "".join(traceback.format_exception(*exc_info)) + self.log.warning("wrote error: %r", reply["message"], exc_info=True) + self.finish(json.dumps(reply)) +``` + +## `jupyter_server/base/handlers.py` — `module:@13` (lines 13-13) + +```python +import traceback +``` + +## `jupyter_server/services/kernels/handlers.py` — `class:KernelActionHandler` (lines 88-111) + +```python +class KernelActionHandler(KernelsAPIHandler): + """A kernel action API handler.""" + + @web.authenticated + @authorized + async def post(self, kernel_id, action): + """Interrupt or restart a kernel.""" + km = self.kernel_manager + if action == "interrupt": + await ensure_async(km.interrupt_kernel(kernel_id)) # type:ignore[func-returns-value] + self.set_status(204) + if action == "restart": + try: + await km.restart_kernel(kernel_id) + except Exception as e: + message = "Exception restarting kernel" + self.log.error(message, exc_info=True) + traceback = format_tb(e.__traceback__) + self.write(json.dumps({"message": message, "traceback": traceback})) + self.set_status(500) + else: + model = await ensure_async(km.kernel_model(kernel_id)) + self.write(json.dumps(model, default=json_default)) + self.finish() +``` + +## `jupyter_server/services/kernels/handlers.py` — `function:KernelActionHandler.post` (lines 91-111) + +```python + async def post(self, kernel_id, action): + """Interrupt or restart a kernel.""" + km = self.kernel_manager + if action == "interrupt": + await ensure_async(km.interrupt_kernel(kernel_id)) # type:ignore[func-returns-value] + self.set_status(204) + if action == "restart": + try: + await km.restart_kernel(kernel_id) + except Exception as e: + message = "Exception restarting kernel" + self.log.error(message, exc_info=True) + traceback = format_tb(e.__traceback__) + self.write(json.dumps({"message": message, "traceback": traceback})) + self.set_status(500) + else: + model = await ensure_async(km.kernel_model(kernel_id)) + self.write(json.dumps(model, default=json_default)) + self.finish() +``` + +## `jupyter_server/services/kernels/handlers.py` — `module:@8` (lines 8-8) + +```python +from traceback import format_tb +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1be661e16eb6de634e11d9f4a9c8afff20a15651 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/task.json @@ -0,0 +1,54 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-d005a7cf5935ac7e7aae", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-d005a7cf5935ac7e7aae", + "project_id": "pyvul__jupyter-server__jupyter_server", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "jupyter_server/base/handlers.py", + "jupyter_server/services/kernels/handlers.py" + ], + "patch_units": { + "before": [ + "class:APIHandler", + "function:APIHandler.write_error", + "module:@13", + "class:KernelActionHandler", + "function:KernelActionHandler.post", + "module:@8" + ], + "after": [ + "class:APIHandler", + "function:APIHandler.write_error", + "module:@13", + "class:KernelActionHandler", + "function:KernelActionHandler.post" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/b64a19b97baa0ccdbe5b40540f40e553adaa3f88e44f223936afd33bafc01b97/database", + "cache_key": "b64a19b97baa0ccdbe5b40540f40e553adaa3f88e44f223936afd33bafc01b97", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/4a63c032f2e58cff5581c9dfdae450535c4c7ecc195a2938763e30a27f37a1d6/database", + "cache_key": "4a63c032f2e58cff5581c9dfdae450535c4c7ecc195a2938763e30a27f37a1d6", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/5cd7ddec99c106b4a5ddd7bc057c6a28b35cb219bf995cf90754a2d27152d5ec/database", + "cache_key": "5cd7ddec99c106b4a5ddd7bc057c6a28b35cb219bf995cf90754a2d27152d5ec", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-d005a7cf5935ac7e7aae/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-d005a7cf5935ac7e7aae/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d005a7cf5935ac7e7aae/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d4c1d81cf8d161274427f6b0581064b4765dd970 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/patch.diff @@ -0,0 +1,24 @@ +diff --git a/apkleaks/apkleaks.py b/apkleaks/apkleaks.py +index c51c75e..e1e084f 100644 +--- a/apkleaks/apkleaks.py ++++ b/apkleaks/apkleaks.py +@@ -2,6 +2,7 @@ + from apkleaks.colors import clr + from contextlib import closing + from distutils.spawn import find_executable ++from pipes import quote + from pyaxmlparser import APK + from urllib.request import urlopen + from zipfile import ZipFile +@@ -84,8 +85,9 @@ class APKLeaks: + classes.write(zipped.read("classes.dex")) + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) +- dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir) +- os.system(dec) ++ args = [self.jadx, dex, "-d", self.tempdir, "--deobf"] ++ comm = "%s" % (" ".join(quote(arg) for arg in args)) ++ os.system(comm) + return self.tempdir + + def unique(self, list): diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..7c62c473b47ef5e347086115727aae701b087d5a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/post_context.md @@ -0,0 +1,155 @@ +# Patch-overlapping Python context after the fix + +## `apkleaks/apkleaks.py` — `class:APKLeaks` (lines 21-145) + +```python +class APKLeaks: + def __init__(self, args): + self.file = args.file + self.prefix = "apkleaks-" + self.tempdir = tempfile.mkdtemp(prefix=self.prefix) + self.main_dir = os.path.dirname(os.path.realpath(__file__)) + self.output = tempfile.mkstemp(suffix=".txt", prefix=self.prefix)[1] if args.output is None else args.output + self.pattern = self.main_dir + "/../config/regexes.json" if args.pattern is None else args.pattern + self.jadx = find_executable("jadx") if find_executable("jadx") is not None else self.main_dir + "/../jadx/bin/jadx%s" % (".bat" if os.name == "nt" else "") + logging.config.dictConfig({"version": 1, "disable_existing_loggers": True}) + + def apk_info(self): + return APK(self.file) + + def dependencies(self): + exter = "https://github.com/skylot/jadx/releases/download/v1.2.0/jadx-1.2.0.zip" + with closing(urlopen(exter)) as jadx: + with ZipFile(io.BytesIO(jadx.read())) as zfile: + zfile.extractall(self.main_dir + "/../jadx") + os.chmod(self.jadx, 33268) + + def write(self, message, color): + sys.stdout.write("%s%s%s" % (color, message, clr.ENDC)) + + def writeln(self, message, color): + self.write(message + "\n", color) + + def integrity(self): + if os.path.exists(self.jadx) is False: + self.writeln("Can't find jadx binary.", clr.WARNING) + valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} + while True: + self.write("Do you want to download jadx? (Y/n) ", clr.OKBLUE) + choice = input().lower() + if choice == "": + choice = valid["y"] + break + elif choice in valid: + choice = valid[choice] + break + else: + self.writeln("\nPlease respond with 'yes' or 'no' (or 'y' or 'n').", clr.WARNING) + if choice: + self.writeln("** Downloading jadx...\n", clr.OKBLUE) + self.dependencies() + else: + sys.exit(self.writeln("Aborted.", clr.FAIL)) + + if os.path.isfile(self.file) is True: + try: + self.apk = self.apk_info() + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) + else: + return self.apk + else: + sys.exit(self.writeln("It's not a valid file!", clr.WARNING)) + + def decompile(self): + self.writeln("** Decompiling APK...", clr.OKBLUE) + with ZipFile(self.file) as zipped: + try: + dex = self.tempdir + "/" + self.apk.package + ".dex" + with open(dex, "wb") as classes: + classes.write(zipped.read("classes.dex")) + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) + args = [self.jadx, dex, "-d", self.tempdir, "--deobf"] + comm = "%s" % (" ".join(quote(arg) for arg in args)) + os.system(comm) + return self.tempdir + + def unique(self, list): + x = numpy.array(list) + return (numpy.unique(x)) + + def finder(self, pattern, path): + matcher = re.compile(pattern) + found = [] + for path, _, files in os.walk(path): + for fn in files: + filepath = os.path.join(path, fn) + if mimetypes.guess_type(filepath)[0] is None: + continue + with open(filepath) as handle: + for lineno, line in enumerate(handle): + mo = matcher.search(line) + if mo: + found.append(mo.group()) + return self.unique(found) + + def extract(self, name, matches): + output = open(self.output, "a+") + if matches: + stdout = ("[%s]" % (name)) + self.writeln("\n" + stdout, clr.OKGREEN) + output.write(stdout + "\n") + for secret in matches: + if name == "LinkFinder" and re.match(r"^.(L[a-z]|application|audio|fonts|image|layout|multipart|plain|text|video).*\/.+", secret) is not None: + continue + stdout = ("- %s" % (secret)) + print(stdout) + output.write(stdout + "\n") + output.write("\n") + output.close() + + def scanning(self): + self.writeln("\n** Scanning against '%s'" % (self.apk.package), clr.OKBLUE) + with open(self.pattern) as regexes: + regex = json.load(regexes) + for name, pattern in regex.items(): + if isinstance(pattern, list): + for pattern in pattern: + thread = threading.Thread(target = self.extract, args = (name, self.finder(pattern, self.tempdir))) + thread.start() + else: + thread = threading.Thread(target = self.extract, args = (name, self.finder(pattern, self.tempdir))) + thread.start() + + def __del__(self): + print("%s\n** Results saved into '%s%s%s%s'%s" % (clr.OKBLUE, clr.ENDC, clr.OKGREEN, self.output, clr.OKBLUE, clr.ENDC)) + try: + shutil.rmtree(self.tempdir) + except Exception: + return +``` + +## `apkleaks/apkleaks.py` — `function:APKLeaks.decompile` (lines 79-91) + +```python + def decompile(self): + self.writeln("** Decompiling APK...", clr.OKBLUE) + with ZipFile(self.file) as zipped: + try: + dex = self.tempdir + "/" + self.apk.package + ".dex" + with open(dex, "wb") as classes: + classes.write(zipped.read("classes.dex")) + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) + args = [self.jadx, dex, "-d", self.tempdir, "--deobf"] + comm = "%s" % (" ".join(quote(arg) for arg in args)) + os.system(comm) + return self.tempdir +``` + +## `apkleaks/apkleaks.py` — `module:@5` (lines 5-5) + +```python +from pipes import quote +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..0b9acc24260b7b701fa539231c787ded9c9d2017 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/pre_context.md @@ -0,0 +1,153 @@ +# Patch-overlapping Python context before the fix + +## `apkleaks/apkleaks.py` — `class:APKLeaks` (lines 20-143) + +```python +class APKLeaks: + def __init__(self, args): + self.file = args.file + self.prefix = "apkleaks-" + self.tempdir = tempfile.mkdtemp(prefix=self.prefix) + self.main_dir = os.path.dirname(os.path.realpath(__file__)) + self.output = tempfile.mkstemp(suffix=".txt", prefix=self.prefix)[1] if args.output is None else args.output + self.pattern = self.main_dir + "/../config/regexes.json" if args.pattern is None else args.pattern + self.jadx = find_executable("jadx") if find_executable("jadx") is not None else self.main_dir + "/../jadx/bin/jadx%s" % (".bat" if os.name == "nt" else "") + logging.config.dictConfig({"version": 1, "disable_existing_loggers": True}) + + def apk_info(self): + return APK(self.file) + + def dependencies(self): + exter = "https://github.com/skylot/jadx/releases/download/v1.2.0/jadx-1.2.0.zip" + with closing(urlopen(exter)) as jadx: + with ZipFile(io.BytesIO(jadx.read())) as zfile: + zfile.extractall(self.main_dir + "/../jadx") + os.chmod(self.jadx, 33268) + + def write(self, message, color): + sys.stdout.write("%s%s%s" % (color, message, clr.ENDC)) + + def writeln(self, message, color): + self.write(message + "\n", color) + + def integrity(self): + if os.path.exists(self.jadx) is False: + self.writeln("Can't find jadx binary.", clr.WARNING) + valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} + while True: + self.write("Do you want to download jadx? (Y/n) ", clr.OKBLUE) + choice = input().lower() + if choice == "": + choice = valid["y"] + break + elif choice in valid: + choice = valid[choice] + break + else: + self.writeln("\nPlease respond with 'yes' or 'no' (or 'y' or 'n').", clr.WARNING) + if choice: + self.writeln("** Downloading jadx...\n", clr.OKBLUE) + self.dependencies() + else: + sys.exit(self.writeln("Aborted.", clr.FAIL)) + + if os.path.isfile(self.file) is True: + try: + self.apk = self.apk_info() + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) + else: + return self.apk + else: + sys.exit(self.writeln("It's not a valid file!", clr.WARNING)) + + def decompile(self): + self.writeln("** Decompiling APK...", clr.OKBLUE) + with ZipFile(self.file) as zipped: + try: + dex = self.tempdir + "/" + self.apk.package + ".dex" + with open(dex, "wb") as classes: + classes.write(zipped.read("classes.dex")) + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) + dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir) + os.system(dec) + return self.tempdir + + def unique(self, list): + x = numpy.array(list) + return (numpy.unique(x)) + + def finder(self, pattern, path): + matcher = re.compile(pattern) + found = [] + for path, _, files in os.walk(path): + for fn in files: + filepath = os.path.join(path, fn) + if mimetypes.guess_type(filepath)[0] is None: + continue + with open(filepath) as handle: + for lineno, line in enumerate(handle): + mo = matcher.search(line) + if mo: + found.append(mo.group()) + return self.unique(found) + + def extract(self, name, matches): + output = open(self.output, "a+") + if matches: + stdout = ("[%s]" % (name)) + self.writeln("\n" + stdout, clr.OKGREEN) + output.write(stdout + "\n") + for secret in matches: + if name == "LinkFinder" and re.match(r"^.(L[a-z]|application|audio|fonts|image|layout|multipart|plain|text|video).*\/.+", secret) is not None: + continue + stdout = ("- %s" % (secret)) + print(stdout) + output.write(stdout + "\n") + output.write("\n") + output.close() + + def scanning(self): + self.writeln("\n** Scanning against '%s'" % (self.apk.package), clr.OKBLUE) + with open(self.pattern) as regexes: + regex = json.load(regexes) + for name, pattern in regex.items(): + if isinstance(pattern, list): + for pattern in pattern: + thread = threading.Thread(target = self.extract, args = (name, self.finder(pattern, self.tempdir))) + thread.start() + else: + thread = threading.Thread(target = self.extract, args = (name, self.finder(pattern, self.tempdir))) + thread.start() + + def __del__(self): + print("%s\n** Results saved into '%s%s%s%s'%s" % (clr.OKBLUE, clr.ENDC, clr.OKGREEN, self.output, clr.OKBLUE, clr.ENDC)) + try: + shutil.rmtree(self.tempdir) + except Exception: + return +``` + +## `apkleaks/apkleaks.py` — `function:APKLeaks.decompile` (lines 78-89) + +```python + def decompile(self): + self.writeln("** Decompiling APK...", clr.OKBLUE) + with ZipFile(self.file) as zipped: + try: + dex = self.tempdir + "/" + self.apk.package + ".dex" + with open(dex, "wb") as classes: + classes.write(zipped.read("classes.dex")) + except Exception as e: + sys.exit(self.writeln(str(e), clr.WARNING)) + dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir) + os.system(dec) + return self.tempdir +``` + +## `apkleaks/apkleaks.py` — `module:@5` (lines 5-5) + +```python +from pyaxmlparser import APK +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ee3b07fd5930eefbf39252d5e93d8ed3495427d2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/task.json @@ -0,0 +1,48 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-d38a3c1956e86350a0c7", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-d38a3c1956e86350a0c7", + "project_id": "pyvul__dwisiswant0__apkleaks", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "apkleaks/apkleaks.py" + ], + "patch_units": { + "before": [ + "class:APKLeaks", + "function:APKLeaks.decompile", + "module:@5" + ], + "after": [ + "class:APKLeaks", + "function:APKLeaks.decompile", + "module:@5" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/f295840aed3766f2d8a44898871d6f7c5305e1117c7a33e855eb8f16645e1630/database", + "cache_key": "f295840aed3766f2d8a44898871d6f7c5305e1117c7a33e855eb8f16645e1630", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/5ee729b1f4b6b69c4605d02f0e31fe0e5adbb8e4237ba0e6d6d12e95ac19554c/database", + "cache_key": "5ee729b1f4b6b69c4605d02f0e31fe0e5adbb8e4237ba0e6d6d12e95ac19554c", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/1acec812a6c38893972d7be72d67f086a2de1d062ba9af17ed8ca1e8dc098a4a/database", + "cache_key": "1acec812a6c38893972d7be72d67f086a2de1d062ba9af17ed8ca1e8dc098a4a", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-d38a3c1956e86350a0c7/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-d38a3c1956e86350a0c7/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-d38a3c1956e86350a0c7/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..50de1ddcd81984dce28b0cda98e62a0437b57b1a --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/patch.diff @@ -0,0 +1,136 @@ +diff --git a/web/pgadmin/misc/__init__.py b/web/pgadmin/misc/__init__.py +index 15adccf51..451271e07 100644 +--- a/web/pgadmin/misc/__init__.py ++++ b/web/pgadmin/misc/__init__.py +@@ -13,7 +13,8 @@ from pgadmin.utils import driver + from flask import url_for, render_template, Response, request, current_app + from flask_babel import gettext + from flask_security import login_required +-from pgadmin.utils import PgAdminModule, replace_binary_path ++from pgadmin.utils import PgAdminModule, replace_binary_path, \ ++ get_binary_path_versions + from pgadmin.utils.csrf import pgCSRFProtect + from pgadmin.utils.session import cleanup_session_files + from pgadmin.misc.themes import get_all_themes +@@ -254,37 +255,13 @@ def validate_binary_path(): + + version_str = '' + if 'utility_path' in data and data['utility_path'] is not None: +- # Check if "$DIR" present in binary path +- binary_path = replace_binary_path(data['utility_path']) +- +- for utility in UTILITIES_ARRAY: +- full_path = os.path.abspath( +- os.path.join(binary_path, +- (utility if os.name != 'nt' else +- (utility + '.exe')))) +- +- try: +- # if path doesn't exist raise exception +- if not os.path.exists(binary_path): +- current_app.logger.warning('Invalid binary path.') +- raise Exception() +- # escape double quotes to avoid command injection. +- # Get the output of the '--version' command +- version_string = \ +- subprocess.getoutput(r'"{0}" --version'.format( +- full_path.replace('"', '""'))) +- # Get the version number by splitting the result string +- version_string.split(") ", 1)[1].split('.', 1)[0] +- except Exception: ++ binary_versions = get_binary_path_versions(data['utility_path']) ++ for utility, version in binary_versions.items(): ++ if version is None: + version_str += "" + utility + ": " + \ + "not found on the specified binary path.
" +- continue +- +- # Replace the name of the utility from the result to avoid +- # duplicate name. +- result_str = version_string.replace(utility, '') +- +- version_str += "" + utility + ": " + result_str + "
" ++ else: ++ version_str += "" + utility + ": " + version + "
" + else: + return precondition_required(gettext('Invalid binary path.')) + +diff --git a/web/pgadmin/utils/__init__.py b/web/pgadmin/utils/__init__.py +index 0d27fee6b..36eeefecf 100644 +--- a/web/pgadmin/utils/__init__.py ++++ b/web/pgadmin/utils/__init__.py +@@ -351,6 +351,40 @@ def get_server(sid): + return server + + ++def get_binary_path_versions(binary_path: str) -> dict: ++ ret = {} ++ binary_path = os.path.abspath( ++ replace_binary_path(binary_path) ++ ) ++ ++ for utility in UTILITIES_ARRAY: ++ ret[utility] = None ++ full_path = os.path.join(binary_path, ++ (utility if os.name != 'nt' else ++ (utility + '.exe'))) ++ ++ try: ++ # if path doesn't exist raise exception ++ if not os.path.isdir(binary_path): ++ current_app.logger.warning('Invalid binary path.') ++ raise Exception() ++ # Get the output of the '--version' command ++ cmd = subprocess.run( ++ [full_path, '--version'], ++ shell=False, ++ capture_output=True, ++ text=True ++ ) ++ if cmd.returncode == 0: ++ ret[utility] = cmd.stdout.split(") ", 1)[1].strip() ++ else: ++ raise Exception() ++ except Exception as _: ++ continue ++ ++ return ret ++ ++ + def set_binary_path(binary_path, bin_paths, server_type, + version_number=None, set_as_default=False): + """ +@@ -358,28 +392,13 @@ def set_binary_path(binary_path, bin_paths, server_type, + default binary path. + """ + path_with_dir = binary_path if "$DIR" in binary_path else None ++ binary_versions = get_binary_path_versions(binary_path) + +- # Check if "$DIR" present in binary path +- binary_path = replace_binary_path(binary_path) +- +- for utility in UTILITIES_ARRAY: +- full_path = os.path.abspath( +- os.path.join(binary_path, (utility if os.name != 'nt' else +- (utility + '.exe')))) +- ++ for utility, version in binary_versions.items(): ++ version_number = version if version_number is None else version_number ++ if version_number.find('.'): ++ version_number = version_number.split('.', 1)[0] + try: +- # if version_number is provided then no need to fetch it. +- if version_number is None: +- # Get the output of the '--version' command +- version_string = \ +- subprocess.getoutput('"{0}" --version'.format(full_path)) +- +- # Get the version number by splitting the result string +- version_number = \ +- version_string.split(") ", 1)[1].split('.', 1)[0] +- elif version_number.find('.'): +- version_number = version_number.split('.', 1)[0] +- + # Get the paths array based on server type + if 'pg_bin_paths' in bin_paths or 'as_bin_paths' in bin_paths: + paths_array = bin_paths['pg_bin_paths'] diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..e33564b6f029514524da89c9bd543479dd50db61 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/post_context.md @@ -0,0 +1,113 @@ +# Patch-overlapping Python context after the fix + +## `web/pgadmin/misc/__init__.py` — `function:validate_binary_path` (lines 240-268) + +```python +def validate_binary_path(): + """ + This function is used to validate the specified utilities path by + running the utilities with their versions. + """ + data = None + if hasattr(request.data, 'decode'): + data = request.data.decode('utf-8') + + if data != '': + data = json.loads(data) + + version_str = '' + if 'utility_path' in data and data['utility_path'] is not None: + binary_versions = get_binary_path_versions(data['utility_path']) + for utility, version in binary_versions.items(): + if version is None: + version_str += "" + utility + ": " + \ + "not found on the specified binary path.
" + else: + version_str += "" + utility + ": " + version + "
" + else: + return precondition_required(gettext('Invalid binary path.')) + + return make_json_response(data=gettext(version_str), status=200) +``` + +## `web/pgadmin/misc/__init__.py` — `module:@16` (lines 16-17) + +```python +from pgadmin.utils import PgAdminModule, replace_binary_path, \ + get_binary_path_versions +``` + +## `web/pgadmin/utils/__init__.py` — `function:get_binary_path_versions` (lines 354-385) + +```python +def get_binary_path_versions(binary_path: str) -> dict: + ret = {} + binary_path = os.path.abspath( + replace_binary_path(binary_path) + ) + + for utility in UTILITIES_ARRAY: + ret[utility] = None + full_path = os.path.join(binary_path, + (utility if os.name != 'nt' else + (utility + '.exe'))) + + try: + # if path doesn't exist raise exception + if not os.path.isdir(binary_path): + current_app.logger.warning('Invalid binary path.') + raise Exception() + # Get the output of the '--version' command + cmd = subprocess.run( + [full_path, '--version'], + shell=False, + capture_output=True, + text=True + ) + if cmd.returncode == 0: + ret[utility] = cmd.stdout.split(") ", 1)[1].strip() + else: + raise Exception() + except Exception as _: + continue + + return ret +``` + +## `web/pgadmin/utils/__init__.py` — `function:set_binary_path` (lines 388-420) + +```python +def set_binary_path(binary_path, bin_paths, server_type, + version_number=None, set_as_default=False): + """ + This function is used to iterate through the utilities and set the + default binary path. + """ + path_with_dir = binary_path if "$DIR" in binary_path else None + binary_versions = get_binary_path_versions(binary_path) + + for utility, version in binary_versions.items(): + version_number = version if version_number is None else version_number + if version_number.find('.'): + version_number = version_number.split('.', 1)[0] + try: + # Get the paths array based on server type + if 'pg_bin_paths' in bin_paths or 'as_bin_paths' in bin_paths: + paths_array = bin_paths['pg_bin_paths'] + if server_type == 'ppas': + paths_array = bin_paths['as_bin_paths'] + else: + paths_array = bin_paths + + for path in paths_array: + if path['version'].find(version_number) == 0 and \ + path['binaryPath'] is None: + path['binaryPath'] = path_with_dir \ + if path_with_dir is not None else binary_path + if set_as_default: + path['isDefault'] = True + break + break + except Exception: + continue +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..ca9acad0a4e8d0e14359c191a79f16ad62f670cb --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/pre_context.md @@ -0,0 +1,120 @@ +# Patch-overlapping Python context before the fix + +## `web/pgadmin/misc/__init__.py` — `function:validate_binary_path` (lines 239-291) + +```python +def validate_binary_path(): + """ + This function is used to validate the specified utilities path by + running the utilities with their versions. + """ + data = None + if hasattr(request.data, 'decode'): + data = request.data.decode('utf-8') + + if data != '': + data = json.loads(data) + + version_str = '' + if 'utility_path' in data and data['utility_path'] is not None: + # Check if "$DIR" present in binary path + binary_path = replace_binary_path(data['utility_path']) + + for utility in UTILITIES_ARRAY: + full_path = os.path.abspath( + os.path.join(binary_path, + (utility if os.name != 'nt' else + (utility + '.exe')))) + + try: + # if path doesn't exist raise exception + if not os.path.exists(binary_path): + current_app.logger.warning('Invalid binary path.') + raise Exception() + # escape double quotes to avoid command injection. + # Get the output of the '--version' command + version_string = \ + subprocess.getoutput(r'"{0}" --version'.format( + full_path.replace('"', '""'))) + # Get the version number by splitting the result string + version_string.split(") ", 1)[1].split('.', 1)[0] + except Exception: + version_str += "" + utility + ": " + \ + "not found on the specified binary path.
" + continue + + # Replace the name of the utility from the result to avoid + # duplicate name. + result_str = version_string.replace(utility, '') + + version_str += "" + utility + ": " + result_str + "
" + else: + return precondition_required(gettext('Invalid binary path.')) + + return make_json_response(data=gettext(version_str), status=200) +``` + +## `web/pgadmin/misc/__init__.py` — `module:@16` (lines 16-16) + +```python +from pgadmin.utils import PgAdminModule, replace_binary_path +``` + +## `web/pgadmin/misc/__init__.py` — `module:@17` (lines 17-17) + +```python +from pgadmin.utils.csrf import pgCSRFProtect +``` + +## `web/pgadmin/utils/__init__.py` — `function:set_binary_path` (lines 354-401) + +```python +def set_binary_path(binary_path, bin_paths, server_type, + version_number=None, set_as_default=False): + """ + This function is used to iterate through the utilities and set the + default binary path. + """ + path_with_dir = binary_path if "$DIR" in binary_path else None + + # Check if "$DIR" present in binary path + binary_path = replace_binary_path(binary_path) + + for utility in UTILITIES_ARRAY: + full_path = os.path.abspath( + os.path.join(binary_path, (utility if os.name != 'nt' else + (utility + '.exe')))) + + try: + # if version_number is provided then no need to fetch it. + if version_number is None: + # Get the output of the '--version' command + version_string = \ + subprocess.getoutput('"{0}" --version'.format(full_path)) + + # Get the version number by splitting the result string + version_number = \ + version_string.split(") ", 1)[1].split('.', 1)[0] + elif version_number.find('.'): + version_number = version_number.split('.', 1)[0] + + # Get the paths array based on server type + if 'pg_bin_paths' in bin_paths or 'as_bin_paths' in bin_paths: + paths_array = bin_paths['pg_bin_paths'] + if server_type == 'ppas': + paths_array = bin_paths['as_bin_paths'] + else: + paths_array = bin_paths + + for path in paths_array: + if path['version'].find(version_number) == 0 and \ + path['binaryPath'] is None: + path['binaryPath'] = path_with_dir \ + if path_with_dir is not None else binary_path + if set_as_default: + path['isDefault'] = True + break + break + except Exception: + continue +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/task.json new file mode 100644 index 0000000000000000000000000000000000000000..bdaf6b04701cdaf307e4d83189230d33f91b8904 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-dbcc9a178b256c49887e", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-dbcc9a178b256c49887e", + "project_id": "pyvul__pgadmin-org__pgadmin4", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "web/pgadmin/misc/__init__.py", + "web/pgadmin/utils/__init__.py" + ], + "patch_units": { + "before": [ + "function:validate_binary_path", + "module:@16", + "module:@17", + "function:set_binary_path" + ], + "after": [ + "function:validate_binary_path", + "module:@16", + "function:get_binary_path_versions", + "function:set_binary_path" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/02f77fb20201c8bf69a0967d9b8aaf9928584f158956dec03126ffdcc421599b/database", + "cache_key": "02f77fb20201c8bf69a0967d9b8aaf9928584f158956dec03126ffdcc421599b", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/373bfeebddc05ab893743882f496be13b26cbce5ae27c614abb96250a5594f83/database", + "cache_key": "373bfeebddc05ab893743882f496be13b26cbce5ae27c614abb96250a5594f83", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/594dbd81970fbad933a60be0bf0ba3e2a94029701e8359aad929b6b7198e0919/database", + "cache_key": "594dbd81970fbad933a60be0bf0ba3e2a94029701e8359aad929b6b7198e0919", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-dbcc9a178b256c49887e/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-dbcc9a178b256c49887e/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-dbcc9a178b256c49887e/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2d8352c8918d7e45df36ed47f540f253eb96ac94 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/patch.diff @@ -0,0 +1,33 @@ +diff --git a/keylime/registrar_common.py b/keylime/registrar_common.py +index 1fd97cd..7f15ae4 100644 +--- a/keylime/registrar_common.py ++++ b/keylime/registrar_common.py +@@ -250,7 +250,9 @@ class UnprotectedHandler(BaseHandler): + try: + port = int(port) + if port < 1 or port > 65535: +- logger.warning("Contact port for agent %s is not a number between 1 and got: %s.", agent_id, port) ++ logger.warning( ++ "Contact port for agent %s is not a number between 1 and 65535 got: %s.", agent_id, port ++ ) + port = None + except ValueError: + logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port) +@@ -447,7 +449,16 @@ class UnprotectedHandler(BaseHandler): + logger.error("SQLAlchemy Error: %s", e) + raise + else: +- raise Exception(f"Auth tag {auth_tag} does not match expected value {ex_mac}") ++ if agent_id and session.query(RegistrarMain).filter_by(agent_id=agent_id).delete(): ++ try: ++ session.commit() ++ except SQLAlchemyError as e: ++ logger.error("SQLAlchemy Error: %s", e) ++ raise ++ ++ raise Exception( ++ f"Auth tag {auth_tag} for agent {agent_id} does not match expected value. The agent has been deleted from database, and a restart of it will be required" ++ ) + + web_util.echo_json_response(self, 200, "Success") + logger.info("PUT activated: %s", agent_id) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..9a630e74dd456f73859b75af017a9c2c0ea5cee6 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/post_context.md @@ -0,0 +1,382 @@ +# Patch-overlapping Python context after the fix + +## `keylime/registrar_common.py` — `class:UnprotectedHandler` (lines 204-477) + +```python +class UnprotectedHandler(BaseHandler): + def do_HEAD(self) -> None: + """HEAD not supported""" + web_util.echo_json_response(self, 405, "HEAD not supported") + + def do_PATCH(self) -> None: + """PATCH not supported""" + web_util.echo_json_response(self, 405, "PATCH not supported") + + def do_GET(self) -> None: + """This method handles the GET requests to the unprotected side of the Registrar Server + + Currently the only supported path is /versions which shows the supported API versions + """ + rest_params = web_util.get_restful_params(self.path) + if rest_params is None: + web_util.echo_json_response(self, 405, "Not Implemented: Use /version/ interface") + return + + if "version" not in rest_params: + web_util.echo_json_response(self, 400, "URI not supported") + logger.warning("GET agent returning 400 response. URI not supported: %s", self.path) + return + + version_info = { + "current_version": keylime_api_version.current_version(), + "supported_versions": keylime_api_version.all_versions(), + } + + web_util.echo_json_response(self, 200, "Success", version_info) + + @staticmethod + def get_network_params( + json_body: Dict[str, Any], agent_id: str + ) -> Tuple[Optional[str], Optional[int], Optional[str]]: + # Validate ip and port + ip = json_body.get("ip") + if ip is not None: + try: + ipaddress.ip_address(ip) + except ValueError: + logger.warning("Contact ip for agent %s is not a valid ip got: %s.", agent_id, ip) + ip = None + + port = json_body.get("port") + if port is not None: + try: + port = int(port) + if port < 1 or port > 65535: + logger.warning( + "Contact port for agent %s is not a number between 1 and 65535 got: %s.", agent_id, port + ) + port = None + except ValueError: + logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port) + port = None + + mtls_cert = json_body.get("mtls_cert") + if mtls_cert is None or mtls_cert == "disabled": + logger.warning("Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id) + + return ip, port, mtls_cert + + def do_POST(self) -> None: + """This method handles the POST requests to add agents to the Registrar Server. + + Currently, only agents resources are available for POSTing, i.e. /agents. All other POST uri's + will return errors. POST requests require an an agent_id identifying the agent to add, and json + block sent in the body with 2 entries: ek and aik. + """ + session = SessionManager().make_session(engine) + + _, agent_id = self._validate_input("POST", True) + if not agent_id: + return + + try: + content_length = int(self.headers.get("Content-Length", 0)) + if content_length == 0: + web_util.echo_json_response(self, 400, "Expected non zero content length") + logger.warning("POST for %s returning 400 response. Expected non zero content length.", agent_id) + return + + post_body = self.rfile.read(content_length) + json_body = json.loads(post_body) + + ekcert = json_body["ekcert"] + aik_tpm = json_body["aik_tpm"] + + if ekcert is None or ekcert == "emulator": + logger.warning("Agent %s did not submit an ekcert", agent_id) + ek_tpm = json_body["ek_tpm"] + else: + if "ek_tpm" in json_body: + # This would mean the agent submitted both a non-None ekcert, *and* + # an ek_tpm... We can deal with it by just ignoring the ek_tpm they sent + logger.warning("Overriding ek_tpm for agent %s from ekcert", agent_id) + # If there's an EKCert, we just overwrite their ek_tpm + # Note, we don't validate the EKCert here, other than the implicit + # "is it a valid x509 cert" check. So it's still untrusted. + # This will be validated by the tenant. + cert = cert_utils.x509_der_cert(base64.b64decode(ekcert)) + pubkey = cert.public_key() + assert isinstance(pubkey, (rsa.RSAPublicKey, ec.EllipticCurvePublicKey)) + ek_tpm = base64.b64encode(tpm2_objects.ek_low_tpm2b_public_from_pubkey(pubkey)).decode() + + aik_attrs = tpm2_objects.get_tpm2b_public_object_attributes( + base64.b64decode(aik_tpm), + ) + if aik_attrs != tpm2_objects.AK_EXPECTED_ATTRS: + web_util.echo_json_response(self, 400, "Invalid AK attributes") + logger.warning( + "Agent %s submitted AIK with invalid attributes! %s (provided) != %s (expected)", + agent_id, + tpm2_objects.object_attributes_description(aik_attrs), + tpm2_objects.object_attributes_description(tpm2_objects.AK_EXPECTED_ATTRS), + ) + return + + # try to encrypt the AIK + aik_enc = Tpm.encryptAIK( + agent_id, + base64.b64decode(ek_tpm), + base64.b64decode(aik_tpm), + ) + if aik_enc is None: + logger.warning("Agent %s failed encrypting AIK", agent_id) + web_util.echo_json_response(self, 400, "Error: failed encrypting AK") + return + + blob, key = aik_enc + + # special behavior if we've registered this uuid before + regcount = 1 + try: + agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first() + except NoResultFound: + agent = None + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + if agent is not None: + # keep track of how many ek-ekcerts have registered on this uuid + assert isinstance(agent.regcount, int) + regcount = agent.regcount + if agent.ek_tpm != ek_tpm or agent.ekcert != ekcert: # pyright: ignore + logger.warning("WARNING: Overwriting previous registration for this UUID with new ek-ekcert pair!") + regcount += 1 + + # force overwrite + logger.info("Overwriting previous registration for this UUID.") + try: + session.query(RegistrarMain).filter_by(agent_id=agent_id).delete() + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + # Check for ip and port and mTLS cert + contact_ip, contact_port, mtls_cert = UnprotectedHandler.get_network_params(json_body, agent_id) + + # Add values to database + d: Dict[str, Any] = { + "agent_id": agent_id, + "ek_tpm": ek_tpm, + "aik_tpm": aik_tpm, + "ekcert": ekcert, + "ip": contact_ip, + "mtls_cert": mtls_cert, + "port": contact_port, + "virtual": int(ekcert == "virtual"), + "active": int(False), + "key": key, + "provider_keys": {}, + "regcount": regcount, + } + + try: + session.add(RegistrarMain(**d)) + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + if rmc: + try: + rmc.record_create(d, None, None) + + except Exception as e: + logger.error("Durable Attestation Error: %s", e) + raise + + response = { + "blob": blob, + } + web_util.echo_json_response(self, 200, "Success", response) + + logger.info("POST returning key blob for agent_id: %s", agent_id) + except Exception as e: + web_util.echo_json_response(self, 400, f"Error: {str(e)}") + logger.warning("POST for %s returning 400 response. Error: %s", agent_id, e) + logger.exception(e) + + def do_PUT(self) -> None: + """This method handles the PUT requests to add agents to the Registrar Server. + + Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's + will return errors. + """ + session = SessionManager().make_session(engine) + + _, agent_id = self._validate_input("PUT", True) + if not agent_id: + return + + try: + content_length = int(self.headers.get("Content-Length", 0)) + if content_length == 0: + web_util.echo_json_response(self, 400, "Expected non zero content length") + logger.warning("PUT for %s returning 400 response. Expected non zero content length.", agent_id) + return + + post_body = self.rfile.read(content_length) + json_body = json.loads(post_body) + + auth_tag = json_body["auth_tag"] + try: + agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first() + except NoResultFound as e: + raise Exception("attempting to activate agent before requesting " f"registrar for {agent_id}") from e + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + assert agent + assert isinstance(agent.key, str) + ex_mac = crypto.do_hmac(agent.key.encode(), agent_id) + if ex_mac == auth_tag: + try: + session.query(RegistrarMain).filter(RegistrarMain.agent_id == agent_id).update( + {"active": int(True)} + ) + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + else: + if agent_id and session.query(RegistrarMain).filter_by(agent_id=agent_id).delete(): + try: + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + raise Exception( + f"Auth tag {auth_tag} for agent {agent_id} does not match expected value. The agent has been deleted from database, and a restart of it will be required" + ) + + web_util.echo_json_response(self, 200, "Success") + logger.info("PUT activated: %s", agent_id) + except Exception as e: + web_util.echo_json_response(self, 400, f"Error: {str(e)}") + logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e) + logger.exception(e) + return + + def do_DELETE(self) -> None: + """DELETE not supported""" + web_util.echo_json_response(self, 405, "DELETE not supported") + + # pylint: disable=W0622 + def log_message(self, format: str, *args: Any) -> None: + return +``` + +## `keylime/registrar_common.py` — `function:UnprotectedHandler.get_network_params` (lines 235-265) + +```python + def get_network_params( + json_body: Dict[str, Any], agent_id: str + ) -> Tuple[Optional[str], Optional[int], Optional[str]]: + # Validate ip and port + ip = json_body.get("ip") + if ip is not None: + try: + ipaddress.ip_address(ip) + except ValueError: + logger.warning("Contact ip for agent %s is not a valid ip got: %s.", agent_id, ip) + ip = None + + port = json_body.get("port") + if port is not None: + try: + port = int(port) + if port < 1 or port > 65535: + logger.warning( + "Contact port for agent %s is not a number between 1 and 65535 got: %s.", agent_id, port + ) + port = None + except ValueError: + logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port) + port = None + + mtls_cert = json_body.get("mtls_cert") + if mtls_cert is None or mtls_cert == "disabled": + logger.warning("Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id) + + return ip, port, mtls_cert +``` + +## `keylime/registrar_common.py` — `function:UnprotectedHandler.do_PUT` (lines 408-469) + +```python + def do_PUT(self) -> None: + """This method handles the PUT requests to add agents to the Registrar Server. + + Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's + will return errors. + """ + session = SessionManager().make_session(engine) + + _, agent_id = self._validate_input("PUT", True) + if not agent_id: + return + + try: + content_length = int(self.headers.get("Content-Length", 0)) + if content_length == 0: + web_util.echo_json_response(self, 400, "Expected non zero content length") + logger.warning("PUT for %s returning 400 response. Expected non zero content length.", agent_id) + return + + post_body = self.rfile.read(content_length) + json_body = json.loads(post_body) + + auth_tag = json_body["auth_tag"] + try: + agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first() + except NoResultFound as e: + raise Exception("attempting to activate agent before requesting " f"registrar for {agent_id}") from e + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + assert agent + assert isinstance(agent.key, str) + ex_mac = crypto.do_hmac(agent.key.encode(), agent_id) + if ex_mac == auth_tag: + try: + session.query(RegistrarMain).filter(RegistrarMain.agent_id == agent_id).update( + {"active": int(True)} + ) + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + else: + if agent_id and session.query(RegistrarMain).filter_by(agent_id=agent_id).delete(): + try: + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + raise Exception( + f"Auth tag {auth_tag} for agent {agent_id} does not match expected value. The agent has been deleted from database, and a restart of it will be required" + ) + + web_util.echo_json_response(self, 200, "Success") + logger.info("PUT activated: %s", agent_id) + except Exception as e: + web_util.echo_json_response(self, 400, f"Error: {str(e)}") + logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e) + logger.exception(e) + return +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..8c8f05c59f9e1cc2398221795efcfd3e8e916cec --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/pre_context.md @@ -0,0 +1,360 @@ +# Patch-overlapping Python context before the fix + +## `keylime/registrar_common.py` — `class:UnprotectedHandler` (lines 204-466) + +```python +class UnprotectedHandler(BaseHandler): + def do_HEAD(self) -> None: + """HEAD not supported""" + web_util.echo_json_response(self, 405, "HEAD not supported") + + def do_PATCH(self) -> None: + """PATCH not supported""" + web_util.echo_json_response(self, 405, "PATCH not supported") + + def do_GET(self) -> None: + """This method handles the GET requests to the unprotected side of the Registrar Server + + Currently the only supported path is /versions which shows the supported API versions + """ + rest_params = web_util.get_restful_params(self.path) + if rest_params is None: + web_util.echo_json_response(self, 405, "Not Implemented: Use /version/ interface") + return + + if "version" not in rest_params: + web_util.echo_json_response(self, 400, "URI not supported") + logger.warning("GET agent returning 400 response. URI not supported: %s", self.path) + return + + version_info = { + "current_version": keylime_api_version.current_version(), + "supported_versions": keylime_api_version.all_versions(), + } + + web_util.echo_json_response(self, 200, "Success", version_info) + + @staticmethod + def get_network_params( + json_body: Dict[str, Any], agent_id: str + ) -> Tuple[Optional[str], Optional[int], Optional[str]]: + # Validate ip and port + ip = json_body.get("ip") + if ip is not None: + try: + ipaddress.ip_address(ip) + except ValueError: + logger.warning("Contact ip for agent %s is not a valid ip got: %s.", agent_id, ip) + ip = None + + port = json_body.get("port") + if port is not None: + try: + port = int(port) + if port < 1 or port > 65535: + logger.warning("Contact port for agent %s is not a number between 1 and got: %s.", agent_id, port) + port = None + except ValueError: + logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port) + port = None + + mtls_cert = json_body.get("mtls_cert") + if mtls_cert is None or mtls_cert == "disabled": + logger.warning("Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id) + + return ip, port, mtls_cert + + def do_POST(self) -> None: + """This method handles the POST requests to add agents to the Registrar Server. + + Currently, only agents resources are available for POSTing, i.e. /agents. All other POST uri's + will return errors. POST requests require an an agent_id identifying the agent to add, and json + block sent in the body with 2 entries: ek and aik. + """ + session = SessionManager().make_session(engine) + + _, agent_id = self._validate_input("POST", True) + if not agent_id: + return + + try: + content_length = int(self.headers.get("Content-Length", 0)) + if content_length == 0: + web_util.echo_json_response(self, 400, "Expected non zero content length") + logger.warning("POST for %s returning 400 response. Expected non zero content length.", agent_id) + return + + post_body = self.rfile.read(content_length) + json_body = json.loads(post_body) + + ekcert = json_body["ekcert"] + aik_tpm = json_body["aik_tpm"] + + if ekcert is None or ekcert == "emulator": + logger.warning("Agent %s did not submit an ekcert", agent_id) + ek_tpm = json_body["ek_tpm"] + else: + if "ek_tpm" in json_body: + # This would mean the agent submitted both a non-None ekcert, *and* + # an ek_tpm... We can deal with it by just ignoring the ek_tpm they sent + logger.warning("Overriding ek_tpm for agent %s from ekcert", agent_id) + # If there's an EKCert, we just overwrite their ek_tpm + # Note, we don't validate the EKCert here, other than the implicit + # "is it a valid x509 cert" check. So it's still untrusted. + # This will be validated by the tenant. + cert = cert_utils.x509_der_cert(base64.b64decode(ekcert)) + pubkey = cert.public_key() + assert isinstance(pubkey, (rsa.RSAPublicKey, ec.EllipticCurvePublicKey)) + ek_tpm = base64.b64encode(tpm2_objects.ek_low_tpm2b_public_from_pubkey(pubkey)).decode() + + aik_attrs = tpm2_objects.get_tpm2b_public_object_attributes( + base64.b64decode(aik_tpm), + ) + if aik_attrs != tpm2_objects.AK_EXPECTED_ATTRS: + web_util.echo_json_response(self, 400, "Invalid AK attributes") + logger.warning( + "Agent %s submitted AIK with invalid attributes! %s (provided) != %s (expected)", + agent_id, + tpm2_objects.object_attributes_description(aik_attrs), + tpm2_objects.object_attributes_description(tpm2_objects.AK_EXPECTED_ATTRS), + ) + return + + # try to encrypt the AIK + aik_enc = Tpm.encryptAIK( + agent_id, + base64.b64decode(ek_tpm), + base64.b64decode(aik_tpm), + ) + if aik_enc is None: + logger.warning("Agent %s failed encrypting AIK", agent_id) + web_util.echo_json_response(self, 400, "Error: failed encrypting AK") + return + + blob, key = aik_enc + + # special behavior if we've registered this uuid before + regcount = 1 + try: + agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first() + except NoResultFound: + agent = None + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + if agent is not None: + # keep track of how many ek-ekcerts have registered on this uuid + assert isinstance(agent.regcount, int) + regcount = agent.regcount + if agent.ek_tpm != ek_tpm or agent.ekcert != ekcert: # pyright: ignore + logger.warning("WARNING: Overwriting previous registration for this UUID with new ek-ekcert pair!") + regcount += 1 + + # force overwrite + logger.info("Overwriting previous registration for this UUID.") + try: + session.query(RegistrarMain).filter_by(agent_id=agent_id).delete() + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + # Check for ip and port and mTLS cert + contact_ip, contact_port, mtls_cert = UnprotectedHandler.get_network_params(json_body, agent_id) + + # Add values to database + d: Dict[str, Any] = { + "agent_id": agent_id, + "ek_tpm": ek_tpm, + "aik_tpm": aik_tpm, + "ekcert": ekcert, + "ip": contact_ip, + "mtls_cert": mtls_cert, + "port": contact_port, + "virtual": int(ekcert == "virtual"), + "active": int(False), + "key": key, + "provider_keys": {}, + "regcount": regcount, + } + + try: + session.add(RegistrarMain(**d)) + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + if rmc: + try: + rmc.record_create(d, None, None) + + except Exception as e: + logger.error("Durable Attestation Error: %s", e) + raise + + response = { + "blob": blob, + } + web_util.echo_json_response(self, 200, "Success", response) + + logger.info("POST returning key blob for agent_id: %s", agent_id) + except Exception as e: + web_util.echo_json_response(self, 400, f"Error: {str(e)}") + logger.warning("POST for %s returning 400 response. Error: %s", agent_id, e) + logger.exception(e) + + def do_PUT(self) -> None: + """This method handles the PUT requests to add agents to the Registrar Server. + + Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's + will return errors. + """ + session = SessionManager().make_session(engine) + + _, agent_id = self._validate_input("PUT", True) + if not agent_id: + return + + try: + content_length = int(self.headers.get("Content-Length", 0)) + if content_length == 0: + web_util.echo_json_response(self, 400, "Expected non zero content length") + logger.warning("PUT for %s returning 400 response. Expected non zero content length.", agent_id) + return + + post_body = self.rfile.read(content_length) + json_body = json.loads(post_body) + + auth_tag = json_body["auth_tag"] + try: + agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first() + except NoResultFound as e: + raise Exception("attempting to activate agent before requesting " f"registrar for {agent_id}") from e + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + assert agent + assert isinstance(agent.key, str) + ex_mac = crypto.do_hmac(agent.key.encode(), agent_id) + if ex_mac == auth_tag: + try: + session.query(RegistrarMain).filter(RegistrarMain.agent_id == agent_id).update( + {"active": int(True)} + ) + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + else: + raise Exception(f"Auth tag {auth_tag} does not match expected value {ex_mac}") + + web_util.echo_json_response(self, 200, "Success") + logger.info("PUT activated: %s", agent_id) + except Exception as e: + web_util.echo_json_response(self, 400, f"Error: {str(e)}") + logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e) + logger.exception(e) + return + + def do_DELETE(self) -> None: + """DELETE not supported""" + web_util.echo_json_response(self, 405, "DELETE not supported") + + # pylint: disable=W0622 + def log_message(self, format: str, *args: Any) -> None: + return +``` + +## `keylime/registrar_common.py` — `function:UnprotectedHandler.get_network_params` (lines 235-263) + +```python + def get_network_params( + json_body: Dict[str, Any], agent_id: str + ) -> Tuple[Optional[str], Optional[int], Optional[str]]: + # Validate ip and port + ip = json_body.get("ip") + if ip is not None: + try: + ipaddress.ip_address(ip) + except ValueError: + logger.warning("Contact ip for agent %s is not a valid ip got: %s.", agent_id, ip) + ip = None + + port = json_body.get("port") + if port is not None: + try: + port = int(port) + if port < 1 or port > 65535: + logger.warning("Contact port for agent %s is not a number between 1 and got: %s.", agent_id, port) + port = None + except ValueError: + logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port) + port = None + + mtls_cert = json_body.get("mtls_cert") + if mtls_cert is None or mtls_cert == "disabled": + logger.warning("Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id) + + return ip, port, mtls_cert +``` + +## `keylime/registrar_common.py` — `function:UnprotectedHandler.do_PUT` (lines 406-458) + +```python + def do_PUT(self) -> None: + """This method handles the PUT requests to add agents to the Registrar Server. + + Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's + will return errors. + """ + session = SessionManager().make_session(engine) + + _, agent_id = self._validate_input("PUT", True) + if not agent_id: + return + + try: + content_length = int(self.headers.get("Content-Length", 0)) + if content_length == 0: + web_util.echo_json_response(self, 400, "Expected non zero content length") + logger.warning("PUT for %s returning 400 response. Expected non zero content length.", agent_id) + return + + post_body = self.rfile.read(content_length) + json_body = json.loads(post_body) + + auth_tag = json_body["auth_tag"] + try: + agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first() + except NoResultFound as e: + raise Exception("attempting to activate agent before requesting " f"registrar for {agent_id}") from e + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + + assert agent + assert isinstance(agent.key, str) + ex_mac = crypto.do_hmac(agent.key.encode(), agent_id) + if ex_mac == auth_tag: + try: + session.query(RegistrarMain).filter(RegistrarMain.agent_id == agent_id).update( + {"active": int(True)} + ) + session.commit() + except SQLAlchemyError as e: + logger.error("SQLAlchemy Error: %s", e) + raise + else: + raise Exception(f"Auth tag {auth_tag} does not match expected value {ex_mac}") + + web_util.echo_json_response(self, 200, "Success") + logger.info("PUT activated: %s", agent_id) + except Exception as e: + web_util.echo_json_response(self, 400, f"Error: {str(e)}") + logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e) + logger.exception(e) + return +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ff06dc7eef1f3c75eb957d38c9a3616eccd145c7 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/task.json @@ -0,0 +1,48 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-e305522c703de57f9ede", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-e305522c703de57f9ede", + "project_id": "pyvul__keylime__keylime", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "keylime/registrar_common.py" + ], + "patch_units": { + "before": [ + "class:UnprotectedHandler", + "function:UnprotectedHandler.get_network_params", + "function:UnprotectedHandler.do_PUT" + ], + "after": [ + "class:UnprotectedHandler", + "function:UnprotectedHandler.get_network_params", + "function:UnprotectedHandler.do_PUT" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/bfd9f477307e251a6c18bdcbec009d3656e1ed260277b98ca4a953f150d755fe/database", + "cache_key": "bfd9f477307e251a6c18bdcbec009d3656e1ed260277b98ca4a953f150d755fe", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/8b574c48597b8d580972ea7178fa48c7bc4fac808e42f9fb1c15226d13b528f7/database", + "cache_key": "8b574c48597b8d580972ea7178fa48c7bc4fac808e42f9fb1c15226d13b528f7", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/4c82099c157fcedafbfa73c0581afd11b937203090856459d9d027898d8bab23/database", + "cache_key": "4c82099c157fcedafbfa73c0581afd11b937203090856459d9d027898d8bab23", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-e305522c703de57f9ede/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-e305522c703de57f9ede/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e305522c703de57f9ede/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7147626536de3f16b71103921a8b6992ae7f8fd1 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/patch.diff @@ -0,0 +1,14 @@ +diff --git a/Lib/fontTools/subset/svg.py b/Lib/fontTools/subset/svg.py +index f6d74a400..2e55bf54c 100644 +--- a/Lib/fontTools/subset/svg.py ++++ b/Lib/fontTools/subset/svg.py +@@ -225,6 +225,9 @@ def subset_glyphs(self, s) -> bool: + # ignore blank text as it's not meaningful in OT-SVG; it also prevents + # dangling tail text after removing an element when pretty_print=True + remove_blank_text=True, ++ # don't replace entities; we don't expect any in OT-SVG and they may ++ # aboused for XXE attacks ++ resolve_entities=False, + ), + ) + diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..da389fdeed44d2a10d923dbc606d92e577f96df5 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/post_context.md @@ -0,0 +1,67 @@ +# Patch-overlapping Python context after the fix + +## `Lib/fontTools/subset/svg.py` — `function:subset_glyphs` (lines 193-254) + +```python +def subset_glyphs(self, s) -> bool: + if etree is None: + raise ImportError("No module named 'lxml', required to subset SVG") + + # glyph names (before subsetting) + glyph_order: List[str] = s.orig_glyph_order + # map from glyph names to original glyph indices + rev_orig_glyph_map: Dict[str, int] = s.reverseOrigGlyphMap + # map from original to new glyph indices (after subsetting) + glyph_index_map: Dict[int, int] = s.glyph_index_map + + new_docs: List[SVGDocument] = [] + for doc in self.docList: + + glyphs = { + glyph_order[i] for i in range(doc.startGlyphID, doc.endGlyphID + 1) + }.intersection(s.glyphs) + if not glyphs: + # no intersection: we can drop the whole record + continue + + svg = etree.fromstring( + # encode because fromstring dislikes xml encoding decl if input is str. + # SVG xml encoding must be utf-8 as per OT spec. + doc.data.encode("utf-8"), + parser=etree.XMLParser( + # Disable libxml2 security restrictions to support very deep trees. + # Without this we would get an error like this: + # `lxml.etree.XMLSyntaxError: internal error: Huge input lookup` + # when parsing big fonts e.g. noto-emoji-picosvg.ttf. + huge_tree=True, + # ignore blank text as it's not meaningful in OT-SVG; it also prevents + # dangling tail text after removing an element when pretty_print=True + remove_blank_text=True, + # don't replace entities; we don't expect any in OT-SVG and they may + # aboused for XXE attacks + resolve_entities=False, + ), + ) + + elements = group_elements_by_id(svg) + gids = {rev_orig_glyph_map[g] for g in glyphs} + element_ids = {f"glyph{i}" for i in gids} + closure_element_ids(elements, element_ids) + + if not subset_elements(svg, element_ids): + continue + + if not s.options.retain_gids: + id_map = remap_glyph_ids(svg, glyph_index_map) + update_glyph_href_links(svg, id_map) + + new_doc = etree.tostring(svg, pretty_print=s.options.pretty_svg).decode("utf-8") + + new_gids = (glyph_index_map[i] for i in gids) + for start, end in ranges(new_gids): + new_docs.append(SVGDocument(new_doc, start, end, doc.compressed)) + + self.docList = new_docs + + return bool(self.docList) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..05c2c21e5a056927e747dbc1136fe9c34580cb12 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/pre_context.md @@ -0,0 +1,64 @@ +# Patch-overlapping Python context before the fix + +## `Lib/fontTools/subset/svg.py` — `function:subset_glyphs` (lines 193-251) + +```python +def subset_glyphs(self, s) -> bool: + if etree is None: + raise ImportError("No module named 'lxml', required to subset SVG") + + # glyph names (before subsetting) + glyph_order: List[str] = s.orig_glyph_order + # map from glyph names to original glyph indices + rev_orig_glyph_map: Dict[str, int] = s.reverseOrigGlyphMap + # map from original to new glyph indices (after subsetting) + glyph_index_map: Dict[int, int] = s.glyph_index_map + + new_docs: List[SVGDocument] = [] + for doc in self.docList: + + glyphs = { + glyph_order[i] for i in range(doc.startGlyphID, doc.endGlyphID + 1) + }.intersection(s.glyphs) + if not glyphs: + # no intersection: we can drop the whole record + continue + + svg = etree.fromstring( + # encode because fromstring dislikes xml encoding decl if input is str. + # SVG xml encoding must be utf-8 as per OT spec. + doc.data.encode("utf-8"), + parser=etree.XMLParser( + # Disable libxml2 security restrictions to support very deep trees. + # Without this we would get an error like this: + # `lxml.etree.XMLSyntaxError: internal error: Huge input lookup` + # when parsing big fonts e.g. noto-emoji-picosvg.ttf. + huge_tree=True, + # ignore blank text as it's not meaningful in OT-SVG; it also prevents + # dangling tail text after removing an element when pretty_print=True + remove_blank_text=True, + ), + ) + + elements = group_elements_by_id(svg) + gids = {rev_orig_glyph_map[g] for g in glyphs} + element_ids = {f"glyph{i}" for i in gids} + closure_element_ids(elements, element_ids) + + if not subset_elements(svg, element_ids): + continue + + if not s.options.retain_gids: + id_map = remap_glyph_ids(svg, glyph_index_map) + update_glyph_href_links(svg, id_map) + + new_doc = etree.tostring(svg, pretty_print=s.options.pretty_svg).decode("utf-8") + + new_gids = (glyph_index_map[i] for i in gids) + for start, end in ranges(new_gids): + new_docs.append(SVGDocument(new_doc, start, end, doc.compressed)) + + self.docList = new_docs + + return bool(self.docList) +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8340f7d32e44ba69daae9a2a8b0583b4e606b5d8 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/task.json @@ -0,0 +1,44 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-e73df8c8998a1ddc180a", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-e73df8c8998a1ddc180a", + "project_id": "pyvul__fonttools__fonttools", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "Lib/fontTools/subset/svg.py" + ], + "patch_units": { + "before": [ + "function:subset_glyphs" + ], + "after": [ + "function:subset_glyphs" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/48cd017d8b697d985212d9a7152bb65fce6592d1ac17bd9f9502723c2e11747b/database", + "cache_key": "48cd017d8b697d985212d9a7152bb65fce6592d1ac17bd9f9502723c2e11747b", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/f5e2fbebb52114085844644a39edc259052bf22a9d38175fb541e9cee0576c08/database", + "cache_key": "f5e2fbebb52114085844644a39edc259052bf22a9d38175fb541e9cee0576c08", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/85e9b83255ff1f73333277d259af5addfd43ae511ccc753cc90d97b2a9dac12a/database", + "cache_key": "85e9b83255ff1f73333277d259af5addfd43ae511ccc753cc90d97b2a9dac12a", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-e73df8c8998a1ddc180a/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-e73df8c8998a1ddc180a/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-e73df8c8998a1ddc180a/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b7456feeb8832dc9a28e2830fca8ea0527f8be5f --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/patch.diff @@ -0,0 +1,13 @@ +diff --git a/apprise/plugins/NotifyIFTTT.py b/apprise/plugins/NotifyIFTTT.py +index c038a9e..b735a4d 100644 +--- a/apprise/plugins/NotifyIFTTT.py ++++ b/apprise/plugins/NotifyIFTTT.py +@@ -355,7 +355,7 @@ class NotifyIFTTT(NotifyBase): + result = re.match( + r'^https?://maker\.ifttt\.com/use/' + r'(?P[A-Z0-9_-]+)' +- r'/?(?P([A-Z0-9_-]+/?)+)?' ++ r'((?P(/[A-Z0-9_-]+)+))?' + r'/?(?P\?.+)?$', url, re.I) + + if result: diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..e2a70c5247c6eabf93c7497362cf89e594f41bb1 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/post_context.md @@ -0,0 +1,352 @@ +# Patch-overlapping Python context after the fix + +## `apprise/plugins/NotifyIFTTT.py` — `class:NotifyIFTTT` (lines 53-371) + +```python +class NotifyIFTTT(NotifyBase): + """ + A wrapper for IFTTT Notifications + + """ + + # The default descriptive name associated with the Notification + service_name = 'IFTTT' + + # The services URL + service_url = 'https://ifttt.com/' + + # The default protocol + secure_protocol = 'ifttt' + + # A URL that takes you to the setup/help of the specific protocol + setup_url = 'https://github.com/caronc/apprise/wiki/Notify_ifttt' + + # Even though you'll add 'Ingredients' as {{ Value1 }} to your Applets, + # you must use their lowercase value in the HTTP POST. + ifttt_default_key_prefix = 'value' + + # The default IFTTT Key to use when mapping the title text to the IFTTT + # event. The idea here is if someone wants to over-ride the default and + # change it to another Ingredient Name (in 2018, you were limited to have + # value1, value2, and value3). + ifttt_default_title_key = 'value1' + + # The default IFTTT Key to use when mapping the body text to the IFTTT + # event. The idea here is if someone wants to over-ride the default and + # change it to another Ingredient Name (in 2018, you were limited to have + # value1, value2, and value3). + ifttt_default_body_key = 'value2' + + # The default IFTTT Key to use when mapping the body text to the IFTTT + # event. The idea here is if someone wants to over-ride the default and + # change it to another Ingredient Name (in 2018, you were limited to have + # value1, value2, and value3). + ifttt_default_type_key = 'value3' + + # IFTTT uses the http protocol with JSON requests + notify_url = 'https://maker.ifttt.com/' \ + 'trigger/{event}/with/key/{webhook_id}' + + # Define object templates + templates = ( + '{schema}://{webhook_id}/{events}', + ) + + # Define our template tokens + template_tokens = dict(NotifyBase.template_tokens, **{ + 'webhook_id': { + 'name': _('Webhook ID'), + 'type': 'string', + 'private': True, + 'required': True, + }, + 'events': { + 'name': _('Events'), + 'type': 'list:string', + 'required': True, + }, + }) + + # Define our template arguments + template_args = dict(NotifyBase.template_args, **{ + 'to': { + 'alias_of': 'events', + }, + }) + + # Define our token control + template_kwargs = { + 'add_tokens': { + 'name': _('Add Tokens'), + 'prefix': '+', + }, + 'del_tokens': { + 'name': _('Remove Tokens'), + 'prefix': '-', + }, + } + + def __init__(self, webhook_id, events, add_tokens=None, del_tokens=None, + **kwargs): + """ + Initialize IFTTT Object + + add_tokens can optionally be a dictionary of key/value pairs + that you want to include in the IFTTT post to the server. + + del_tokens can optionally be a list/tuple/set of tokens + that you want to eliminate from the IFTTT post. There isn't + much real functionality to this one unless you want to remove + reference to Value1, Value2, and/or Value3 + + """ + super(NotifyIFTTT, self).__init__(**kwargs) + + # Webhook ID (associated with project) + self.webhook_id = validate_regex(webhook_id) + if not self.webhook_id: + msg = 'An invalid IFTTT Webhook ID ' \ + '({}) was specified.'.format(webhook_id) + self.logger.warning(msg) + raise TypeError(msg) + + # Store our Events we wish to trigger + self.events = parse_list(events) + if not self.events: + msg = 'You must specify at least one event you wish to trigger on.' + self.logger.warning(msg) + raise TypeError(msg) + + # Tokens to include in post + self.add_tokens = {} + if add_tokens: + self.add_tokens.update(add_tokens) + + # Tokens to remove + self.del_tokens = [] + if del_tokens is not None: + if isinstance(del_tokens, (list, tuple, set)): + self.del_tokens = del_tokens + + elif isinstance(del_tokens, dict): + # Convert the dictionary into a list + self.del_tokens = set(del_tokens.keys()) + + else: + msg = 'del_token must be a list; {} was provided'.format( + str(type(del_tokens))) + self.logger.warning(msg) + raise TypeError(msg) + + def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): + """ + Perform IFTTT Notification + """ + + headers = { + 'User-Agent': self.app_id, + 'Content-Type': 'application/json', + } + + # prepare JSON Object + payload = { + self.ifttt_default_title_key: title, + self.ifttt_default_body_key: body, + self.ifttt_default_type_key: notify_type, + } + + # Add any new tokens expected (this can also potentially override + # any entries defined above) + payload.update(self.add_tokens) + + # Eliminate fields flagged for removal otherwise ensure all tokens are + # lowercase since that is what the IFTTT server expects from us. + payload = {x.lower(): y for x, y in payload.items() + if x not in self.del_tokens} + + # error tracking (used for function return) + has_error = False + + # Create a copy of our event lit + events = list(self.events) + + while len(events): + + # Retrive an entry off of our event list + event = events.pop(0) + + # URL to transmit content via + url = self.notify_url.format( + webhook_id=self.webhook_id, + event=event, + ) + + self.logger.debug('IFTTT POST URL: %s (cert_verify=%r)' % ( + url, self.verify_certificate, + )) + self.logger.debug('IFTTT Payload: %s' % str(payload)) + + # Always call throttle before any remote server i/o is made + self.throttle() + + try: + r = requests.post( + url, + data=dumps(payload), + headers=headers, + verify=self.verify_certificate, + timeout=self.request_timeout, + ) + self.logger.debug( + u"IFTTT HTTP response headers: %r" % r.headers) + self.logger.debug( + u"IFTTT HTTP response body: %r" % r.content) + + if r.status_code != requests.codes.ok: + # We had a problem + status_str = \ + NotifyIFTTT.http_response_code_lookup(r.status_code) + + self.logger.warning( + 'Failed to send IFTTT notification to {}: ' + '{}{}error={}.'.format( + event, + status_str, + ', ' if status_str else '', + r.status_code)) + + self.logger.debug( + 'Response Details:\r\n{}'.format(r.content)) + + # Mark our failure + has_error = True + continue + + else: + self.logger.info( + 'Sent IFTTT notification to %s.' % event) + + except requests.RequestException as e: + self.logger.warning( + 'A Connection error occurred sending IFTTT:%s ' % ( + event) + 'notification.' + ) + self.logger.debug('Socket Exception: %s' % str(e)) + + # Mark our failure + has_error = True + continue + + return not has_error + + def url(self, privacy=False, *args, **kwargs): + """ + Returns the URL built dynamically based on specified arguments. + """ + + # Our URL parameters + params = self.url_parameters(privacy=privacy, *args, **kwargs) + + # Store any new key/value pairs added to our list + params.update({'+{}'.format(k): v for k, v in self.add_tokens}) + params.update({'-{}'.format(k): '' for k in self.del_tokens}) + + return '{schema}://{webhook_id}@{events}/?{params}'.format( + schema=self.secure_protocol, + webhook_id=self.pprint(self.webhook_id, privacy, safe=''), + events='/'.join([NotifyIFTTT.quote(x, safe='') + for x in self.events]), + params=NotifyIFTTT.urlencode(params), + ) + + @staticmethod + def parse_url(url): + """ + Parses the URL and returns enough arguments that can allow + us to re-instantiate this object. + + """ + results = NotifyBase.parse_url(url, verify_host=False) + if not results: + # We're done early as we couldn't load the results + return results + + # Our API Key is the hostname if no user is specified + results['webhook_id'] = \ + results['user'] if results['user'] else results['host'] + + # Unquote our API Key + results['webhook_id'] = NotifyIFTTT.unquote(results['webhook_id']) + + # Parse our add_token and del_token arguments (if specified) + results['add_token'] = results['qsd+'] + results['del_token'] = results['qsd-'] + + # Our Event + results['events'] = list() + if results['user']: + # If a user was defined, then the hostname is actually a event + # too + results['events'].append(NotifyIFTTT.unquote(results['host'])) + + # Now fetch the remaining tokens + results['events'].extend(NotifyIFTTT.split_path(results['fullpath'])) + + # The 'to' makes it easier to use yaml configuration + if 'to' in results['qsd'] and len(results['qsd']['to']): + results['events'] += \ + NotifyIFTTT.parse_list(results['qsd']['to']) + + return results + + @staticmethod + def parse_native_url(url): + """ + Support https://maker.ifttt.com/use/WEBHOOK_ID/EVENT_ID + """ + + result = re.match( + r'^https?://maker\.ifttt\.com/use/' + r'(?P[A-Z0-9_-]+)' + r'((?P(/[A-Z0-9_-]+)+))?' + r'/?(?P\?.+)?$', url, re.I) + + if result: + return NotifyIFTTT.parse_url( + '{schema}://{webhook_id}{events}{params}'.format( + schema=NotifyIFTTT.secure_protocol, + webhook_id=result.group('webhook_id'), + events='' if not result.group('events') + else '@{}'.format(result.group('events')), + params='' if not result.group('params') + else result.group('params'))) + + return None +``` + +## `apprise/plugins/NotifyIFTTT.py` — `function:NotifyIFTTT.parse_native_url` (lines 349-371) + +```python + def parse_native_url(url): + """ + Support https://maker.ifttt.com/use/WEBHOOK_ID/EVENT_ID + """ + + result = re.match( + r'^https?://maker\.ifttt\.com/use/' + r'(?P[A-Z0-9_-]+)' + r'((?P(/[A-Z0-9_-]+)+))?' + r'/?(?P\?.+)?$', url, re.I) + + if result: + return NotifyIFTTT.parse_url( + '{schema}://{webhook_id}{events}{params}'.format( + schema=NotifyIFTTT.secure_protocol, + webhook_id=result.group('webhook_id'), + events='' if not result.group('events') + else '@{}'.format(result.group('events')), + params='' if not result.group('params') + else result.group('params'))) + + return None +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..aee31dc3a4ac1631a97af64a48052609f28c3d98 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/pre_context.md @@ -0,0 +1,352 @@ +# Patch-overlapping Python context before the fix + +## `apprise/plugins/NotifyIFTTT.py` — `class:NotifyIFTTT` (lines 53-371) + +```python +class NotifyIFTTT(NotifyBase): + """ + A wrapper for IFTTT Notifications + + """ + + # The default descriptive name associated with the Notification + service_name = 'IFTTT' + + # The services URL + service_url = 'https://ifttt.com/' + + # The default protocol + secure_protocol = 'ifttt' + + # A URL that takes you to the setup/help of the specific protocol + setup_url = 'https://github.com/caronc/apprise/wiki/Notify_ifttt' + + # Even though you'll add 'Ingredients' as {{ Value1 }} to your Applets, + # you must use their lowercase value in the HTTP POST. + ifttt_default_key_prefix = 'value' + + # The default IFTTT Key to use when mapping the title text to the IFTTT + # event. The idea here is if someone wants to over-ride the default and + # change it to another Ingredient Name (in 2018, you were limited to have + # value1, value2, and value3). + ifttt_default_title_key = 'value1' + + # The default IFTTT Key to use when mapping the body text to the IFTTT + # event. The idea here is if someone wants to over-ride the default and + # change it to another Ingredient Name (in 2018, you were limited to have + # value1, value2, and value3). + ifttt_default_body_key = 'value2' + + # The default IFTTT Key to use when mapping the body text to the IFTTT + # event. The idea here is if someone wants to over-ride the default and + # change it to another Ingredient Name (in 2018, you were limited to have + # value1, value2, and value3). + ifttt_default_type_key = 'value3' + + # IFTTT uses the http protocol with JSON requests + notify_url = 'https://maker.ifttt.com/' \ + 'trigger/{event}/with/key/{webhook_id}' + + # Define object templates + templates = ( + '{schema}://{webhook_id}/{events}', + ) + + # Define our template tokens + template_tokens = dict(NotifyBase.template_tokens, **{ + 'webhook_id': { + 'name': _('Webhook ID'), + 'type': 'string', + 'private': True, + 'required': True, + }, + 'events': { + 'name': _('Events'), + 'type': 'list:string', + 'required': True, + }, + }) + + # Define our template arguments + template_args = dict(NotifyBase.template_args, **{ + 'to': { + 'alias_of': 'events', + }, + }) + + # Define our token control + template_kwargs = { + 'add_tokens': { + 'name': _('Add Tokens'), + 'prefix': '+', + }, + 'del_tokens': { + 'name': _('Remove Tokens'), + 'prefix': '-', + }, + } + + def __init__(self, webhook_id, events, add_tokens=None, del_tokens=None, + **kwargs): + """ + Initialize IFTTT Object + + add_tokens can optionally be a dictionary of key/value pairs + that you want to include in the IFTTT post to the server. + + del_tokens can optionally be a list/tuple/set of tokens + that you want to eliminate from the IFTTT post. There isn't + much real functionality to this one unless you want to remove + reference to Value1, Value2, and/or Value3 + + """ + super(NotifyIFTTT, self).__init__(**kwargs) + + # Webhook ID (associated with project) + self.webhook_id = validate_regex(webhook_id) + if not self.webhook_id: + msg = 'An invalid IFTTT Webhook ID ' \ + '({}) was specified.'.format(webhook_id) + self.logger.warning(msg) + raise TypeError(msg) + + # Store our Events we wish to trigger + self.events = parse_list(events) + if not self.events: + msg = 'You must specify at least one event you wish to trigger on.' + self.logger.warning(msg) + raise TypeError(msg) + + # Tokens to include in post + self.add_tokens = {} + if add_tokens: + self.add_tokens.update(add_tokens) + + # Tokens to remove + self.del_tokens = [] + if del_tokens is not None: + if isinstance(del_tokens, (list, tuple, set)): + self.del_tokens = del_tokens + + elif isinstance(del_tokens, dict): + # Convert the dictionary into a list + self.del_tokens = set(del_tokens.keys()) + + else: + msg = 'del_token must be a list; {} was provided'.format( + str(type(del_tokens))) + self.logger.warning(msg) + raise TypeError(msg) + + def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): + """ + Perform IFTTT Notification + """ + + headers = { + 'User-Agent': self.app_id, + 'Content-Type': 'application/json', + } + + # prepare JSON Object + payload = { + self.ifttt_default_title_key: title, + self.ifttt_default_body_key: body, + self.ifttt_default_type_key: notify_type, + } + + # Add any new tokens expected (this can also potentially override + # any entries defined above) + payload.update(self.add_tokens) + + # Eliminate fields flagged for removal otherwise ensure all tokens are + # lowercase since that is what the IFTTT server expects from us. + payload = {x.lower(): y for x, y in payload.items() + if x not in self.del_tokens} + + # error tracking (used for function return) + has_error = False + + # Create a copy of our event lit + events = list(self.events) + + while len(events): + + # Retrive an entry off of our event list + event = events.pop(0) + + # URL to transmit content via + url = self.notify_url.format( + webhook_id=self.webhook_id, + event=event, + ) + + self.logger.debug('IFTTT POST URL: %s (cert_verify=%r)' % ( + url, self.verify_certificate, + )) + self.logger.debug('IFTTT Payload: %s' % str(payload)) + + # Always call throttle before any remote server i/o is made + self.throttle() + + try: + r = requests.post( + url, + data=dumps(payload), + headers=headers, + verify=self.verify_certificate, + timeout=self.request_timeout, + ) + self.logger.debug( + u"IFTTT HTTP response headers: %r" % r.headers) + self.logger.debug( + u"IFTTT HTTP response body: %r" % r.content) + + if r.status_code != requests.codes.ok: + # We had a problem + status_str = \ + NotifyIFTTT.http_response_code_lookup(r.status_code) + + self.logger.warning( + 'Failed to send IFTTT notification to {}: ' + '{}{}error={}.'.format( + event, + status_str, + ', ' if status_str else '', + r.status_code)) + + self.logger.debug( + 'Response Details:\r\n{}'.format(r.content)) + + # Mark our failure + has_error = True + continue + + else: + self.logger.info( + 'Sent IFTTT notification to %s.' % event) + + except requests.RequestException as e: + self.logger.warning( + 'A Connection error occurred sending IFTTT:%s ' % ( + event) + 'notification.' + ) + self.logger.debug('Socket Exception: %s' % str(e)) + + # Mark our failure + has_error = True + continue + + return not has_error + + def url(self, privacy=False, *args, **kwargs): + """ + Returns the URL built dynamically based on specified arguments. + """ + + # Our URL parameters + params = self.url_parameters(privacy=privacy, *args, **kwargs) + + # Store any new key/value pairs added to our list + params.update({'+{}'.format(k): v for k, v in self.add_tokens}) + params.update({'-{}'.format(k): '' for k in self.del_tokens}) + + return '{schema}://{webhook_id}@{events}/?{params}'.format( + schema=self.secure_protocol, + webhook_id=self.pprint(self.webhook_id, privacy, safe=''), + events='/'.join([NotifyIFTTT.quote(x, safe='') + for x in self.events]), + params=NotifyIFTTT.urlencode(params), + ) + + @staticmethod + def parse_url(url): + """ + Parses the URL and returns enough arguments that can allow + us to re-instantiate this object. + + """ + results = NotifyBase.parse_url(url, verify_host=False) + if not results: + # We're done early as we couldn't load the results + return results + + # Our API Key is the hostname if no user is specified + results['webhook_id'] = \ + results['user'] if results['user'] else results['host'] + + # Unquote our API Key + results['webhook_id'] = NotifyIFTTT.unquote(results['webhook_id']) + + # Parse our add_token and del_token arguments (if specified) + results['add_token'] = results['qsd+'] + results['del_token'] = results['qsd-'] + + # Our Event + results['events'] = list() + if results['user']: + # If a user was defined, then the hostname is actually a event + # too + results['events'].append(NotifyIFTTT.unquote(results['host'])) + + # Now fetch the remaining tokens + results['events'].extend(NotifyIFTTT.split_path(results['fullpath'])) + + # The 'to' makes it easier to use yaml configuration + if 'to' in results['qsd'] and len(results['qsd']['to']): + results['events'] += \ + NotifyIFTTT.parse_list(results['qsd']['to']) + + return results + + @staticmethod + def parse_native_url(url): + """ + Support https://maker.ifttt.com/use/WEBHOOK_ID/EVENT_ID + """ + + result = re.match( + r'^https?://maker\.ifttt\.com/use/' + r'(?P[A-Z0-9_-]+)' + r'/?(?P([A-Z0-9_-]+/?)+)?' + r'/?(?P\?.+)?$', url, re.I) + + if result: + return NotifyIFTTT.parse_url( + '{schema}://{webhook_id}{events}{params}'.format( + schema=NotifyIFTTT.secure_protocol, + webhook_id=result.group('webhook_id'), + events='' if not result.group('events') + else '@{}'.format(result.group('events')), + params='' if not result.group('params') + else result.group('params'))) + + return None +``` + +## `apprise/plugins/NotifyIFTTT.py` — `function:NotifyIFTTT.parse_native_url` (lines 349-371) + +```python + def parse_native_url(url): + """ + Support https://maker.ifttt.com/use/WEBHOOK_ID/EVENT_ID + """ + + result = re.match( + r'^https?://maker\.ifttt\.com/use/' + r'(?P[A-Z0-9_-]+)' + r'/?(?P([A-Z0-9_-]+/?)+)?' + r'/?(?P\?.+)?$', url, re.I) + + if result: + return NotifyIFTTT.parse_url( + '{schema}://{webhook_id}{events}{params}'.format( + schema=NotifyIFTTT.secure_protocol, + webhook_id=result.group('webhook_id'), + events='' if not result.group('events') + else '@{}'.format(result.group('events')), + params='' if not result.group('params') + else result.group('params'))) + + return None +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4b4e02986789ce01287b4b6c7ae8b4df474158c4 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-f55f7c013a9f5bd1eb0d", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-f55f7c013a9f5bd1eb0d", + "project_id": "pyvul__caronc__apprise", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "apprise/plugins/NotifyIFTTT.py" + ], + "patch_units": { + "before": [ + "class:NotifyIFTTT", + "function:NotifyIFTTT.parse_native_url" + ], + "after": [ + "class:NotifyIFTTT", + "function:NotifyIFTTT.parse_native_url" + ] + }, + "runtime_assets": { + "before": { + "database": "assets/14c7dffc83f6154b963e9f0975c7aecf287c056f253f975923e0ce41c8ba61ce/database", + "cache_key": "14c7dffc83f6154b963e9f0975c7aecf287c056f253f975923e0ce41c8ba61ce", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/01e0a522a84fb01af3434b1a833327894e72dc78380285e813e165d80347c3bf/database", + "cache_key": "01e0a522a84fb01af3434b1a833327894e72dc78380285e813e165d80347c3bf", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/fc64be56f86084ed1741beba8919c61280668ac81d26a42e2103a16c61adf529/database", + "cache_key": "fc64be56f86084ed1741beba8919c61280668ac81d26a42e2103a16c61adf529", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-f55f7c013a9f5bd1eb0d/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-f55f7c013a9f5bd1eb0d/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-f55f7c013a9f5bd1eb0d/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/patch.diff b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2e0af5fa4b43c916177e3e8f8767a68e80f54101 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/patch.diff @@ -0,0 +1,19 @@ +diff --git a/torbot/modules/validators.py b/torbot/modules/validators.py +deleted file mode 100644 +index a8e78c3..0000000 +--- a/torbot/modules/validators.py ++++ /dev/null +@@ -1,13 +0,0 @@ +-import validators +- +- +-def validate_email(email): +- if not isinstance(email, str): +- return False +- return validators.email(email) +- +- +-def validate_link(link): +- if not isinstance(link, str): +- return False +- return validators.url(link) diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/post_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/post_context.md new file mode 100644 index 0000000000000000000000000000000000000000..fe76e127f574ad375e7716cf91bd7af4550b205e --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/post_context.md @@ -0,0 +1,3 @@ +# Patch-overlapping Python context after the fix + +No patch-overlapping Python semantic unit exists on this side. diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/pre_context.md b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/pre_context.md new file mode 100644 index 0000000000000000000000000000000000000000..119883986a5d41d1035209c47749d824d53800c7 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/pre_context.md @@ -0,0 +1,25 @@ +# Patch-overlapping Python context before the fix + +## `torbot/modules/validators.py` — `function:validate_email` (lines 4-7) + +```python +def validate_email(email): + if not isinstance(email, str): + return False + return validators.email(email) +``` + +## `torbot/modules/validators.py` — `function:validate_link` (lines 10-13) + +```python +def validate_link(link): + if not isinstance(link, str): + return False + return validators.url(link) +``` + +## `torbot/modules/validators.py` — `module:@1` (lines 1-1) + +```python +import validators +``` diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/task.json b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a6a79654f0a54d29bdbbb657727a944b4b253677 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/task.json @@ -0,0 +1,44 @@ +{ + "schema_version": "synthesis-task-v1", + "task": { + "pair_id": "pyvul-ff1e02f88768f34e43fb", + "dataset_id": "PyVul", + "dataset_item_id": "pyvul-ff1e02f88768f34e43fb", + "project_id": "pyvul__dedsecinside__torbot", + "language": "python", + "backend": "codeql" + }, + "changed_python_files": [ + "torbot/modules/validators.py" + ], + "patch_units": { + "before": [ + "function:validate_email", + "function:validate_link", + "module:@1" + ], + "after": [] + }, + "runtime_assets": { + "before": { + "database": "assets/cd89e0b8eefefaf75bf5849ee4b36c79864f39fffb229b039387addb18da3715/database", + "cache_key": "cd89e0b8eefefaf75bf5849ee4b36c79864f39fffb229b039387addb18da3715", + "codeql_version": "2.26.4" + }, + "after": { + "database": "assets/52be73c6def3c938193fe86d1b31746a4dfdba192902768ffd0229acfd82c142/database", + "cache_key": "52be73c6def3c938193fe86d1b31746a4dfdba192902768ffd0229acfd82c142", + "codeql_version": "2.26.4" + }, + "refine": { + "database": "assets/3eb30acb3ddeef44ea60ec174a82d145e2571cece0fc40ddcd7c99f0aa13d7c6/database", + "cache_key": "3eb30acb3ddeef44ea60ec174a82d145e2571cece0fc40ddcd7c99f0aa13d7c6", + "codeql_version": "2.26.4" + } + }, + "benchmark_contract": { + "agent_visible": true, + "reference_query_location": "references/pyvul-ff1e02f88768f34e43fb/query/ (do not mount into agent)", + "evaluator_location": "evaluator/pyvul-ff1e02f88768f34e43fb/ (do not mount into agent)" + } +} diff --git a/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/task_prompt.md b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..665b2fa6614a07840269ab72f778c1b7ef643ce2 --- /dev/null +++ b/tasks/codeql_python_benchmark51_v2/pyvul-ff1e02f88768f34e43fb/task_prompt.md @@ -0,0 +1,82 @@ +# Python CodeQL detector synthesis + +You are cc operating in `/work`. Starting only from the supplied patch, +before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL +detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside +this session, but no later framework repair or resume will occur. + +## Inputs and owned outputs + +- Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`. +- Read `references/codeql/convergence_protocol.md` and + `references/codeql/api_navigation.md` before experimenting. Read the remaining + `references/codeql/` files for the selected mechanism. +- Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is + uncertain. Do not guess predicate names or build a large family of inspection queries. +- Complete the design contract in `state.json` and `scope_statement.md` before final validation. +- Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the + fixed offline dependency in `query/qlpack.yml`. +- Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This + task-unique metadata must never be used in a query predicate. +- Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`. +- Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`, + `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field. + +## Required reasoning contract + +Before coding, record this mapping in `state.json`: + +```text +vulnerable operation / trigger / patch safety condition + → CodeQL-observable evidence + → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism + → source, sink/report site, guard/barrier and query predicates +``` + +Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require +real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace +either with source-text matching or with the mere presence of patch-added syntax. + +## Mandatory convergence contract + +The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes +27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is +a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in +`references/codeql/convergence_protocol.md`: + +1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql` + immediately. Do not wait until every CodeQL API detail is known. +2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one + `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled + definition with `scripts/search_codeql_api.sh` or simplify the mechanism. +3. Obtain a compiling minimal main query before broadening it. Compile the main query after every + meaningful mechanism change. +4. Move in order from compile → relevant before finding → after elimination → final contract. Do + not continue API exploration after the intended before/after differential is established. +5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27 + finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all + exploration, preserve the best compiling query, finish the contract files, and exit. + +## Semantic and generalization rules + +- Report at the vulnerable call, operator, access, or sink. +- Do not use a patch-local path, line, commit hash, label, or local variable name as the primary + matching condition. Stable library/framework APIs or public project APIs are allowed only when + `scope_statement.md` explains why they define the intended vulnerability family. +- The safety condition introduced by the patch must be represented by the query. +- A lower after warning count is not enough: inspect SARIF and ensure at least one intended before + finding is in a patch-overlapping semantic unit and the corresponding finding disappears after. +- Avoid broad proxy queries that report an enclosing function or unrelated API merely because it + changed in the patch. + +## Final validation protocol + +1. Compile the final query. +2. Run it on before and inspect `raw/before.sarif` for the intended report location. +3. Run the identical query on after and inspect `raw/after.sarif`. +4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency, + and absence of patch-local hardcoding. +5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`. + +Do not modify the runtime databases, references, patch, context, or validation scripts except for +normal CodeQL-generated database caches produced by the provided run scripts. diff --git a/tasks/csa159/pair_134585/checker_template.cpp b/tasks/csa159/pair_134585/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_134585/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_134585/config.json b/tasks/csa159/pair_134585/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0f273fcfb4a7f730fc039d9cdc8093c647a016f0 --- /dev/null +++ b/tasks/csa159/pair_134585/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "adaptivecomputing_torque", + "before_commit": "94480e87f9779363780f4cf8d35831663ab354f4", + "after_commit": "3ed749263abe3d69fa3626d142a5789dcb5a5684", + "repo_path": "/workspace/repo/adaptivecomputing/torque", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/adaptivecomputing_torque/deb44cd48e9a01a88128f531bef29c09a287379a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/adaptivecomputing_torque/deb44cd48e9a01a88128f531bef29c09a287379a/compile_commands.json", + "changed_files": [ + "src/lib/Libdis/disrsi_.c" + ], + "commit_message": "Merge pull request #171 into 2.5-fixes.", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_134585/patch.diff b/tasks/csa159/pair_134585/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..41f5b14f5d5e2b3f7796333e9192de45af29c449 --- /dev/null +++ b/tasks/csa159/pair_134585/patch.diff @@ -0,0 +1,19 @@ +diff --git a/src/lib/Libdis/disrsi_.c b/src/lib/Libdis/disrsi_.c +index 69edd2803..154514c27 100644 +--- a/src/lib/Libdis/disrsi_.c ++++ b/src/lib/Libdis/disrsi_.c +@@ -112,6 +112,15 @@ int disrsi_( + if (dis_umaxd == 0) + disiui_(); + ++ if (count >= dis_umaxd) ++ { ++ if (count > dis_umaxd) ++ goto overflow; ++ ++ if (memcmp(scratch, dis_umax, dis_umaxd) > 0) ++ goto overflow; ++ } ++ + switch (c = (*dis_getc)(stream)) + { \ No newline at end of file diff --git a/tasks/csa159/pair_134585/post_functions.txt b/tasks/csa159/pair_134585/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..f54cb8e0f7660ed7f940ed20e8608c5a536d8c22 --- /dev/null +++ b/tasks/csa159/pair_134585/post_functions.txt @@ -0,0 +1,177 @@ +### File: src/lib/Libdis/disrsi_.c +```c +int disrsi_( + + int stream, + int *negate, + unsigned *value, + unsigned count) + + { + int c; + unsigned locval; + unsigned ndigs; + char *cp; + char scratch[DIS_BUFSIZ+1]; + + assert(negate != NULL); + assert(value != NULL); + assert(count); + assert(stream >= 0); + assert(dis_getc != NULL); + assert(dis_gets != NULL); + + memset(scratch, 0, DIS_BUFSIZ+1); + if (dis_umaxd == 0) + disiui_(); + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + goto overflow; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + goto overflow; + } + + switch (c = (*dis_getc)(stream)) + { + + case '-': + + case '+': + + *negate = c == '-'; + + if ((*dis_gets)(stream, scratch, count) != (int)count) + { + return(DIS_EOD); + } + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + goto overflow; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + goto overflow; + } + + cp = scratch; + + locval = 0; + + do + { + if (((c = *cp++) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + locval = 10 * locval + c - '0'; + } + while (--count); + + *value = locval; + + return (DIS_SUCCESS); + + break; + + case '0': + + return (DIS_LEADZRO); + + break; + + case '1': + + case '2': + + case '3': + + case '4': + + case '5': + + case '6': + + case '7': + + case '8': + + case '9': + + ndigs = c - '0'; + + if (count > 1) + { + if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) + { + return(DIS_EOD); + } + + cp = scratch; + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + break; + + *cp = c; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + break; + } + + while (--count) + { + if (((c = *++cp) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + ndigs = 10 * ndigs + c - '0'; + } + } /* END if (count > 1) */ + + return(disrsi_(stream, negate, value, ndigs)); + + /*NOTREACHED*/ + + break; + + case - 1: + + return(DIS_EOD); + + /*NOTREACHED*/ + + break; + + case -2: + + return(DIS_EOF); + + /*NOTREACHED*/ + + break; + + default: + + return(DIS_NONDIGIT); + + /*NOTREACHED*/ + + break; + } + + *negate = FALSE; + +overflow: + + *value = UINT_MAX; + + return(DIS_OVERFLOW); + } +``` diff --git a/tasks/csa159/pair_134585/pre_functions.txt b/tasks/csa159/pair_134585/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8f4a3d03219eb25597093f5346bacab79174ba4 --- /dev/null +++ b/tasks/csa159/pair_134585/pre_functions.txt @@ -0,0 +1,168 @@ +### File: src/lib/Libdis/disrsi_.c +```c +int disrsi_( + + int stream, + int *negate, + unsigned *value, + unsigned count) + + { + int c; + unsigned locval; + unsigned ndigs; + char *cp; + char scratch[DIS_BUFSIZ+1]; + + assert(negate != NULL); + assert(value != NULL); + assert(count); + assert(stream >= 0); + assert(dis_getc != NULL); + assert(dis_gets != NULL); + + memset(scratch, 0, DIS_BUFSIZ+1); + if (dis_umaxd == 0) + disiui_(); + + switch (c = (*dis_getc)(stream)) + { + + case '-': + + case '+': + + *negate = c == '-'; + + if ((*dis_gets)(stream, scratch, count) != (int)count) + { + return(DIS_EOD); + } + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + goto overflow; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + goto overflow; + } + + cp = scratch; + + locval = 0; + + do + { + if (((c = *cp++) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + locval = 10 * locval + c - '0'; + } + while (--count); + + *value = locval; + + return (DIS_SUCCESS); + + break; + + case '0': + + return (DIS_LEADZRO); + + break; + + case '1': + + case '2': + + case '3': + + case '4': + + case '5': + + case '6': + + case '7': + + case '8': + + case '9': + + ndigs = c - '0'; + + if (count > 1) + { + if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) + { + return(DIS_EOD); + } + + cp = scratch; + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + break; + + *cp = c; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + break; + } + + while (--count) + { + if (((c = *++cp) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + ndigs = 10 * ndigs + c - '0'; + } + } /* END if (count > 1) */ + + return(disrsi_(stream, negate, value, ndigs)); + + /*NOTREACHED*/ + + break; + + case - 1: + + return(DIS_EOD); + + /*NOTREACHED*/ + + break; + + case -2: + + return(DIS_EOF); + + /*NOTREACHED*/ + + break; + + default: + + return(DIS_NONDIGIT); + + /*NOTREACHED*/ + + break; + } + + *negate = FALSE; + +overflow: + + *value = UINT_MAX; + + return(DIS_OVERFLOW); + } +``` diff --git a/tasks/csa159/pair_134585/task_prompt.md b/tasks/csa159/pair_134585/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_134585/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_134943/checker_template.cpp b/tasks/csa159/pair_134943/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_134943/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_134943/config.json b/tasks/csa159/pair_134943/config.json new file mode 100644 index 0000000000000000000000000000000000000000..35c5c772f03c213cd3dcb5dec97b8cb31d2283d7 --- /dev/null +++ b/tasks/csa159/pair_134943/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "jedisct1_pure-ftpd", + "before_commit": "9a8d379512dd7af25965746d65f5d187c9cbda4c", + "after_commit": "bf6fcd4935e95128cf22af5924cdc8fe5c0579da", + "repo_path": "/workspace/repo/jedisct1/pure-ftpd", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jedisct1_pure-ftpd/ed78ab681e7025c3f6eee0106d504095995fee90/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jedisct1_pure-ftpd/ed78ab681e7025c3f6eee0106d504095995fee90/compile_commands.json", + "changed_files": [ + "src/utils.c" + ], + "commit_message": "pure_strcmp(): len(s2) can be > len(s1)\n\nReported by Antonio Morales from GitHub Security Labs, thanks!", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_134943/patch.diff b/tasks/csa159/pair_134943/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1833343f5cbaa01db5b1757f5d6eea68b1f88f66 --- /dev/null +++ b/tasks/csa159/pair_134943/patch.diff @@ -0,0 +1,15 @@ +diff --git a/src/utils.c b/src/utils.c +index f41492d..5e88104 100644 +--- a/src/utils.c ++++ b/src/utils.c +@@ -45,5 +45,9 @@ int pure_memcmp(const void * const b1_, const void * const b2_, size_t len) + + int pure_strcmp(const char * const s1, const char * const s2) + { +- return pure_memcmp(s1, s2, strlen(s1) + 1U); ++ const size_t s1_len = strlen(s1); ++ const size_t s2_len = strlen(s2); ++ const size_t len = (s1_len < s2_len) ? s1_len : s2_len; ++ ++ return pure_memcmp(s1, s2, len + 1); + } \ No newline at end of file diff --git a/tasks/csa159/pair_134943/post_functions.txt b/tasks/csa159/pair_134943/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..85e21e0d4b3a316a0adb5d0dcfe048ede9b735d8 --- /dev/null +++ b/tasks/csa159/pair_134943/post_functions.txt @@ -0,0 +1,11 @@ +### File: src/utils.c +```c +int pure_strcmp(const char * const s1, const char * const s2) +{ + const size_t s1_len = strlen(s1); + const size_t s2_len = strlen(s2); + const size_t len = (s1_len < s2_len) ? s1_len : s2_len; + + return pure_memcmp(s1, s2, len + 1); +} +``` diff --git a/tasks/csa159/pair_134943/pre_functions.txt b/tasks/csa159/pair_134943/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..d109c42a7ad9996a1ef2963184aa1555d471eb79 --- /dev/null +++ b/tasks/csa159/pair_134943/pre_functions.txt @@ -0,0 +1,27 @@ +### File: src/utils.c +```c + for (i = 0U; i < len; i++) { + d |= b1[i] ^ b2[i]; + } + return (int) ((1 & ((d - 1) >> 8)) - 1); +} + +#endif + +int pure_strcmp(const char * const s1, const char * const s2) +{ + return pure_memcmp(s1, s2, strlen(s1) + 1U); +} + +#endif + +int pure_strcmp(const char * const s1, const char * const s2) +{ + return pure_memcmp(s1, s2, strlen(s1) + 1U); +} + +int pure_strcmp(const char * const s1, const char * const s2) +{ + return pure_memcmp(s1, s2, strlen(s1) + 1U); +} +``` diff --git a/tasks/csa159/pair_134943/task_prompt.md b/tasks/csa159/pair_134943/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ec5b6cee7857dcea153d7747780963f04b7a594f --- /dev/null +++ b/tasks/csa159/pair_134943/task_prompt.md @@ -0,0 +1,376 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `syntax_only` + +### Current failure diagnosis + +- The rollout failed the semantic_mechanism check because it used local def-use analysis and CFG dominance even though the original defect is established by a direct call relation: pure_memcmp receives strlen(s1)+1 as its count while reading both s1 and s2. +- The implemented rule generalized the defect to memcmp, bcmp, pure_memcmp, arbitrary strlen(X)+K expressions, fixed extents, aliases, and guards, producing only a conservative superset of the patch-specific root cause. +- Successful differential detection did not prove mechanism suitability; the checker reported the buggy source and stayed clean on the patch, but semantic correctness remained partial and the mechanism was judged overkill. + +### Preserve from prior rollouts + +- Preserve successful compilation, code verification, and before/after validation. +- Preserve objective eligibility gate G6 and the existing differential result of one relevant buggy report and zero patched reports. +- Preserve an accepted or clean refinement outcome. +- Preserve semantic and process scores at or above their configured thresholds. +- Remain independent of patch line numbers, changed-line anchors, source paths, and patch-local textual fragments. +- Do not introduce function-body hardcoding or other patch-local hardcoding. + +### Required semantic proof + +- Identify a direct pure_memcmp call whose first two arguments are string operands and whose third argument is syntactically derived from strlen of exactly one of those operands plus the terminating-byte increment. +- Establish that the one-sided count supplies no bound derived from the other operand even though pure_memcmp reads the requested count from both operands. +- Report the potential out-of-bounds read because the other operand may be shorter than the operand used to compute the count. +- Recognize the patched local relation as safe: the selected length is the minimum of strlen values for both operands, followed by the one-byte increment. + +### Implementation constraints + +- Use a CSA call-oriented or AST callback that exposes the CallExpr and its argument expressions; no ProgramState fact tracking, interprocedural propagation, CFG construction, or dominance analysis is required. +- Match callees and strlen operations through declarations and AST nodes rather than source-text matching. +- Keep analysis intra-procedural and limited to the direct expression or immediately associated local declarations needed to recognize the original and patched forms. +- Emit the diagnostic at the vulnerable pure_memcmp CallExpr and highlight the third argument and the operand not represented in its bound. +- Keep the rule project-general enough to recognize equivalent pure_memcmp call expressions without depending on pure_strcmp, src/utils.c, or line 49. +- Conservatively skip calls when the required one-sided strlen provenance or operand correspondence cannot be established. + +### Validation checklist + +- Compile the fresh checker as a loadable CSA plugin and verify registration and loading succeed. +- Scan the original source and require exactly one relevant warning in src/utils.c::pure_strcmp. +- Scan the patched source and require zero warnings for the min(strlen(s1), strlen(s2))+1 form. +- Verify the warning location is the pure_memcmp call with zero-line distance from the vulnerable statement and that the count and under-bounded operand are highlighted. +- Test equivalent direct one-sided expressions for either operand and require detection without path or filename anchors. +- Test the patched ternary minimum, including the equivalent reversed comparison form, and require suppression. +- Run code verification and paired cross-validation, preserving one disappeared relevant warning, no unrelated disappeared warnings, and objective gate G6. +- Run refinement and require an accepted or clean result with semantic and process thresholds preserved. + +### Avoid and forbidden regressions + +- Do not reuse or reconstruct the prior checker or treat its implementation as the starting point. +- Do not repeat the CFG-dominance, guard implication, path approximation, alias, fixed-extent, or broad local def-use machinery that caused the mechanism mismatch. +- Do not broaden the sink set to memcmp or bcmp unless source evidence independently requires that scope. +- Do not infer safety or vulnerability from operand distinctness alone. +- Do not model strlen(Y)+1 as the allocation extent of Y or claim a definite over-read without evidence that Y is shorter. +- Do not trade away the accepted compile, differential, localization, refinement, hardcoding-free, or anchor-free results to improve the mechanism score. diff --git a/tasks/csa159/pair_135175/checker_template.cpp b/tasks/csa159/pair_135175/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135175/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_135175/config.json b/tasks/csa159/pair_135175/config.json new file mode 100644 index 0000000000000000000000000000000000000000..deaf3d93cf7243c86eeccb467dcd7735f9b28d22 --- /dev/null +++ b/tasks/csa159/pair_135175/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "libical_libical", + "before_commit": "04d84749e53db08c71ed0ce8b6ba5c11082743cd", + "after_commit": "830d9530817516377c2bc3b532798ce2c6b4765a", + "repo_path": "/workspace/repo/libical/libical", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libical_libical/19acf43794ad4c99f7e6687cb39424a82b737828/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libical_libical/19acf43794ad4c99f7e6687cb39424a82b737828/compile_commands.json", + "changed_files": [ + "src/libical/icalparser.c" + ], + "commit_message": "icalparser.c: don't create two ICAL_XLICINVALID_COMPONENT for an invalid component", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_135175/patch.diff b/tasks/csa159/pair_135175/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bb91afcd3bc7e76454598766266e8d30620204f6 --- /dev/null +++ b/tasks/csa159/pair_135175/patch.diff @@ -0,0 +1,17 @@ +diff --git a/src/libical/icalparser.c b/src/libical/icalparser.c +index 2735c9ac..36778909 100644 +--- a/src/libical/icalparser.c ++++ b/src/libical/icalparser.c +@@ -713,12 +713,6 @@ icalcomponent *icalparser_add_line(icalparser *parser, char *line) + + comp_kind = icalenum_string_to_component_kind(str); + +- if (comp_kind == ICAL_NO_COMPONENT) { +- c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT); +- insert_error(c, str, "Parse error in component name", +- ICAL_XLICERRORTYPE_COMPONENTPARSEERROR); +- } +- + c = icalcomponent_new(comp_kind); + + if (c == 0) { \ No newline at end of file diff --git a/tasks/csa159/pair_135175/post_functions.txt b/tasks/csa159/pair_135175/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..8a28aa4435b9fbdfb1737c5b0559230e82a90a33 --- /dev/null +++ b/tasks/csa159/pair_135175/post_functions.txt @@ -0,0 +1,250 @@ +### File: src/libical/icalparser.c +```c +icalcomponent *icalparser_add_line(icalparser *parser, char *line) +{ + char *str; + char *end; + int vcount = 0; + icalproperty *prop; + icalproperty_kind prop_kind; + icalvalue *value; + icalvalue_kind value_kind = ICAL_NO_VALUE; + + icalerror_check_arg_rz((parser != 0), "parser"); + + if (line == 0) { + parser->state = ICALPARSER_ERROR; + return 0; + } + + if (line_is_blank(line) == 1) { + return 0; + } + + /* Begin by getting the property name at the start of the line. The + property name may end up being "BEGIN" or "END" in which case it + is not really a property, but the marker for the start or end of + a component */ + + end = 0; + str = parser_get_prop_name(line, &end); + + if (str == 0 || *str == '\0') { + /* Could not get a property name */ + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + if (tail) { + insert_error( + tail, line, + "Got a data line, but could not find a property name or component begin tag", + ICAL_XLICERRORTYPE_COMPONENTPARSEERROR); + } + tail = 0; + parser->state = ICALPARSER_ERROR; + icalmemory_free_buffer(str); + str = NULL; + return 0; + } + + /********************************************************************** + * Handle begin and end of components + **********************************************************************/ + /* If the property name is BEGIN or END, we are actually + starting or ending a new component */ + + if (strcasecmp(str, "BEGIN") == 0) { + icalcomponent *c; + icalcomponent_kind comp_kind; + + parser->level++; + icalmemory_free_buffer(str); + str = parser_get_next_value(end, &end, value_kind); + + comp_kind = icalenum_string_to_component_kind(str); + + c = icalcomponent_new(comp_kind); + + if (c == 0) { + c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT); + insert_error(c, str, "Parse error in component name", + ICAL_XLICERRORTYPE_COMPONENTPARSEERROR); + } + + pvl_push(parser->components, c); + + parser->state = ICALPARSER_BEGIN_COMP; + + icalmemory_free_buffer(str); + str = NULL; + return 0; + + } else if (strcasecmp(str, "END") == 0) { + icalcomponent *tail; + + parser->level--; + icalmemory_free_buffer(str); + str = parser_get_next_value(end, &end, value_kind); + + /* Pop last component off of list and add it to the second-to-last */ + parser->root_component = pvl_pop(parser->components); + + tail = pvl_data(pvl_tail(parser->components)); + + if (tail != 0) { + icalcomponent_add_component(tail, parser->root_component); + } + + tail = 0; + icalmemory_free_buffer(str); + str = NULL; + + /* Return the component if we are back to the 0th level */ + if (parser->level == 0) { + icalcomponent *rtrn; + + if (pvl_count(parser->components) != 0) { + /* There are still components on the stack -- this means + that one of them did not have a proper "END" */ + pvl_push(parser->components, parser->root_component); + (void)icalparser_clean(parser); /* may reset parser->root_component */ + } + + assert(pvl_count(parser->components) == 0); + + parser->state = ICALPARSER_SUCCESS; + rtrn = parser->root_component; + parser->root_component = 0; + return rtrn; + + } else { + parser->state = ICALPARSER_END_COMP; + return 0; + } + } + + /* There is no point in continuing if we have not seen a + component yet */ + + if (pvl_data(pvl_tail(parser->components)) == 0) { + parser->state = ICALPARSER_ERROR; + icalmemory_free_buffer(str); + str = NULL; + return 0; + } + + /********************************************************************** + * Handle property names + **********************************************************************/ + + /* At this point, the property name really is a property name, + (Not a component name) so make a new property and add it to + the component */ + + prop_kind = icalproperty_string_to_kind(str); + + prop = icalproperty_new(prop_kind); + + if (prop != 0) { + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + if (prop_kind == ICAL_X_PROPERTY) { + icalproperty_set_x_name(prop, str); + } + + icalcomponent_add_property(tail, prop); + + /* Set the value kind for the default for this type of + property. This may be re-set by a VALUE parameter */ + value_kind = icalproperty_kind_to_value_kind(icalproperty_isa(prop)); + + } else { + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + insert_error(tail, str, "Parse error in property name", + ICAL_XLICERRORTYPE_PROPERTYPARSEERROR); + + tail = 0; + parser->state = ICALPARSER_ERROR; + icalmemory_free_buffer(str); + str = NULL; + return 0; + } + + icalmemory_free_buffer(str); + str = NULL; + + /********************************************************************** + * Handle parameter values + **********************************************************************/ + + /* Now, add any parameters to the last property */ + + while (1) { + if (*(end - 1) == ':') { + /* if the last separator was a ":" and the value is a + URL, icalparser_get_next_parameter will find the + ':' in the URL, so better break now. */ + break; + } + + icalmemory_free_buffer(str); + str = parser_get_next_parameter(end, &end); + strstriplt(str); + if (str != 0) { + char *name_heap = 0; + char *pvalue_heap = 0; + char name_stack[TMP_BUF_SIZE]; + char pvalue_stack[TMP_BUF_SIZE]; + char *name = name_stack; + char *pvalue = pvalue_stack; + + icalparameter *param = 0; + icalparameter_kind kind; + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + if (!parser_get_param_name_stack(str, name_stack, sizeof(name_stack), + pvalue_stack, sizeof(pvalue_stack))) { + name_heap = parser_get_param_name_heap(str, &pvalue_heap); + + name = name_heap; + pvalue = pvalue_heap; + + if (name_heap == 0) { + /* 'tail' defined above */ + insert_error(tail, str, "Cant parse parameter name", + ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR); + tail = 0; + break; + } + } + + kind = icalparameter_string_to_kind(name); + + if (kind == ICAL_X_PARAMETER) { + param = icalparameter_new(ICAL_X_PARAMETER); + if (param != 0) { + icalparameter_set_xname(param, name); + icalparameter_set_xvalue(param, pvalue); + } + } else if (kind == ICAL_IANA_PARAMETER) { + ical_unknown_token_handling tokHandlingSetting = + ical_get_unknown_token_handling_setting(); + if (tokHandlingSetting == ICAL_DISCARD_TOKEN) { + if (name_heap) { + icalmemory_free_buffer(name_heap); + name_heap = 0; + } + if (pvalue_heap) { + icalmemory_free_buffer(pvalue_heap); + pvalue_heap = 0; + } + continue; + } + + param = icalparameter_new(ICAL_IANA_PARAMETER); + + if (param != 0) { + icalparamete + +// ... (12351 more chars) +``` diff --git a/tasks/csa159/pair_135175/pre_functions.txt b/tasks/csa159/pair_135175/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..903a5c31a055ce1d36c45ae3097834390bded86e --- /dev/null +++ b/tasks/csa159/pair_135175/pre_functions.txt @@ -0,0 +1,247 @@ +### File: src/libical/icalparser.c +```c +icalcomponent *icalparser_add_line(icalparser *parser, char *line) +{ + char *str; + char *end; + int vcount = 0; + icalproperty *prop; + icalproperty_kind prop_kind; + icalvalue *value; + icalvalue_kind value_kind = ICAL_NO_VALUE; + + icalerror_check_arg_rz((parser != 0), "parser"); + + if (line == 0) { + parser->state = ICALPARSER_ERROR; + return 0; + } + + if (line_is_blank(line) == 1) { + return 0; + } + + /* Begin by getting the property name at the start of the line. The + property name may end up being "BEGIN" or "END" in which case it + is not really a property, but the marker for the start or end of + a component */ + + end = 0; + str = parser_get_prop_name(line, &end); + + if (str == 0 || *str == '\0') { + /* Could not get a property name */ + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + if (tail) { + insert_error( + tail, line, + "Got a data line, but could not find a property name or component begin tag", + ICAL_XLICERRORTYPE_COMPONENTPARSEERROR); + } + tail = 0; + parser->state = ICALPARSER_ERROR; + icalmemory_free_buffer(str); + str = NULL; + return 0; + } + + /********************************************************************** + * Handle begin and end of components + **********************************************************************/ + /* If the property name is BEGIN or END, we are actually + starting or ending a new component */ + + if (strcasecmp(str, "BEGIN") == 0) { + icalcomponent *c; + icalcomponent_kind comp_kind; + + parser->level++; + icalmemory_free_buffer(str); + str = parser_get_next_value(end, &end, value_kind); + + comp_kind = icalenum_string_to_component_kind(str); + + if (comp_kind == ICAL_NO_COMPONENT) { + c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT); + insert_error(c, str, "Parse error in component name", + ICAL_XLICERRORTYPE_COMPONENTPARSEERROR); + } + + c = icalcomponent_new(comp_kind); + + if (c == 0) { + c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT); + insert_error(c, str, "Parse error in component name", + ICAL_XLICERRORTYPE_COMPONENTPARSEERROR); + } + + pvl_push(parser->components, c); + + parser->state = ICALPARSER_BEGIN_COMP; + + icalmemory_free_buffer(str); + str = NULL; + return 0; + + } else if (strcasecmp(str, "END") == 0) { + icalcomponent *tail; + + parser->level--; + icalmemory_free_buffer(str); + str = parser_get_next_value(end, &end, value_kind); + + /* Pop last component off of list and add it to the second-to-last */ + parser->root_component = pvl_pop(parser->components); + + tail = pvl_data(pvl_tail(parser->components)); + + if (tail != 0) { + icalcomponent_add_component(tail, parser->root_component); + } + + tail = 0; + icalmemory_free_buffer(str); + str = NULL; + + /* Return the component if we are back to the 0th level */ + if (parser->level == 0) { + icalcomponent *rtrn; + + if (pvl_count(parser->components) != 0) { + /* There are still components on the stack -- this means + that one of them did not have a proper "END" */ + pvl_push(parser->components, parser->root_component); + (void)icalparser_clean(parser); /* may reset parser->root_component */ + } + + assert(pvl_count(parser->components) == 0); + + parser->state = ICALPARSER_SUCCESS; + rtrn = parser->root_component; + parser->root_component = 0; + return rtrn; + + } else { + parser->state = ICALPARSER_END_COMP; + return 0; + } + } + + /* There is no point in continuing if we have not seen a + component yet */ + + if (pvl_data(pvl_tail(parser->components)) == 0) { + parser->state = ICALPARSER_ERROR; + icalmemory_free_buffer(str); + str = NULL; + return 0; + } + + /********************************************************************** + * Handle property names + **********************************************************************/ + + /* At this point, the property name really is a property name, + (Not a component name) so make a new property and add it to + the component */ + + prop_kind = icalproperty_string_to_kind(str); + + prop = icalproperty_new(prop_kind); + + if (prop != 0) { + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + if (prop_kind == ICAL_X_PROPERTY) { + icalproperty_set_x_name(prop, str); + } + + icalcomponent_add_property(tail, prop); + + /* Set the value kind for the default for this type of + property. This may be re-set by a VALUE parameter */ + value_kind = icalproperty_kind_to_value_kind(icalproperty_isa(prop)); + + } else { + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + insert_error(tail, str, "Parse error in property name", + ICAL_XLICERRORTYPE_PROPERTYPARSEERROR); + + tail = 0; + parser->state = ICALPARSER_ERROR; + icalmemory_free_buffer(str); + str = NULL; + return 0; + } + + icalmemory_free_buffer(str); + str = NULL; + + /********************************************************************** + * Handle parameter values + **********************************************************************/ + + /* Now, add any parameters to the last property */ + + while (1) { + if (*(end - 1) == ':') { + /* if the last separator was a ":" and the value is a + URL, icalparser_get_next_parameter will find the + ':' in the URL, so better break now. */ + break; + } + + icalmemory_free_buffer(str); + str = parser_get_next_parameter(end, &end); + strstriplt(str); + if (str != 0) { + char *name_heap = 0; + char *pvalue_heap = 0; + char name_stack[TMP_BUF_SIZE]; + char pvalue_stack[TMP_BUF_SIZE]; + char *name = name_stack; + char *pvalue = pvalue_stack; + + icalparameter *param = 0; + icalparameter_kind kind; + icalcomponent *tail = pvl_data(pvl_tail(parser->components)); + + if (!parser_get_param_name_stack(str, name_stack, sizeof(name_stack), + pvalue_stack, sizeof(pvalue_stack))) { + name_heap = parser_get_param_name_heap(str, &pvalue_heap); + + name = name_heap; + pvalue = pvalue_heap; + + if (name_heap == 0) { + /* 'tail' defined above */ + insert_error(tail, str, "Cant parse parameter name", + ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR); + tail = 0; + break; + } + } + + kind = icalparameter_string_to_kind(name); + + if (kind == ICAL_X_PARAMETER) { + param = icalparameter_new(ICAL_X_PARAMETER); + if (param != 0) { + icalparameter_set_xname(param, name); + icalparameter_set_xvalue(param, pvalue); + } + } else if (kind == ICAL_IANA_PARAMETER) { + ical_unknown_token_handling tokHandlingSetting = + ical_get_unknown_token_handling_setting(); + if (tokHandlingSetting == ICAL_DISCARD_TOKEN) { + if (name_heap) { + icalmemory_free_buffer(name_heap); + name_heap = 0; + } + if (pvalue_heap) { + icalmemory_free_buffer(pvalu + +// ... (12603 more chars) +``` diff --git a/tasks/csa159/pair_135175/task_prompt.md b/tasks/csa159/pair_135175/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..92a852e4728348b7195e6676eb55858b6d196311 --- /dev/null +++ b/tasks/csa159/pair_135175/task_prompt.md @@ -0,0 +1,378 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `path_sensitive` + +### Current failure diagnosis + +- The rollout failed the process-quality threshold even though compilation, differential validation, scope checks, and semantic scoring passed. +- The design classified every unrecognized call as ownership-neutral consumption, which the review identified as overly broad and capable of false positives. +- The implementation could report when replacement was merely not disproven rather than requiring that the incoming binding be provably different, and a later analyzer failure on a false-positive fixture was not diagnosed or repaired. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6 and the accepted or clean refinement outcome. +- Retain path-sensitive CSA ownership tracking as the adequate minimum mechanism. +- Maintain semantic score at or above the configured threshold while matching the accepted invalid-placeholder overwrite contract. +- Keep the checker project-general within the documented ownership API and independent of patch anchors, source locations, analyzed function names, local variable names, removed text, and commit identifiers. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- At the overwrite operation, establish that the old binding denotes a live caller-owned allocation returned by a component constructor. +- Establish that the allocation was created with the ICAL_XLICINVALID_COMPONENT or ICAL_NO_COMPONENT sentinel associated with the invalid-component placeholder path. +- Establish along the current path that the placeholder was consumed by the relevant ownership-neutral parse-error handling operation. +- Establish that no recognized release or ownership transfer discharged the caller's ownership before the overwrite. +- Establish that the owning region is rebound to a value provably different from the old object, making the old allocation unreachable from that owner. +- Suppress the report for null or null-constrained constructor results, self-rebinds, provably equal values, and unknown or undefined incoming values. + +### Implementation constraints + +- Use check::PostCall to record symbolic constructor results and their invalid-placeholder fact in path-sensitive ProgramState. +- Use check::PreCall, or an equivalent call-state callback, to recognize the documented release and ownership-transfer APIs and to record only explicitly identified ownership-neutral consumption. +- Use check::Bind at the actual store, reading the pre-store value of the bound region and associating the diagnostic with that overwrite location. +- Track ownership by symbolic value or region state across intervening statements and calls; do not rely on dead-symbol, function-exit, AST-only, or source-text matching. +- Recognize only the documented libical constructor, releaser, transfer APIs, and public sentinel declarations; do not treat arbitrary unknown callees as consumption or transfer. +- Preserve parameter-region handling and report locality, including the lost allocation and rebound owning region as diagnostic-interest context. +- Keep matching independent of file names, function names, variable names, line numbers, removed source spans, and commit identifiers. + +### Validation checklist + +- Compile the new checker successfully and verify the produced analyzer artifact before scanning. +- Run the before/after paired scan: report the motivating defect in the vulnerable source and produce no report in the patched source. +- Verify that the warning is attached to the pointer overwrite bind, is near the changed code, and identifies the lost allocation rather than symbol death or function exit. +- Run the relevant false-positive fixture with release, ownership transfer, self-rebind, null-result, and unknown-value paths. +- Test that an unrelated unrecognized call does not automatically satisfy the consumption condition. +- Confirm project-general behavior across non-patched code and absence of patch-anchor or patch-local hardcoding. +- Run refinement and investigate any analyzer failure or false-positive result before accepting the rollout. + +### Avoid and forbidden regressions + +- Do not use syntax-only matching, dead-store matching, check::DeadSymbols-only reporting, or check::EndFunction leak reporting. +- Do not treat every call that receives the component as ownership-neutral consumption. +- Do not report merely because replacement is not disproven; require path evidence that the incoming value differs from the old allocation. +- Do not treat pointer escape or an arbitrary call as ownership transfer. +- Do not weaken the invalid-placeholder, ownership-neutral-consumption, release/transfer, or overwrite requirements to improve scan counts. +- Do not regress compile, before/after differential detection, G6 eligibility, semantic adequacy, refinement acceptance, anchor freedom, or hardcoding freedom. diff --git a/tasks/csa159/pair_135384/checker_template.cpp b/tasks/csa159/pair_135384/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135384/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_135384/config.json b/tasks/csa159/pair_135384/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a3c0194d81e5b54e90ea2a479e0f8fbec3b4f83d --- /dev/null +++ b/tasks/csa159/pair_135384/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "mity_md4c", + "before_commit": "bcdbd126a5c099981b6d637b09d376dc22fa0f46", + "after_commit": "22ca89a3008966c4316d6b0a158b1a49f9038df0", + "repo_path": "/workspace/repo/mity/md4c", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/mity_md4c/db7d1c92ec34cae9624be373726e36f22a7d7019/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/mity_md4c/db7d1c92ec34cae9624be373726e36f22a7d7019/compile_commands.json", + "changed_files": [ + "src/md4c.c" + ], + "commit_message": "Fix ISANYOF encountering a zero byte in the input.\n\nWhen it happened, it could lead to unexpected results, including broken\ninternal state of the parser.\n\nFixes #130.", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_135384/patch.diff b/tasks/csa159/pair_135384/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..04da5765561a2bc18e63d40091194b7184414b49 --- /dev/null +++ b/tasks/csa159/pair_135384/patch.diff @@ -0,0 +1,34 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 5176d97..d7967d2 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -2,6 +2,16 @@ + # MD4C Change Log + + ++## Next Version (Work in Progress) ++ ++Fixes: ++ ++* [#130](https://github.com/mity/md4c/issues/130): ++ Fix `ISANYOF` macro, which could provide unexpected results when encountering ++ zero byte in the input text; in some cases leading to broken internal state ++ of the parser. ++ ++ + ## Version 0.4.5 + + Fixes: +diff --git a/src/md4c.c b/src/md4c.c +index 6324446..0119e7a 100644 +--- a/src/md4c.c ++++ b/src/md4c.c +@@ -276,7 +276,7 @@ struct MD_VERBATIMLINE_tag { + /* Character classification. + * Note we assume ASCII compatibility of code points < 128 here. */ + #define ISIN_(ch, ch_min, ch_max) ((ch_min) <= (unsigned)(ch) && (unsigned)(ch) <= (ch_max)) +-#define ISANYOF_(ch, palette) (md_strchr((palette), (ch)) != NULL) ++#define ISANYOF_(ch, palette) ((ch) != _T('\0') && md_strchr((palette), (ch)) != NULL) + #define ISANYOF2_(ch, ch1, ch2) ((ch) == (ch1) || (ch) == (ch2)) + #define ISANYOF3_(ch, ch1, ch2, ch3) ((ch) == (ch1) || (ch) == (ch2) || (ch) == (ch3)) + #define ISASCII_(ch) ((unsigned)(ch) <= 127) \ No newline at end of file diff --git a/tasks/csa159/pair_135384/post_functions.txt b/tasks/csa159/pair_135384/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..893d8c305dacd675bcfedfa42bb009317a222391 --- /dev/null +++ b/tasks/csa159/pair_135384/post_functions.txt @@ -0,0 +1,256 @@ +### File: src/md4c.c +```c +/* + * MD4C: Markdown parser for C + * (http://github.com/mity/md4c) + * + * Copyright (c) 2016-2020 Martin Mitas + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "md4c.h" + +#include +#include +#include +#include + + +/***************************** + *** Miscellaneous Stuff *** + *****************************/ + +#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199409L + /* C89/90 or old compilers in general may not understand "inline". */ + #if defined __GNUC__ + #define inline __inline__ + #elif defined _MSC_VER + #define inline __inline + #else + #define inline + #endif +#endif + +/* Make the UTF-8 support the default. */ +#if !defined MD4C_USE_ASCII && !defined MD4C_USE_UTF8 && !defined MD4C_USE_UTF16 + #define MD4C_USE_UTF8 +#endif + +/* Magic for making wide literals with MD4C_USE_UTF16. */ +#ifdef _T + #undef _T +#endif +#if defined MD4C_USE_UTF16 + #define _T(x) L##x +#else + #define _T(x) x +#endif + +/* Misc. macros. */ +#define SIZEOF_ARRAY(a) (sizeof(a) / sizeof(a[0])) + +#define STRINGIZE_(x) #x +#define STRINGIZE(x) STRINGIZE_(x) + +#ifndef TRUE + #define TRUE 1 + #define FALSE 0 +#endif + + +/************************ + *** Internal Types *** + ************************/ + +/* These are omnipresent so lets save some typing. */ +#define CHAR MD_CHAR +#define SZ MD_SIZE +#define OFF MD_OFFSET + +typedef struct MD_MARK_tag MD_MARK; +typedef struct MD_BLOCK_tag MD_BLOCK; +typedef struct MD_CONTAINER_tag MD_CONTAINER; +typedef struct MD_REF_DEF_tag MD_REF_DEF; + + +/* During analyzes of inline marks, we need to manage some "mark chains", + * of (yet unresolved) openers. This structure holds start/end of the chain. + * The chain internals are then realized through MD_MARK::prev and ::next. + */ +typedef struct MD_MARKCHAIN_tag MD_MARKCHAIN; +struct MD_MARKCHAIN_tag { + int head; /* Index of first mark in the chain, or -1 if empty. */ + int tail; /* Index of last mark in the chain, or -1 if empty. */ +}; + +/* Context propagated through all the parsing. */ +typedef struct MD_CTX_tag MD_CTX; +struct MD_CTX_tag { + /* Immutable stuff (parameters of md_parse()). */ + const CHAR* text; + SZ size; + MD_PARSER parser; + void* userdata; + + /* When this is true, it allows some optimizations. */ + int doc_ends_with_newline; + + /* Helper temporary growing buffer. */ + CHAR* buffer; + unsigned alloc_buffer; + + /* Reference definitions. */ + MD_REF_DEF* ref_defs; + int n_ref_defs; + int alloc_ref_defs; + void** ref_def_hashtable; + int ref_def_hashtable_size; + + /* Stack of inline/span markers. + * This is only used for parsing a single block contents but by storing it + * here we may reuse the stack for subsequent blocks; i.e. we have fewer + * (re)allocations. */ + MD_MARK* marks; + int n_marks; + int alloc_marks; + +#if defined MD4C_USE_UTF16 + char mark_char_map[128]; +#else + char mark_char_map[256]; +#endif + + /* For resolving of inline spans. */ + MD_MARKCHAIN mark_chains[13]; +#define PTR_CHAIN (ctx->mark_chains[0]) +#define TABLECELLBOUNDARIES (ctx->mark_chains[1]) +#define ASTERISK_OPENERS_extraword_mod3_0 (ctx->mark_chains[2]) +#define ASTERISK_OPENERS_extraword_mod3_1 (ctx->mark_chains[3]) +#define ASTERISK_OPENERS_extraword_mod3_2 (ctx->mark_chains[4]) +#define ASTERISK_OPENERS_intraword_mod3_0 (ctx->mark_chains[5]) +#define ASTERISK_OPENERS_intraword_mod3_1 (ctx->mark_chains[6]) +#define ASTERISK_OPENERS_intraword_mod3_2 (ctx->mark_chains[7]) +#define UNDERSCORE_OPENERS (ctx->mark_chains[8]) +#define TILDE_OPENERS_1 (ctx->mark_chains[9]) +#define TILDE_OPENERS_2 (ctx->mark_chains[10]) +#define BRACKET_OPENERS (ctx->mark_chains[11]) +#define DOLLAR_OPENERS (ctx->mark_chains[12]) +#define OPENERS_CHAIN_FIRST 2 +#define OPENERS_CHAIN_LAST 12 + + int n_table_cell_boundaries; + + /* For resolving links. */ + int unresolved_link_head; + int unresolved_link_tail; + + /* For resolving raw HTML. */ + OFF html_comment_horizon; + OFF html_proc_instr_horizon; + OFF html_decl_horizon; + OFF html_cdata_horizon; + + /* For block analysis. + * Notes: + * -- It holds MD_BLOCK as well as MD_LINE structures. After each + * MD_BLOCK, its (multiple) MD_LINE(s) follow. + * -- For MD_BLOCK_HTML and MD_BLOCK_CODE, MD_VERBATIMLINE(s) are used + * instead of MD_LINE(s). + */ + void* block_bytes; + MD_BLOCK* current_block; + int n_block_bytes; + int alloc_block_bytes; + + /* For container block analysis. */ + MD_CONTAINER* containers; + int n_containers; + int alloc_containers; + + /* Minimal indentation to call the block "indented code block". */ + unsigned code_indent_offset; + + /* Contextual info for line analysis. */ + SZ code_fence_length; /* For checking closing fence length. */ + int html_block_type; /* For checking closing raw HTML condition. */ + int last_line_has_list_loosening_effect; + int last_list_item_starts_with_two_blank_lines; +}; + +enum MD_LINETYPE_tag { + MD_LINE_BLANK, + MD_LINE_HR, + MD_LINE_ATXHEADER, + MD_LINE_SETEXTHEADER, + MD_LINE_SETEXTUNDERLINE, + MD_LINE_INDENTEDCODE, + MD_LINE_FENCEDCODE, + MD_LINE_HTML, + MD_LINE_TEXT, + MD_LINE_TABLE, + MD_LINE_TABLEUNDERLINE +}; +typedef enum MD_LINETYPE_tag MD_LINETYPE; + +typedef struct MD_LINE_ANALYSIS_tag MD_LINE_ANALYSIS; +struct MD_LINE_ANALYSIS_tag { + MD_LINETYPE type : 16; + unsigned data : 16; + OFF beg; + OFF end; + unsigned indent; /* Indentation level. */ +}; + +typedef struct MD_LINE_tag MD_LINE; +struct MD_LINE_tag { + OFF beg; + OFF end; +}; + +typedef struct MD_VERBATIMLINE_tag MD_VERBATIMLINE; +struct MD_VERBATIMLINE_tag { + OFF beg; + OFF end; + OFF indent; +}; + + +/******************* + *** Debugging *** + *******************/ + +#define MD_LOG(msg) \ + do { \ + if(ctx->parser.debug_log != NULL) \ + ctx->parser.debug_log((msg), ctx->userdata); \ + } while(0) + +#ifdef DEBUG + #define MD_ASSERT(cond) \ + do { \ + if(!(cond)) { \ + MD_LOG(__FILE__ ":" STRINGIZE(__LINE__) ": " \ + "Assertion '" STRINGIZE(cond) "' failed."); \ + exit(1); \ + } \ + + +// ... (211656 more chars) +``` diff --git a/tasks/csa159/pair_135384/pre_functions.txt b/tasks/csa159/pair_135384/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b1e7adeec02c00912fb4f692d61c036b836e710b --- /dev/null +++ b/tasks/csa159/pair_135384/pre_functions.txt @@ -0,0 +1,256 @@ +### File: src/md4c.c +```c +/* + * MD4C: Markdown parser for C + * (http://github.com/mity/md4c) + * + * Copyright (c) 2016-2020 Martin Mitas + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "md4c.h" + +#include +#include +#include +#include + + +/***************************** + *** Miscellaneous Stuff *** + *****************************/ + +#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199409L + /* C89/90 or old compilers in general may not understand "inline". */ + #if defined __GNUC__ + #define inline __inline__ + #elif defined _MSC_VER + #define inline __inline + #else + #define inline + #endif +#endif + +/* Make the UTF-8 support the default. */ +#if !defined MD4C_USE_ASCII && !defined MD4C_USE_UTF8 && !defined MD4C_USE_UTF16 + #define MD4C_USE_UTF8 +#endif + +/* Magic for making wide literals with MD4C_USE_UTF16. */ +#ifdef _T + #undef _T +#endif +#if defined MD4C_USE_UTF16 + #define _T(x) L##x +#else + #define _T(x) x +#endif + +/* Misc. macros. */ +#define SIZEOF_ARRAY(a) (sizeof(a) / sizeof(a[0])) + +#define STRINGIZE_(x) #x +#define STRINGIZE(x) STRINGIZE_(x) + +#ifndef TRUE + #define TRUE 1 + #define FALSE 0 +#endif + + +/************************ + *** Internal Types *** + ************************/ + +/* These are omnipresent so lets save some typing. */ +#define CHAR MD_CHAR +#define SZ MD_SIZE +#define OFF MD_OFFSET + +typedef struct MD_MARK_tag MD_MARK; +typedef struct MD_BLOCK_tag MD_BLOCK; +typedef struct MD_CONTAINER_tag MD_CONTAINER; +typedef struct MD_REF_DEF_tag MD_REF_DEF; + + +/* During analyzes of inline marks, we need to manage some "mark chains", + * of (yet unresolved) openers. This structure holds start/end of the chain. + * The chain internals are then realized through MD_MARK::prev and ::next. + */ +typedef struct MD_MARKCHAIN_tag MD_MARKCHAIN; +struct MD_MARKCHAIN_tag { + int head; /* Index of first mark in the chain, or -1 if empty. */ + int tail; /* Index of last mark in the chain, or -1 if empty. */ +}; + +/* Context propagated through all the parsing. */ +typedef struct MD_CTX_tag MD_CTX; +struct MD_CTX_tag { + /* Immutable stuff (parameters of md_parse()). */ + const CHAR* text; + SZ size; + MD_PARSER parser; + void* userdata; + + /* When this is true, it allows some optimizations. */ + int doc_ends_with_newline; + + /* Helper temporary growing buffer. */ + CHAR* buffer; + unsigned alloc_buffer; + + /* Reference definitions. */ + MD_REF_DEF* ref_defs; + int n_ref_defs; + int alloc_ref_defs; + void** ref_def_hashtable; + int ref_def_hashtable_size; + + /* Stack of inline/span markers. + * This is only used for parsing a single block contents but by storing it + * here we may reuse the stack for subsequent blocks; i.e. we have fewer + * (re)allocations. */ + MD_MARK* marks; + int n_marks; + int alloc_marks; + +#if defined MD4C_USE_UTF16 + char mark_char_map[128]; +#else + char mark_char_map[256]; +#endif + + /* For resolving of inline spans. */ + MD_MARKCHAIN mark_chains[13]; +#define PTR_CHAIN (ctx->mark_chains[0]) +#define TABLECELLBOUNDARIES (ctx->mark_chains[1]) +#define ASTERISK_OPENERS_extraword_mod3_0 (ctx->mark_chains[2]) +#define ASTERISK_OPENERS_extraword_mod3_1 (ctx->mark_chains[3]) +#define ASTERISK_OPENERS_extraword_mod3_2 (ctx->mark_chains[4]) +#define ASTERISK_OPENERS_intraword_mod3_0 (ctx->mark_chains[5]) +#define ASTERISK_OPENERS_intraword_mod3_1 (ctx->mark_chains[6]) +#define ASTERISK_OPENERS_intraword_mod3_2 (ctx->mark_chains[7]) +#define UNDERSCORE_OPENERS (ctx->mark_chains[8]) +#define TILDE_OPENERS_1 (ctx->mark_chains[9]) +#define TILDE_OPENERS_2 (ctx->mark_chains[10]) +#define BRACKET_OPENERS (ctx->mark_chains[11]) +#define DOLLAR_OPENERS (ctx->mark_chains[12]) +#define OPENERS_CHAIN_FIRST 2 +#define OPENERS_CHAIN_LAST 12 + + int n_table_cell_boundaries; + + /* For resolving links. */ + int unresolved_link_head; + int unresolved_link_tail; + + /* For resolving raw HTML. */ + OFF html_comment_horizon; + OFF html_proc_instr_horizon; + OFF html_decl_horizon; + OFF html_cdata_horizon; + + /* For block analysis. + * Notes: + * -- It holds MD_BLOCK as well as MD_LINE structures. After each + * MD_BLOCK, its (multiple) MD_LINE(s) follow. + * -- For MD_BLOCK_HTML and MD_BLOCK_CODE, MD_VERBATIMLINE(s) are used + * instead of MD_LINE(s). + */ + void* block_bytes; + MD_BLOCK* current_block; + int n_block_bytes; + int alloc_block_bytes; + + /* For container block analysis. */ + MD_CONTAINER* containers; + int n_containers; + int alloc_containers; + + /* Minimal indentation to call the block "indented code block". */ + unsigned code_indent_offset; + + /* Contextual info for line analysis. */ + SZ code_fence_length; /* For checking closing fence length. */ + int html_block_type; /* For checking closing raw HTML condition. */ + int last_line_has_list_loosening_effect; + int last_list_item_starts_with_two_blank_lines; +}; + +enum MD_LINETYPE_tag { + MD_LINE_BLANK, + MD_LINE_HR, + MD_LINE_ATXHEADER, + MD_LINE_SETEXTHEADER, + MD_LINE_SETEXTUNDERLINE, + MD_LINE_INDENTEDCODE, + MD_LINE_FENCEDCODE, + MD_LINE_HTML, + MD_LINE_TEXT, + MD_LINE_TABLE, + MD_LINE_TABLEUNDERLINE +}; +typedef enum MD_LINETYPE_tag MD_LINETYPE; + +typedef struct MD_LINE_ANALYSIS_tag MD_LINE_ANALYSIS; +struct MD_LINE_ANALYSIS_tag { + MD_LINETYPE type : 16; + unsigned data : 16; + OFF beg; + OFF end; + unsigned indent; /* Indentation level. */ +}; + +typedef struct MD_LINE_tag MD_LINE; +struct MD_LINE_tag { + OFF beg; + OFF end; +}; + +typedef struct MD_VERBATIMLINE_tag MD_VERBATIMLINE; +struct MD_VERBATIMLINE_tag { + OFF beg; + OFF end; + OFF indent; +}; + + +/******************* + *** Debugging *** + *******************/ + +#define MD_LOG(msg) \ + do { \ + if(ctx->parser.debug_log != NULL) \ + ctx->parser.debug_log((msg), ctx->userdata); \ + } while(0) + +#ifdef DEBUG + #define MD_ASSERT(cond) \ + do { \ + if(!(cond)) { \ + MD_LOG(__FILE__ ":" STRINGIZE(__LINE__) ": " \ + "Assertion '" STRINGIZE(cond) "' failed."); \ + exit(1); \ + } \ + + +// ... (211634 more chars) +``` diff --git a/tasks/csa159/pair_135384/task_prompt.md b/tasks/csa159/pair_135384/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..fcd2add9019cb33bbaecb54fb7e08d20c7f4132c --- /dev/null +++ b/tasks/csa159/pair_135384/task_prompt.md @@ -0,0 +1,379 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `control_flow` + +### Current failure diagnosis + +- The independent rollout failed only on refinement_accepted: the judge returned feedback_required after one round and never reached an accepted or clean refinement outcome. +- The run was framework-budget-salvaged as plausible, so the checker was never independently proven through a completed refinement loop despite later compile, differential, and semantic gates passing. +- Unresolved blocker remains that refinement is not accepted or clean; a fresh synthesis must close that process gap rather than reuse a salvaged artifact. + +### Preserve from prior rollouts + +- Retain successful plugin compile, paired before/after scans, and code verification as already achieved on the last passing harness. +- Retain objective eligibility gate G6 (all objective items passed, 49/49). +- Retain an adequate CSA mechanism no weaker than call-site matching of strchr/wcschr plus a local AST check for the dominating NUL guard the patch introduces. +- Retain semantic score at or above the accepted 9.0 adequate contract. +- Retain process quality at or above the last passing process score of 86.96. +- Remain free of patch-anchor dependence. +- Remain free of patch-local hardcoding of identifiers, literals, or locations unique to the fix hunk. + +### Required semantic proof + +- A resolved strchr or wcschr CallExpr is a sink only when its return value is consumed as a character-membership test: compared with NULL/0, logically negated, or used as a boolean &&/||/if/while/for/do/ternary condition. +- The sink is unsafe when argument 1 is not a compile-time integer constant, so the searched character may be NUL, and no dominating guard proves that same argument non-NUL before the call is evaluated. +- Pre-patch ISANYOF_ expands to md_strchr((palette), (ch)) != NULL; when ch is zero, strchr/wcschr returns the palette terminator (non-NULL) and the membership test spuriously succeeds, which can corrupt parser state. +- Post-patch ((ch) != _T('\0') && md_strchr((palette), (ch)) != NULL) is safe because C && short-circuit makes the NUL inequality dominate the call, so the checker must stay silent. +- Equivalent dominating guards are also safe: || with LHS ch == '\0' and the call on the RHS, or an if/while/for/ternary condition (or conjunct/disjunct of it) that proves the same argument non-NUL on the branch that contains the call. +- A compile-time constant character argument is safe either as 0 (intentional terminator search) or as non-zero (statically non-NUL). + +### Implementation constraints + +- Implement with check::ASTCodeBody and ParentMap over each function body so membership-use and guard dominance are proven on the AST/CFG of the enclosing expression; do not use check::PreCall, ConstraintManager::assumeDual, ProgramState, taint, or PathSensitiveBugReport. +- Treat only direct callees named strchr or wcschr with at least two arguments as sinks; do not encode md4c type names, ISANYOF_, md_strchr, palette literals, file paths, or line numbers in the match logic. +- Detect membership-use by walking parents through ParenExpr and ImplicitCastExpr to a NULL comparison, unary !, &&/|| operand, or branch/loop/ternary condition. +- Prove dominance structurally: the guard operand and CallExpr argument 1 are the same expression after IgnoreParenImpCasts using spelling-location ranges, and a comparison against 0 on && LHS, inverted || LHS, or the taken enclosing branch guarantees non-NUL. +- Emit a BasicBugReport at SourceManager::getSpellingLoc of the membership expression, keyed uniquely by that spelling encoding, so a macro-body bug reports once on the definition span around src/md4c.c:279 instead of at every expansion. +- Keep the proof local to one function body; do not require interprocedural propagation. + +### Validation checklist + +- Compile the new plugin as a CSA shared object with a registered checker class, ASTCodeBody callback, and report path. +- Before-patch scan of src/md4c.c must produce exactly one warning at the ISANYOF_ macro definition spelling site (src/md4c.c:279), collapsing all expansions. +- After-patch scan must produce zero warnings because the new (ch) != _T('\0') conjunct dominates the membership call in every expansion. +- The disappeared diagnostic must sit on the patched global-declaration span (distance 0) with no reports in non-patched functions and no new patched-tree findings. +- Re-establish G6: differential detection, diagnostic sharpness, FP/scope control, and CSA implementation quality all pass. +- Refinement must finish accepted and clean; do not stop at feedback_required, not_run, or budget salvage. +- Confirm after-tree silence is caused by the dominating NUL guard being recognized, not by renaming the callee or special-casing the patched macro. + +### Avoid and forbidden regressions + +- Do not reconstruct, copy, repair, or resume any prior checker implementation. +- Do not regress hard_validation, objective_gate, semantic_mechanism, semantic_score, process_score, anchor_free, or hardcoding_free. +- Do not key detection on ISANYOF_, md_strchr, _T, MD_CHAR, palette contents, CHANGELOG text, or src/md4c.c:279. +- Do not report memchr, memmem, or non-membership strchr/wcschr uses such as pointer arithmetic or terminator-scan loops. +- Do not attach diagnostics to macro expansion locations or path-sensitive error nodes that fan out per use-site. +- Do not weaken the accepted contract to a bare callee-name match that would still fire after the && NUL guard is added. +- Do not leave the rollout in a salvaged or plausible state without an accepted refinement outcome. diff --git a/tasks/csa159/pair_135405/checker_template.cpp b/tasks/csa159/pair_135405/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135405/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_135405/config.json b/tasks/csa159/pair_135405/config.json new file mode 100644 index 0000000000000000000000000000000000000000..cbe8ca6022781a5eb6e578077c16d6b0c2f52cca --- /dev/null +++ b/tasks/csa159/pair_135405/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "mwarning_KadNode", + "before_commit": "d52f6f543faa5304f23d2275bf248cd62b39322a", + "after_commit": "91b38304755310458e01243214d8fbe792ba887d", + "repo_path": "/workspace/repo/mwarning/KadNode", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/mwarning_KadNode/d52f6f543faa5304f23d2275bf248cd62b39322a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/mwarning_KadNode/d52f6f543faa5304f23d2275bf248cd62b39322a/compile_commands.json", + "changed_files": [ + "src/ext-cmd.c" + ], + "commit_message": "cmd: check input length, fixes #79", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_135405/patch.diff b/tasks/csa159/pair_135405/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..27de3a21c5057410fa763a7b92f579b2bb2e8ab9 --- /dev/null +++ b/tasks/csa159/pair_135405/patch.diff @@ -0,0 +1,65 @@ +diff --git a/src/ext-cmd.c b/src/ext-cmd.c +index c14b18b..1b5495f 100644 +--- a/src/ext-cmd.c ++++ b/src/ext-cmd.c +@@ -335,6 +335,33 @@ static int select_read(int sockfd, char buffer[], int bufsize, struct timeval *t + } + #endif + ++static int append_strings(char buf[], size_t bufsize, int argc, char *argv[]) ++{ ++ int i; ++ int len; ++ ++ // Check input length ++ len = 0; ++ for (i = 0; i < argc; ++i) { ++ len += 1 + strlen(argv[i]); ++ if(len >= bufsize) { ++ return EXIT_FAILURE; ++ } ++ } ++ ++ // Concatenate strings ++ buf[0] = '\0'; ++ for (i = 0; i < argc; ++i) { ++ if (i) { ++ strcat(buf, " "); ++ } ++ strcat(buf, argv[i]); ++ } ++ strcat(buf, "\n"); ++ ++ return EXIT_SUCCESS; ++} ++ + int cmd_client(int argc, char *argv[]) + { + char buffer[256]; +@@ -343,7 +370,6 @@ int cmd_client(int argc, char *argv[]) + struct timeval tv; + ssize_t size; + int sock; +- size_t i; + + // Default unix socket path + path = CMD_PATH; +@@ -369,15 +395,10 @@ int cmd_client(int argc, char *argv[]) + } + } + +- // Construct request string from args +- buffer[0] = '\0'; +- for (i = 0; i < argc; ++i) { +- if (i) { +- strcat(buffer, " "); +- } +- strcat(buffer, argv[i]); ++ if (EXIT_FAILURE == append_strings(buffer, sizeof(buffer), argc, argv)) { ++ fprintf(stderr, "Input to long\n"); ++ return EXIT_FAILURE; + } +- strcat(buffer, "\n"); + + sock = socket(AF_LOCAL, SOCK_STREAM, 0); + if (sock < 0) { \ No newline at end of file