code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
def test_can_parse_json_string():
request = mock.MagicMock()
request.method = "POST"
request.content_type = "application/json"
request.get_json = mock.MagicMock()
request.get_json.return_value = '{"name": "hello2"}'
msg = _get_request_message(CreateExperiment(), flask_request=request)
assert msg.name == "hello2" | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_can_block_post_request_with_missing_content_type():
request = mock.MagicMock()
request.method = "POST"
request.content_type = None
request.get_json = mock.MagicMock()
request.get_json.return_value = {"name": "hello"}
with pytest.raises(MlflowException, match=r"Bad Request. Content-Type"):
_get_request_message(CreateExperiment(), flask_request=request) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_can_parse_json():
request = mock.MagicMock()
request.method = "POST"
request.content_type = "application/json"
request.get_json = mock.MagicMock()
request.get_json.return_value = {"name": "hello"}
msg = _get_request_message(CreateExperiment(), flask_request=request)
assert msg.name == "hello" | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_can_parse_post_json_with_content_type_params():
request = mock.MagicMock()
request.method = "POST"
request.content_type = "application/json; charset=utf-8"
request.get_json = mock.MagicMock()
request.get_json.return_value = {"name": "hello"}
msg = _get_request_message(CreateExperiment(), flask_request=request)
assert msg.name == "hello" | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def to_html(self) -> str:
"""
Returns a rendered HTML representing the content of the tab.
:return: a HTML string
"""
from jinja2 import BaseLoader
from jinja2.sandbox import SandboxedEnvironment
j2_env = SandboxedEnvironment(loader=BaseLoader()).from_string(self.template)
return j2_env.render({**self._context}) | 1 | Python | CWE-1336 | Improper Neutralization of Special Elements Used in a Template Engine | The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine. | https://cwe.mitre.org/data/definitions/1336.html | safe |
def is_local_uri(uri, is_tracking_or_registry_uri=True):
"""
Returns true if the specified URI is a local file path (/foo or file:/foo).
:param uri: The URI.
:param is_tracking_uri: Whether or not the specified URI is an MLflow Tracking or MLflow
Model Registry URI. Examples of other URIs are MLflow artifact URIs,
filesystem paths, etc.
"""
if uri == "databricks" and is_tracking_or_registry_uri:
return False
if is_windows() and uri.startswith("\\\\"):
# windows network drive path looks like: "\\<server name>\path\..."
return False
parsed_uri = urllib.parse.urlparse(uri)
scheme = parsed_uri.scheme
if scheme == "":
return True
if parsed_uri.hostname and not (
parsed_uri.hostname == "."
or parsed_uri.hostname.startswith("localhost")
or parsed_uri.hostname.startswith("127.0.0.1")
):
return False
if scheme == "file":
return True
if is_windows() and len(scheme) == 1 and scheme.lower() == pathlib.Path(uri).drive.lower()[0]:
return True
return False | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_is_local_uri():
assert is_local_uri("mlruns")
assert is_local_uri("./mlruns")
assert is_local_uri("file:///foo/mlruns")
assert is_local_uri("file:foo/mlruns")
assert is_local_uri("file://./mlruns")
assert is_local_uri("file://localhost/mlruns")
assert is_local_uri("file://localhost:5000/mlruns")
assert is_local_uri("file://127.0.0.1/mlruns")
assert is_local_uri("file://127.0.0.1:5000/mlruns")
assert is_local_uri("//proc/self/root")
assert is_local_uri("/proc/self/root")
assert not is_local_uri("file://myhostname/path/to/file")
assert not is_local_uri("https://whatever")
assert not is_local_uri("http://whatever")
assert not is_local_uri("databricks")
assert not is_local_uri("databricks:whatever")
assert not is_local_uri("databricks://whatever") | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def validate_path_is_safe(path):
"""
Validates that the specified path is safe to join with a trusted prefix. This is a security
measure to prevent path traversal attacks.
A valid path should:
not contain separators other than '/'
not contain .. to navigate to parent dir in path
not be an absolute path
"""
from mlflow.utils.file_utils import local_file_uri_to_path
# We must decode URL before validating it
path = urllib.parse.unquote(path)
exc = MlflowException("Invalid path", error_code=INVALID_PARAMETER_VALUE)
if any((s in path) for s in ("#", "%23")):
raise exc
if is_file_uri(path):
path = local_file_uri_to_path(path)
if (
any((s in path) for s in _OS_ALT_SEPS)
or ".." in path.split("/")
or pathlib.PureWindowsPath(path).is_absolute()
or pathlib.PurePosixPath(path).is_absolute()
or (is_windows() and len(path) >= 2 and path[1] == ":")
):
raise exc | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def validate_path_is_safe(path):
"""
Validates that the specified path is safe to join with a trusted prefix. This is a security
measure to prevent path traversal attacks.
A valid path should:
not contain separators other than '/'
not contain .. to navigate to parent dir in path
not be an absolute path
"""
from mlflow.utils.file_utils import local_file_uri_to_path
# We must decode URL before validating it
path = urllib.parse.unquote(path)
exc = MlflowException("Invalid path", error_code=INVALID_PARAMETER_VALUE)
if any((s in path) for s in ("#", "%23")):
raise exc
if is_file_uri(path):
path = local_file_uri_to_path(path)
if (
any((s in path) for s in _OS_ALT_SEPS)
or ".." in path.split("/")
or pathlib.PureWindowsPath(path).is_absolute()
or pathlib.PurePosixPath(path).is_absolute()
or (is_windows() and len(path) >= 2 and path[1] == ":")
):
raise exc | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_delete_artifact_mlflow_artifacts_throws_for_malicious_path(enable_serve_artifacts, path):
response = _delete_artifact_mlflow_artifacts(path)
assert response.status_code == 400
json_response = json.loads(response.get_data())
assert json_response["error_code"] == ErrorCode.Name(INVALID_PARAMETER_VALUE)
assert json_response["message"] == "Invalid path" | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_delete_artifact_mlflow_artifacts_throws_for_malicious_path(enable_serve_artifacts, path):
response = _delete_artifact_mlflow_artifacts(path)
assert response.status_code == 400
json_response = json.loads(response.get_data())
assert json_response["error_code"] == ErrorCode.Name(INVALID_PARAMETER_VALUE)
assert json_response["message"] == "Invalid path" | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def enable_serve_artifacts(monkeypatch):
monkeypatch.setenv(SERVE_ARTIFACTS_ENV_VAR, "true") | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def enable_serve_artifacts(monkeypatch):
monkeypatch.setenv(SERVE_ARTIFACTS_ENV_VAR, "true") | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_list_artifacts_malicious_path(http_artifact_repo, path):
with mock.patch(
"mlflow.store.artifact.http_artifact_repo.http_request",
return_value=MockResponse(
{
"files": [
{"path": path, "is_dir": False, "file_size": 1},
]
},
200,
),
):
with pytest.raises(MlflowException, match="Invalid path"):
http_artifact_repo.list_artifacts() | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_list_artifacts_malicious_path(http_artifact_repo, path):
with mock.patch(
"mlflow.store.artifact.http_artifact_repo.http_request",
return_value=MockResponse(
{
"files": [
{"path": path, "is_dir": False, "file_size": 1},
]
},
200,
),
):
with pytest.raises(MlflowException, match="Invalid path"):
http_artifact_repo.list_artifacts() | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_path_validation(mlflow_client):
experiment_id = mlflow_client.create_experiment("tags validation")
created_run = mlflow_client.create_run(experiment_id)
run_id = created_run.info.run_id
invalid_path = "../path"
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid path",
}
response = requests.get(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/artifacts/list",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}/get-artifact",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}//model-versions/get-artifact",
params={"name": "model", "version": 1, "path": invalid_path},
)
assert_response(response) | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_path_validation(mlflow_client):
experiment_id = mlflow_client.create_experiment("tags validation")
created_run = mlflow_client.create_run(experiment_id)
run_id = created_run.info.run_id
invalid_path = "../path"
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid path",
}
response = requests.get(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/artifacts/list",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}/get-artifact",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}//model-versions/get-artifact",
params={"name": "model", "version": 1, "path": invalid_path},
)
assert_response(response) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid path",
} | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid path",
} | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_validate_path_is_safe_windows_good(path):
validate_path_is_safe(path) | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_validate_path_is_safe_windows_good(path):
validate_path_is_safe(path) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_validate_path_is_safe_good(path):
validate_path_is_safe(path) | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_validate_path_is_safe_good(path):
validate_path_is_safe(path) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_validate_path_is_safe_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_validate_path_is_safe_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_validate_path_is_safe_windows_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_validate_path_is_safe_windows_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def load(self, dst_path=None) -> str:
"""
Downloads the dataset source to the local filesystem.
:param dst_path: Path of the local filesystem destination directory to which to download the
dataset source. If the directory does not exist, it is created. If
unspecified, the dataset source is downloaded to a new uniquely-named
directory on the local filesystem.
:return: The path to the downloaded dataset source on the local filesystem.
"""
resp = cloud_storage_http_request(
method="GET",
url=self.url,
stream=True,
)
augmented_raise_for_status(resp)
basename = self._extract_filename(resp)
if not basename:
basename = "dataset_source"
if dst_path is None:
dst_path = create_tmp_dir()
dst_path = os.path.join(dst_path, basename)
with open(dst_path, "wb") as f:
chunk_size = 1024 * 1024 # 1 MB
for chunk in resp.iter_content(chunk_size=chunk_size):
f.write(chunk)
return dst_path | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def _extract_filename(self, response) -> str:
"""
Extracts a filename from the Content-Disposition header or the URL's path.
"""
if content_disposition := response.headers.get("Content-Disposition"):
for match in re.finditer(r"filename=(.+)", content_disposition):
filename = match[1].strip("'\"")
if _is_path(filename):
raise MlflowException.invalid_parameter_value(
f"Invalid filename in Content-Disposition header: {filename}. "
"It must be a file name, not a path."
)
return filename
# Extract basename from URL if no valid filename in Content-Disposition
return os.path.basename(urlparse(self.url).path) | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def download_with_mock_content_disposition_headers(*args, **kwargs):
response = cloud_storage_http_request(*args, **kwargs)
response.headers = {"Content-Disposition": f"attachment; filename={filename}"}
return response | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def test_source_load_with_content_disposition_header_invalid_filename_windows(filename):
def download_with_mock_content_disposition_headers(*args, **kwargs):
response = cloud_storage_http_request(*args, **kwargs)
response.headers = {"Content-Disposition": f"attachment; filename={filename}"}
return response
with mock.patch(
"mlflow.data.http_dataset_source.cloud_storage_http_request",
side_effect=download_with_mock_content_disposition_headers,
):
source = HTTPDatasetSource(
"https://raw.githubusercontent.com/mlflow/mlflow/master/tests/datasets/winequality-red.csv"
)
# Expect an MlflowException for invalid filenames
with pytest.raises(MlflowException, match="Invalid filename in Content-Disposition header"):
source.load() | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
def list_artifacts(self, path=None):
with self.get_ftp_client() as ftp:
artifact_dir = self.path
list_dir = posixpath.join(artifact_dir, path) if path else artifact_dir
if not self._is_dir(ftp, list_dir):
return []
artifact_files = ftp.nlst(list_dir)
# Make sure artifact_files is a list of file names because ftp.nlst
# may return absolute paths.
artifact_files = [os.path.basename(f) for f in artifact_files]
artifact_files = list(filter(lambda x: x != "." and x != "..", artifact_files))
infos = []
for file_name in artifact_files:
file_path = file_name if path is None else posixpath.join(path, file_name)
full_file_path = posixpath.join(list_dir, file_name)
if self._is_dir(ftp, full_file_path):
infos.append(FileInfo(file_path, True, None))
else:
size = self._size(ftp, full_file_path)
infos.append(FileInfo(file_path, False, size))
return infos | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_list_artifacts_malicious_path(ftp_mock):
artifact_root_path = "/experiment_id/run_id/"
repo = FTPArtifactRepository("ftp://test_ftp" + artifact_root_path)
repo.get_ftp_client = MagicMock()
call_mock = MagicMock(return_value=ftp_mock)
repo.get_ftp_client.return_value = MagicMock(__enter__=call_mock)
ftp_mock.nlst = MagicMock(return_value=[".", "/.", "/..", "//.."])
artifacts = repo.list_artifacts(path=None)
assert artifacts == [] | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def _create_multipart_upload_artifact(artifact_path):
"""
A request handler for `POST /mlflow-artifacts/mpu/create` to create a multipart upload
to `artifact_path` (a relative path from the root artifact directory).
"""
artifact_path = validate_path_is_safe(artifact_path)
request_message = _get_request_message(
CreateMultipartUpload(),
schema={
"path": [_assert_required, _assert_string],
"num_parts": [_assert_intlike],
},
)
path = request_message.path
num_parts = request_message.num_parts
artifact_repo = _get_artifact_repo_mlflow_artifacts()
_validate_support_multipart_upload(artifact_repo)
create_response = artifact_repo.create_multipart_upload(
path,
num_parts,
artifact_path,
)
response_message = create_response.to_proto()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def get_artifact_handler():
from querystring_parser import parser
query_string = request.query_string.decode("utf-8")
request_dict = parser.parse(query_string, normalized=True)
run_id = request_dict.get("run_id") or request_dict.get("run_uuid")
path = request_dict["path"]
path = validate_path_is_safe(path)
run = _get_tracking_store().get_run(run_id)
if _is_servable_proxied_run_artifact_root(run.info.artifact_uri):
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_path = _get_proxied_run_artifact_destination_path(
proxied_artifact_root=run.info.artifact_uri,
relative_path=path,
)
else:
artifact_repo = _get_artifact_repo(run)
artifact_path = path
return _send_artifact(artifact_repo, artifact_path) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _delete_artifact_mlflow_artifacts(artifact_path):
"""
A request handler for `DELETE /mlflow-artifacts/artifacts?path=<value>` to delete artifacts in
`path` (a relative path from the root artifact directory).
"""
artifact_path = validate_path_is_safe(artifact_path)
_get_request_message(DeleteArtifact())
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_repo.delete_artifacts(artifact_path)
response_message = DeleteArtifact.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _list_artifacts():
request_message = _get_request_message(
ListArtifacts(),
schema={
"run_id": [_assert_string, _assert_required],
"path": [_assert_string],
"page_token": [_assert_string],
},
)
response_message = ListArtifacts.Response()
if request_message.HasField("path"):
path = request_message.path
path = validate_path_is_safe(path)
else:
path = None
run_id = request_message.run_id or request_message.run_uuid
run = _get_tracking_store().get_run(run_id)
if _is_servable_proxied_run_artifact_root(run.info.artifact_uri):
artifact_entities = _list_artifacts_for_proxied_run_artifact_root(
proxied_artifact_root=run.info.artifact_uri,
relative_path=path,
)
else:
artifact_entities = _get_artifact_repo(run).list_artifacts(path)
response_message.files.extend([a.to_proto() for a in artifact_entities])
response_message.root_uri = run.info.artifact_uri
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _abort_multipart_upload_artifact(artifact_path):
"""
A request handler for `POST /mlflow-artifacts/mpu/abort` to abort a multipart upload
to `artifact_path` (a relative path from the root artifact directory).
"""
artifact_path = validate_path_is_safe(artifact_path)
request_message = _get_request_message(
AbortMultipartUpload(),
schema={
"path": [_assert_required, _assert_string],
"upload_id": [_assert_string],
},
)
path = request_message.path
upload_id = request_message.upload_id
artifact_repo = _get_artifact_repo_mlflow_artifacts()
_validate_support_multipart_upload(artifact_repo)
artifact_repo.abort_multipart_upload(
path,
upload_id,
artifact_path,
)
return _wrap_response(AbortMultipartUpload.Response()) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def get_model_version_artifact_handler():
from querystring_parser import parser
query_string = request.query_string.decode("utf-8")
request_dict = parser.parse(query_string, normalized=True)
name = request_dict.get("name")
version = request_dict.get("version")
path = request_dict["path"]
path = validate_path_is_safe(path)
artifact_uri = _get_model_registry_store().get_model_version_download_uri(name, version)
if _is_servable_proxied_run_artifact_root(artifact_uri):
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_path = _get_proxied_run_artifact_destination_path(
proxied_artifact_root=artifact_uri,
relative_path=path,
)
else:
artifact_repo = get_artifact_repository(artifact_uri)
artifact_path = path
return _send_artifact(artifact_repo, artifact_path) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _download_artifact(artifact_path):
"""
A request handler for `GET /mlflow-artifacts/artifacts/<artifact_path>` to download an artifact
from `artifact_path` (a relative path from the root artifact directory).
"""
artifact_path = validate_path_is_safe(artifact_path)
tmp_dir = tempfile.TemporaryDirectory()
artifact_repo = _get_artifact_repo_mlflow_artifacts()
dst = artifact_repo.download_artifacts(artifact_path, tmp_dir.name)
# Ref: https://stackoverflow.com/a/24613980/6943581
file_handle = open(dst, "rb") # noqa: SIM115
def stream_and_remove_file():
yield from file_handle
file_handle.close()
tmp_dir.cleanup()
file_sender_response = current_app.response_class(stream_and_remove_file())
return _response_with_file_attachment_headers(artifact_path, file_sender_response) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _complete_multipart_upload_artifact(artifact_path):
"""
A request handler for `POST /mlflow-artifacts/mpu/complete` to complete a multipart upload
to `artifact_path` (a relative path from the root artifact directory).
"""
artifact_path = validate_path_is_safe(artifact_path)
request_message = _get_request_message(
CompleteMultipartUpload(),
schema={
"path": [_assert_required, _assert_string],
"upload_id": [_assert_string],
"parts": [_assert_required],
},
)
path = request_message.path
upload_id = request_message.upload_id
parts = [MultipartUploadPart.from_proto(part) for part in request_message.parts]
artifact_repo = _get_artifact_repo_mlflow_artifacts()
_validate_support_multipart_upload(artifact_repo)
artifact_repo.complete_multipart_upload(
path,
upload_id,
parts,
artifact_path,
)
return _wrap_response(CompleteMultipartUpload.Response()) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _list_artifacts_mlflow_artifacts():
"""
A request handler for `GET /mlflow-artifacts/artifacts?path=<value>` to list artifacts in `path`
(a relative path from the root artifact directory).
"""
request_message = _get_request_message(ListArtifactsMlflowArtifacts())
path = validate_path_is_safe(request_message.path) if request_message.HasField("path") else None
artifact_repo = _get_artifact_repo_mlflow_artifacts()
files = []
for file_info in artifact_repo.list_artifacts(path):
basename = posixpath.basename(file_info.path)
new_file_info = FileInfo(basename, file_info.is_dir, file_info.file_size)
files.append(new_file_info.to_proto())
response_message = ListArtifacts.Response()
response_message.files.extend(files)
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _upload_artifact(artifact_path):
"""
A request handler for `PUT /mlflow-artifacts/artifacts/<artifact_path>` to upload an artifact
to `artifact_path` (a relative path from the root artifact directory).
"""
artifact_path = validate_path_is_safe(artifact_path)
head, tail = posixpath.split(artifact_path)
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = os.path.join(tmp_dir, tail)
with open(tmp_path, "wb") as f:
chunk_size = 1024 * 1024 # 1 MB
while True:
chunk = request.stream.read(chunk_size)
if len(chunk) == 0:
break
f.write(chunk)
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_repo.log_artifact(tmp_path, artifact_path=head or None)
return _wrap_response(UploadArtifact.Response()) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def list_artifacts(self, path=None):
endpoint = "/mlflow-artifacts/artifacts"
url, tail = self.artifact_uri.split(endpoint, maxsplit=1)
root = tail.lstrip("/")
params = {"path": posixpath.join(root, path) if path else root}
host_creds = _get_default_host_creds(url)
resp = http_request(host_creds, endpoint, "GET", params=params)
augmented_raise_for_status(resp)
file_infos = []
for f in resp.json().get("files", []):
validated_path = validate_path_is_safe(f["path"])
file_info = FileInfo(
posixpath.join(path, validated_path) if path else validated_path,
f["is_dir"],
int(f["file_size"]) if ("file_size" in f) else None,
)
file_infos.append(file_info)
return sorted(file_infos, key=lambda f: f.path) | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def validate_path_is_safe(path):
"""
Validates that the specified path is safe to join with a trusted prefix. This is a security
measure to prevent path traversal attacks.
A valid path should:
not contain separators other than '/'
not contain .. to navigate to parent dir in path
not be an absolute path
"""
from mlflow.utils.file_utils import local_file_uri_to_path
# We must decode path before validating it
path = _decode(path)
exc = MlflowException("Invalid path", error_code=INVALID_PARAMETER_VALUE)
if "#" in path:
raise exc
if is_file_uri(path):
path = local_file_uri_to_path(path)
if (
any((s in path) for s in _OS_ALT_SEPS)
or ".." in path.split("/")
or pathlib.PureWindowsPath(path).is_absolute()
or pathlib.PurePosixPath(path).is_absolute()
or (is_windows() and len(path) >= 2 and path[1] == ":")
):
raise exc
return path | 1 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | safe |
def _get_http_response_with_retries(
method,
url,
max_retries,
backoff_factor,
backoff_jitter,
retry_codes,
raise_on_status=True,
allow_redirects=None,
**kwargs,
):
"""
Performs an HTTP request using Python's `requests` module with an automatic retry policy.
:param method: a string indicating the method to use, e.g. "GET", "POST", "PUT".
:param url: the target URL address for the HTTP request.
:param max_retries: Maximum total number of retries.
:param backoff_factor: a time factor for exponential backoff. e.g. value 5 means the HTTP
request will be retried with interval 5, 10, 20... seconds. A value of 0 turns off the
exponential backoff.
:param backoff_jitter: A random jitter to add to the backoff interval.
:param retry_codes: a list of HTTP response error codes that qualifies for retry.
:param raise_on_status: whether to raise an exception, or return a response, if status falls
in retry_codes range and retries have been exhausted.
:param kwargs: Additional keyword arguments to pass to `requests.Session.request()`
:return: requests.Response object.
"""
session = _get_request_session(
max_retries, backoff_factor, backoff_jitter, retry_codes, raise_on_status
)
# the environment variable is hardcoded here to avoid importing mlflow.
# however, documentation is available in environment_variables.py
env_value = os.getenv("MLFLOW_ALLOW_HTTP_REDIRECTS", "true").lower() in ["true", "1"]
allow_redirects = env_value if allow_redirects is None else allow_redirects
return session.request(method, url, allow_redirects=allow_redirects, **kwargs) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_databricks_http_request_integration(get_config, request):
"""Confirms that the databricks http request params can in fact be used as an HTTP request"""
def confirm_request_params(*args, **kwargs):
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Basic dXNlcjpwYXNz"
assert args == ("PUT", "host/clusters/list")
assert kwargs == {
"allow_redirects": True,
"headers": headers,
"verify": True,
"json": {"a": "b"},
"timeout": 120,
}
http_response = mock.MagicMock()
http_response.status_code = 200
http_response.text = '{"OK": "woo"}'
return http_response
request.side_effect = confirm_request_params
get_config.return_value = DatabricksConfig.from_password("host", "user", "pass", insecure=False)
response = DatabricksJobRunner(databricks_profile_uri=None)._databricks_api_request(
"/clusters/list", "PUT", json={"a": "b"}
)
assert json.loads(response.text) == {"OK": "woo"}
get_config.reset_mock()
response = DatabricksJobRunner(
databricks_profile_uri=construct_db_uri_from_profile("my-profile")
)._databricks_api_request("/clusters/list", "PUT", json={"a": "b"})
assert json.loads(response.text) == {"OK": "woo"}
assert get_config.call_count == 0 | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def confirm_request_params(*args, **kwargs):
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Basic dXNlcjpwYXNz"
assert args == ("PUT", "host/clusters/list")
assert kwargs == {
"allow_redirects": True,
"headers": headers,
"verify": True,
"json": {"a": "b"},
"timeout": 120,
}
http_response = mock.MagicMock()
http_response.status_code = 200
http_response.text = '{"OK": "woo"}'
return http_response | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_log_artifact_gcp_with_headers(
databricks_artifact_repo, test_file, artifact_path, expected_location
):
expected_headers = {header.name: header.value for header in MOCK_HEADERS}
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_GCP_SIGNED_URL,
type=ArtifactCredentialType.GCP_SIGNED_URL,
headers=MOCK_HEADERS,
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put",
MOCK_GCP_SIGNED_URL,
allow_redirects=True,
data=ANY,
headers=expected_headers,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_log_artifact_azure_with_headers(
databricks_artifact_repo, test_file, artifact_path, expected_location
):
mock_azure_headers = {
"x-ms-encryption-scope": "test-scope",
"x-ms-tags": "some-tags",
"x-ms-blob-type": "some-type",
}
filtered_azure_headers = {
"x-ms-encryption-scope": "test-scope",
"x-ms-tags": "some-tags",
}
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_AZURE_SIGNED_URI,
type=ArtifactCredentialType.AZURE_SAS_URI,
headers=[
ArtifactCredentialInfo.HttpHeader(name=header_name, value=header_value)
for header_name, header_value in mock_azure_headers.items()
],
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put",
f"{MOCK_AZURE_SIGNED_URI}?comp=blocklist",
allow_redirects=True,
data=ANY,
headers=filtered_azure_headers,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_log_artifact_aws(databricks_artifact_repo, test_file, artifact_path, expected_location):
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_AWS_SIGNED_URI, type=ArtifactCredentialType.AWS_PRESIGNED_URL
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put", MOCK_AWS_SIGNED_URI, allow_redirects=True, data=ANY, headers={}, timeout=None
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_log_artifact_adls_gen2_flush_error(databricks_artifact_repo, test_file):
mock_successful_response = Response()
mock_successful_response.status_code = 200
mock_successful_response.close = lambda: None
mock_error_response = MlflowException("MOCK ERROR")
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_ADLS_GEN2_SIGNED_URI,
type=ArtifactCredentialType.AZURE_ADLS_GEN2_SAS_URI,
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", side_effect=[mock_successful_response, mock_error_response]
) as request_mock:
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_ADLS_GEN2_SIGNED_URI,
type=ArtifactCredentialType.AZURE_ADLS_GEN2_SAS_URI,
)
with pytest.raises(MlflowException, match=r"MOCK ERROR"):
databricks_artifact_repo.log_artifact(test_file)
get_credential_infos_mock.assert_called_with(GetCredentialsForWrite, MOCK_RUN_ID, ANY)
assert request_mock.mock_calls == [
mock.call(
"put",
f"{MOCK_ADLS_GEN2_SIGNED_URI}?resource=file",
allow_redirects=True,
headers={},
timeout=None,
),
mock.call(
"patch",
f"{MOCK_ADLS_GEN2_SIGNED_URI}?action=append&position=0&flush=true",
allow_redirects=True,
data=ANY,
headers={},
timeout=None,
),
] | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_log_artifact_gcp(databricks_artifact_repo, test_file, artifact_path, expected_location):
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_GCP_SIGNED_URL, type=ArtifactCredentialType.GCP_SIGNED_URL
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put", MOCK_GCP_SIGNED_URL, allow_redirects=True, data=ANY, headers={}, timeout=None
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_log_artifact_aws_with_headers(
databricks_artifact_repo, test_file, artifact_path, expected_location
):
expected_headers = {header.name: header.value for header in MOCK_HEADERS}
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_AWS_SIGNED_URI,
type=ArtifactCredentialType.AWS_PRESIGNED_URL,
headers=MOCK_HEADERS,
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put",
MOCK_AWS_SIGNED_URI,
allow_redirects=True,
data=ANY,
headers=expected_headers,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_successful_http_request(request):
def mock_request(*args, **kwargs):
# Filter out None arguments
assert args == ("POST", "https://hello/api/2.0/mlflow/experiments/search")
kwargs = {k: v for k, v in kwargs.items() if v is not None}
assert kwargs == {
"allow_redirects": True,
"json": {"view_type": "ACTIVE_ONLY"},
"headers": DefaultRequestHeaderProvider().request_headers(),
"verify": True,
"timeout": 120,
}
response = mock.MagicMock()
response.status_code = 200
response.text = '{"experiments": [{"name": "Exp!", "lifecycle_stage": "active"}]}'
return response
request.side_effect = mock_request
store = RestStore(lambda: MlflowHostCreds("https://hello"))
experiments = store.search_experiments()
assert experiments[0].name == "Exp!" | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def mock_request(*args, **kwargs):
# Filter out None arguments
assert args == ("POST", "https://hello/api/2.0/mlflow/experiments/search")
kwargs = {k: v for k, v in kwargs.items() if v is not None}
assert kwargs == {
"allow_redirects": True,
"json": {"view_type": "ACTIVE_ONLY"},
"headers": DefaultRequestHeaderProvider().request_headers(),
"verify": True,
"timeout": 120,
}
response = mock.MagicMock()
response.status_code = 200
response.text = '{"experiments": [{"name": "Exp!", "lifecycle_stage": "active"}]}'
return response | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_redirects_disabled_if_env_var_set(monkeypatch, env_value):
monkeypatch.setenv("MLFLOW_ALLOW_HTTP_REDIRECTS", env_value)
with mock.patch("requests.Session.request") as mock_request:
mock_request.return_value.status_code = 302
mock_request.return_value.text = "mock response"
response = request_utils.cloud_storage_http_request("GET", "http://localhost:5000")
assert response.text == "mock response"
mock_request.assert_called_once_with(
"GET",
"http://localhost:5000",
allow_redirects=False,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_redirects_enabled_by_default():
with mock.patch("requests.Session.request") as mock_request:
mock_request.return_value.status_code = 302
mock_request.return_value.text = "mock response"
response = request_utils.cloud_storage_http_request(
"GET",
"http://localhost:5000",
)
assert response.text == "mock response"
mock_request.assert_called_once_with(
"GET",
"http://localhost:5000",
allow_redirects=True,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_redirects_enabled_if_env_var_set(monkeypatch, env_value):
monkeypatch.setenv("MLFLOW_ALLOW_HTTP_REDIRECTS", env_value)
with mock.patch("requests.Session.request") as mock_request:
mock_request.return_value.status_code = 302
mock_request.return_value.text = "mock response"
response = request_utils.cloud_storage_http_request(
"GET",
"http://localhost:5000",
)
assert response.text == "mock response"
mock_request.assert_called_once_with(
"GET",
"http://localhost:5000",
allow_redirects=True,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_redirect_kwarg_overrides_env_value_true(monkeypatch, env_value):
monkeypatch.setenv("MLFLOW_ALLOW_HTTP_REDIRECTS", env_value)
with mock.patch("requests.Session.request") as mock_request:
mock_request.return_value.status_code = 302
mock_request.return_value.text = "mock response"
response = request_utils.cloud_storage_http_request(
"GET", "http://localhost:5000", allow_redirects=False
)
assert response.text == "mock response"
mock_request.assert_called_once_with(
"GET",
"http://localhost:5000",
allow_redirects=False,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_redirect_kwarg_overrides_env_value_false(monkeypatch, env_value):
monkeypatch.setenv("MLFLOW_ALLOW_HTTP_REDIRECTS", env_value)
with mock.patch("requests.Session.request") as mock_request:
mock_request.return_value.status_code = 302
mock_request.return_value.text = "mock response"
response = request_utils.cloud_storage_http_request(
"GET", "http://localhost:5000", allow_redirects=True
)
assert response.text == "mock response"
mock_request.assert_called_once_with(
"GET",
"http://localhost:5000",
allow_redirects=True,
timeout=None,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_with_token(request):
host_only = MlflowHostCreds("http://my-host", token="my-token")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Bearer my-token"
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=True,
headers=headers,
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_with_content_type_header(request):
host_only = MlflowHostCreds("http://my-host", token="my-token")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
extra_headers = {"Content-Type": "text/plain"}
http_request(host_only, "/my/endpoint", "GET", extra_headers=extra_headers)
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Bearer my-token"
headers["Content-Type"] = "text/plain"
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=True,
headers=headers,
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_with_aws_sigv4(request, monkeypatch):
"""This test requires the "requests_auth_aws_sigv4" package to be installed"""
from requests_auth_aws_sigv4 import AWSSigV4
monkeypatch.setenvs(
{
"AWS_ACCESS_KEY_ID": "access-key",
"AWS_SECRET_ACCESS_KEY": "secret-key",
"AWS_DEFAULT_REGION": "eu-west-1",
}
)
aws_sigv4 = MlflowHostCreds("http://my-host", aws_sigv4=True)
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(aws_sigv4, "/my/endpoint", "GET")
class AuthMatcher:
def __eq__(self, other):
return isinstance(other, AWSSigV4)
request.assert_called_once_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=mock.ANY,
headers=mock.ANY,
timeout=mock.ANY,
auth=AuthMatcher(),
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_client_cert_path(request):
host_only = MlflowHostCreds("http://my-host", client_cert_path="/some/path")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=True,
cert="/some/path",
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_server_cert_path(request):
host_only = MlflowHostCreds("http://my-host", server_cert_path="/some/path")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify="/some/path",
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_request_headers(request):
"""This test requires the package in tests/resources/mlflow-test-plugin to be installed"""
from mlflow_test_plugin.request_header_provider import PluginRequestHeaderProvider
# The test plugin's request header provider always returns False from in_context to avoid
# polluting request headers in developers' environments. The following mock overrides this to
# perform the integration test.
with mock.patch.object(PluginRequestHeaderProvider, "in_context", return_value=True):
host_only = MlflowHostCreds("http://my-host", server_cert_path="/some/path")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify="/some/path",
headers={**DefaultRequestHeaderProvider().request_headers(), "test": "header"},
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_hostonly(request):
host_only = MlflowHostCreds("http://my-host")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=True,
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_request_headers_user_agent_and_extra_header(request):
"""This test requires the package in tests/resources/mlflow-test-plugin to be installed"""
from mlflow_test_plugin.request_header_provider import PluginRequestHeaderProvider
# The test plugin's request header provider always returns False from in_context to avoid
# polluting request headers in developers' environments. The following mock overrides this to
# perform the integration test.
with mock.patch.object(
PluginRequestHeaderProvider, "in_context", return_value=True
), mock.patch.object(
PluginRequestHeaderProvider,
"request_headers",
return_value={_USER_AGENT: "test_user_agent", "header": "value"},
):
host_only = MlflowHostCreds("http://my-host", server_cert_path="/some/path")
expected_headers = {
_USER_AGENT: "{} {}".format(
DefaultRequestHeaderProvider().request_headers()[_USER_AGENT], "test_user_agent"
),
"header": "value",
}
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify="/some/path",
headers=expected_headers,
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_provide_redirect_kwarg():
with mock.patch("requests.Session.request") as mock_request:
mock_request.return_value.status_code = 302
mock_request.return_value.text = "mock response"
response = http_request(
MlflowHostCreds("http://my-host"),
"/my/endpoint",
"GET",
allow_redirects=False,
)
assert response.text == "mock response"
mock_request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=False,
headers=mock.ANY,
verify=mock.ANY,
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_with_basic_auth(request):
host_only = MlflowHostCreds("http://my-host", username="user", password="pass")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Basic dXNlcjpwYXNz"
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=True,
headers=headers,
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_with_insecure(request):
host_only = MlflowHostCreds("http://my-host", ignore_tls_verification=True)
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=False,
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_request_headers_user_agent(request):
"""This test requires the package in tests/resources/mlflow-test-plugin to be installed"""
from mlflow_test_plugin.request_header_provider import PluginRequestHeaderProvider
# The test plugin's request header provider always returns False from in_context to avoid
# polluting request headers in developers' environments. The following mock overrides this to
# perform the integration test.
with mock.patch.object(
PluginRequestHeaderProvider, "in_context", return_value=True
), mock.patch.object(
PluginRequestHeaderProvider,
"request_headers",
return_value={_USER_AGENT: "test_user_agent"},
):
host_only = MlflowHostCreds("http://my-host", server_cert_path="/some/path")
expected_headers = {
_USER_AGENT: "{} {}".format(
DefaultRequestHeaderProvider().request_headers()[_USER_AGENT], "test_user_agent"
)
}
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify="/some/path",
headers=expected_headers,
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_with_auth(fetch_auth, request):
mock_fetch_auth = {"test_name": "test_auth_value"}
fetch_auth.return_value = mock_fetch_auth
auth = "test_auth_name"
host_only = MlflowHostCreds("http://my-host", auth=auth)
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
fetch_auth.assert_called_with(auth)
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=mock.ANY,
headers=mock.ANY,
timeout=mock.ANY,
auth=mock_fetch_auth,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_wrapper(request):
host_only = MlflowHostCreds("http://my-host", ignore_tls_verification=True)
response = mock.MagicMock()
response.status_code = 200
response.text = "{}"
request.return_value = response
http_request_safe(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=False,
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
)
response.text = "non json"
request.return_value = response
http_request_safe(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=False,
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
)
response.status_code = 400
response.text = ""
request.return_value = response
with pytest.raises(MlflowException, match="Response body"):
http_request_safe(host_only, "/my/endpoint", "GET")
response.text = (
'{"error_code": "RESOURCE_DOES_NOT_EXIST", "message": "Node type not supported"}'
)
request.return_value = response
with pytest.raises(RestException, match="RESOURCE_DOES_NOT_EXIST: Node type not supported"):
http_request_safe(host_only, "/my/endpoint", "GET") | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def test_http_request_cleans_hostname(request):
# Add a trailing slash, should be removed.
host_only = MlflowHostCreds("http://my-host/")
response = mock.MagicMock()
response.status_code = 200
request.return_value = response
http_request(host_only, "/my/endpoint", "GET")
request.assert_called_with(
"GET",
"http://my-host/my/endpoint",
allow_redirects=True,
verify=True,
headers=DefaultRequestHeaderProvider().request_headers(),
timeout=120,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def open_url(self, url):
"""Open the given URL in a new browser window.
Display an error dialog if everything fails.
"""
(r, w) = os.pipe()
if os.fork() > 0:
os.close(w)
status = os.wait()[1]
if status:
title = _("Unable to start web browser")
error = _("Unable to start web browser to open %s." % url)
message = os.fdopen(r).readline()
if message:
error += "\n" + message
self.ui_error_message(title, error)
try:
os.close(r)
except OSError:
pass
return
os.setsid()
os.close(r)
try:
try:
run_as_real_user(["xdg-open", url], get_user_env=True)
except OSError:
# fall back to webbrowser
webbrowser.open(url, new=True, autoraise=True)
sys.exit(0)
except Exception as error: # pylint: disable=broad-except
os.write(w, str(error))
sys.exit(1)
os._exit(0) # pylint: disable=protected-access | 1 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
def run_as_real_user(
args: list[str], *, get_user_env: bool = False, **kwargs
) -> None:
"""Call subprocess.run as real user if called via sudo/pkexec.
If we are called through pkexec/sudo, determine the real user ID and
run the command with it to get the user's web browser settings.
If get_user_env is set to True, the D-BUS address and XDG_DATA_DIRS
is grabbed from a running gvfsd and added to the process environment.
"""
uid = _get_env_int("SUDO_UID", _get_env_int("PKEXEC_UID"))
if uid is None or not get_process_user_and_group().is_root():
subprocess.run(args, check=False, **kwargs)
return
pwuid = pwd.getpwuid(uid)
gid = _get_env_int("SUDO_GID")
if gid is None:
gid = pwuid.pw_gid
env = {
k: v
for k, v in os.environ.items()
if not k.startswith("SUDO_") and k != "PKEXEC_UID"
}
if get_user_env:
env |= _get_users_environ(uid)
env["HOME"] = pwuid.pw_dir
subprocess.run(
args,
check=False,
env=env,
user=uid,
group=gid,
extra_groups=os.getgrouplist(pwuid.pw_name, gid),
**kwargs,
) | 1 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
def test_run_as_real_user_no_gvfsd(
self, getpwuid_mock: unittest.mock.MagicMock
) -> None:
"""Test run_as_real_user() without no gvfsd process."""
getpwuid_mock.return_value = pwd.struct_passwd(
(
"testuser",
"x",
1337,
42,
"Test user,,,",
"/home/testuser",
"/bin/bash",
)
)
with unittest.mock.patch(
"subprocess.run", side_effect=mock_run_calls_except_pgrep
) as run_mock:
run_as_real_user(["/bin/true"], get_user_env=True)
run_mock.assert_called_with(
["/bin/true"],
check=False,
env={"HOME": "/home/testuser"},
user=1337,
group=42,
extra_groups=[42],
)
self.assertEqual(run_mock.call_count, 2) | 1 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
def test_run_as_real_user(self) -> None:
"""Test run_as_real_user() with SUDO_UID set."""
pwuid = pwd.getpwuid(int(os.environ["SUDO_UID"]))
with tempfile.TemporaryDirectory() as tmpdir:
# rename test program to fake gvfsd
gvfsd_mock = os.path.join(tmpdir, "gvfsd")
shutil.copy(self.TEST_EXECUTABLE, gvfsd_mock)
gvfsd_env = {
"XDG_DATA_DIRS": "mocked XDG data dir",
"DBUS_SESSION_BUS_ADDRESS": "/fake/dbus/path",
}
with self._run_test_executable(gvfsd_mock, env=gvfsd_env):
with unittest.mock.patch(
"subprocess.run", side_effect=mock_run_calls_except_pgrep
) as run_mock:
run_as_real_user(["/bin/true"], get_user_env=True)
run_mock.assert_called_with(
["/bin/true"],
check=False,
env={
"DBUS_SESSION_BUS_ADDRESS": "/fake/dbus/path",
"XDG_DATA_DIRS": "mocked XDG data dir",
"HOME": pwuid.pw_dir,
},
user=int(os.environ["SUDO_UID"]),
group=pwuid.pw_gid,
extra_groups=os.getgrouplist(pwuid.pw_name, pwuid.pw_gid),
)
self.assertEqual(run_mock.call_count, 2) | 1 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
def redact_sensitive_keys(metadata, redact_value=REDACT_SENSITIVE_VALUE):
"""Redact any sensitive keys from to provided metadata dictionary.
Replace any keys values listed in 'sensitive_keys' with redact_value.
"""
# While 'sensitive_keys' should already sanitized to only include what
# is in metadata, it is possible keys will overlap. For example, if
# "merged_cfg" and "merged_cfg/ds/userdata" both match, it's possible that
# "merged_cfg" will get replaced first, meaning "merged_cfg/ds/userdata"
# no longer represents a valid key.
# Thus, we still need to do membership checks in this function.
if not metadata.get("sensitive_keys", []):
return metadata
md_copy = copy.deepcopy(metadata)
for key_path in metadata.get("sensitive_keys"):
path_parts = key_path.split("/")
obj = md_copy
for path in path_parts:
if (
path in obj
and isinstance(obj[path], dict)
and path != path_parts[-1]
):
obj = obj[path]
if path in obj:
obj[path] = redact_value
return md_copy | 1 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
def process_instance_metadata(metadata, key_path="", sensitive_keys=()):
"""Process all instance metadata cleaning it up for persisting as json.
Strip ci-b64 prefix and catalog any 'base64_encoded_keys' as a list
@return Dict copy of processed metadata.
"""
md_copy = copy.deepcopy(metadata)
base64_encoded_keys = []
sens_keys = []
for key, val in metadata.items():
if key_path:
sub_key_path = key_path + "/" + key
else:
sub_key_path = key
if (
key.lower() in sensitive_keys
or sub_key_path.lower() in sensitive_keys
):
sens_keys.append(sub_key_path)
if isinstance(val, str) and val.startswith("ci-b64:"):
base64_encoded_keys.append(sub_key_path)
md_copy[key] = val.replace("ci-b64:", "")
if isinstance(val, dict):
return_val = process_instance_metadata(
val, sub_key_path, sensitive_keys
)
base64_encoded_keys.extend(return_val.pop("base64_encoded_keys"))
sens_keys.extend(return_val.pop("sensitive_keys"))
md_copy[key] = return_val
md_copy["base64_encoded_keys"] = sorted(base64_encoded_keys)
md_copy["sensitive_keys"] = sorted(sens_keys)
return md_copy | 1 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
def _initialize_filesystem(self):
util.ensure_dirs(self._initial_subdirs())
log_file = util.get_cfg_option_str(self.cfg, "def_log_file")
if log_file:
# At this point the log file should have already been created
# in the setupLogging function of log.py
util.ensure_file(log_file, mode=0o640, preserve_mode=False)
perms = self.cfg.get("syslog_fix_perms")
if not perms:
perms = {}
if not isinstance(perms, list):
perms = [perms]
error = None
for perm in perms:
u, g = util.extract_usergroup(perm)
try:
util.chownbyname(log_file, u, g)
return
except OSError as e:
error = e
LOG.warning(
"Failed changing perms on '%s'. tried: %s. %s",
log_file,
",".join(perms),
error,
) | 1 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
def test_existing_file_permissions(self, init, tmpdir):
"""Test file permissions are set as expected.
CIS Hardening requires 640 permissions. These permissions are
currently hardcoded on every boot, but if there's ever a reason
to change this, we need to then ensure that they
are *not* set every boot.
See https://bugs.launchpad.net/cloud-init/+bug/1900837.
"""
log_file = tmpdir.join("cloud-init.log")
log_file.ensure()
# Use a mode that will never be made the default so this test will
# always be valid
log_file.chmod(0o606)
init._cfg = {"def_log_file": str(log_file)}
init._initialize_filesystem()
assert 0o640 == stat.S_IMODE(log_file.stat().mode) | 1 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
def test_regular_user_cant_add_users(self):
response = self.client.get("/admin/auth/user/add/")
self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code)
response = self.client.post(
"/admin/auth/user/add/",
{
"username": "added-by-regular-user",
"password1": __FOR_TESTING__,
"password2": __FOR_TESTING__,
},
follow=True,
)
self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code)
self.assertFalse(
get_user_model().objects.filter(username="added-by-regular-user").exists()
) | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def test_moderator_can_add_users(self):
user_should_have_perm(self.moderator, "auth.add_user")
user_should_have_perm(self.moderator, "auth.change_user")
# test for https://github.com/kiwitcms/Kiwi/issues/642
self.client.login( # nosec:B106:hardcoded_password_funcarg
username=self.moderator.username, password="admin-password"
)
response = self.client.get("/admin/auth/user/add/")
self.assertEqual(HTTPStatus.OK, response.status_code)
# only these fields can be edited
self.assertContains(response, "id_username")
self.assertContains(response, "id_password1")
self.assertContains(response, "id_password2")
response = self.client.post(
"/admin/auth/user/add/",
{
"username": "added-by-moderator",
"password1": __FOR_TESTING__,
"password2": __FOR_TESTING__,
},
follow=True,
)
self.assertEqual(HTTPStatus.OK, response.status_code)
self.assertTrue(
get_user_model().objects.filter(username="added-by-moderator").exists()
) | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def test_superuser_can_add_users(self):
# test for https://github.com/kiwitcms/Kiwi/issues/642
self.client.login( # nosec:B106:hardcoded_password_funcarg
username=self.admin.username, password="admin-password"
)
response = self.client.get("/admin/auth/user/add/")
self.assertEqual(HTTPStatus.OK, response.status_code)
response = self.client.post(
"/admin/auth/user/add/",
{
"username": "added-by-admin",
"password1": __FOR_TESTING__,
"password2": __FOR_TESTING__,
},
follow=True,
)
self.assertEqual(HTTPStatus.OK, response.status_code)
self.assertTrue(
get_user_model().objects.filter(username="added-by-admin").exists()
) | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def setUp(self):
self.data = {
"username": "test_user",
"password1": __FOR_TESTING__,
"password2": __FOR_TESTING__,
"email": "[email protected]",
} | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def test_invalid_form(self):
response = self.client.post(
self.register_url,
{
"username": "kiwi-tester",
"password1": __FOR_TESTING__,
"password2": f"000-{__FOR_TESTING__}",
"email": "[email protected]",
},
follow=False,
)
self.assertContains(response, _("The two password fields didn’t match."))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "registration/registration_form.html") | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def assert_user_registration(self, username, follow=False):
with patch("tcms.kiwi_auth.models.secrets") as _secrets:
_secrets.token_hex.return_value = self.fake_activate_key
try:
# https://github.com/mbi/django-simple-captcha/issues/84
# pylint: disable=import-outside-toplevel
from captcha.conf import settings as captcha_settings
captcha_settings.CAPTCHA_TEST_MODE = True
response = self.client.post(
self.register_url,
{
"username": username,
"password1": __FOR_TESTING__,
"password2": __FOR_TESTING__,
"email": "[email protected]",
"captcha_0": "PASSED",
"captcha_1": "PASSED",
},
follow=follow,
)
finally:
captcha_settings.CAPTCHA_TEST_MODE = False
user = User.objects.get(username=username)
self.assertEqual("[email protected]", user.email)
if User.objects.filter(is_superuser=True).count() == 1 and user.is_superuser:
self.assertTrue(user.is_active)
else:
self.assertFalse(user.is_active)
key = UserActivationKey.objects.get(user=user)
self.assertEqual(self.fake_activate_key, key.activation_key)
return response, user | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def test_register_user_already_registered(self):
User.objects.create_user("kiwi-tester", "[email protected]", "password")
response = self.client.post(
self.register_url,
{
"username": "test_user",
"password1": __FOR_TESTING__,
"password2": __FOR_TESTING__,
"email": "[email protected]",
},
follow=False,
)
self.assertContains(response, _("A user with that email already exists."))
user = User.objects.filter(username="test_user")
self.assertEqual(user.count(), 0) | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def test_send_mail_for_password_reset(self, mail_sent):
user = User.objects.create_user("kiwi-tester", "[email protected]", "password")
user.is_active = True
user.save()
try:
# https://github.com/mbi/django-simple-captcha/issues/84
# pylint: disable=import-outside-toplevel
from captcha.conf import settings as captcha_settings
captcha_settings.CAPTCHA_TEST_MODE = True
response = self.client.post(
self.password_reset_url,
{
"email": "[email protected]",
"captcha_0": "PASSED",
"captcha_1": "PASSED",
},
follow=True,
)
finally:
captcha_settings.CAPTCHA_TEST_MODE = False
self.assertContains(response, _("Password reset email was sent"))
# Verify mail is sent
mail_sent.assert_called_once() | 1 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
def process_response(self, request, response):
if settings.DEBUG:
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers[
"Content-Security-Policy"
] = "script-src 'self' cdn.crowdin.com;"
return response | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_uploading_svg_with_forbidden_attributes_should_fail(self, file_name):
with open(f"tests/ui/data/{file_name}", "rb") as svg_file:
b64 = base64.b64encode(svg_file.read()).decode()
message = str(_("File contains forbidden attribute:"))
with self.assertRaisesRegex(Fault, message):
self.rpc_client.User.add_attachment("image.svg", b64) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def deny_uploads_containing_script_tag(uploaded_file):
for chunk in uploaded_file.chunks(2048):
if chunk.lower().find(b"<script") > -1:
raise ValidationError(_("File contains forbidden <script> tag"))
if chunk.lower().find(b"onload=") > -1:
raise ValidationError(_("File contains forbidden attribute:") + "onload") | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
async def save_server(self, request):
await self.elg(request)
guild = self.bot.get_guild(int(request.match_info.get('server', '0')))
if guild is None:
self.notfound()
if not guild.get_member(
int(self.getsesh(request)['client']['id'])
).guild_permissions.administrator:
self.notfound()
data = await request.post()
params = []
otherparams = {}
for k in data.keys():
if not k.startswith('channel-'):
otherparams[k] = ','.join(data.getall(k))
continue
param = {'channel_id': int(k[len('channel-'):])}
for v in data.getall(k):
v = v.partition('=')
if v[0] == 'ping':
if 'ping' not in param:
param['ping'] = set()
param['ping'].add(v[-1])
else:
param[v[0]] = v[-1] or None
param['ping'] = '|'.join(param.get('ping', ())) or None
params.append(param)
otherparams['guild_id'] = guild.id
if set(param['channel_id'] for param in params) \
- set(channel.id for channel in guild.channels): # is not empty
raise web.HTTPBadRequest
try:
with self.db.connection:
self.db.executemany(
'UPDATE channels SET lang=:lang, games_ping=:ping \
WHERE channel_id=:channel_id',
params
)
self.db.execute(
'UPDATE guilds SET guild_disabled_commands=:disable_cmd, \
guild_disabled_cogs=:disable_cog, words_censor=:words_censor WHERE guild_id=:guild_id',
otherparams
)
except sql.ProgrammingError as exc:
raise web.HTTPBadRequest(reason=str(exc))
raise web.HTTPSeeOther(request.path) | 1 | Python | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
def render_GET(self, request):
template = unsafe_env.get_template('generate_new.html')
sites_len = len(get_all_canary_sites())
now = datetime.datetime.now()
return template.render(settings=settings, sites_len=sites_len, now=now).encode('utf8') | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def get_signed_upload_url(path: str) -> str:
client = boto3.client(
"s3",
aws_access_key_id=settings.S3_KEY,
aws_secret_access_key=settings.S3_SECRET_KEY,
region_name=settings.S3_REGION,
endpoint_url=settings.S3_ENDPOINT_URL,
)
return client.generate_presigned_url(
ClientMethod="get_object",
Params={
"Bucket": settings.S3_AUTH_UPLOADS_BUCKET,
"Key": path,
},
ExpiresIn=SIGNED_UPLOAD_URL_DURATION,
HttpMethod="GET",
) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def check_xsend_links(
name: str,
name_str_for_test: str,
content_disposition: str = "",
download: bool = False,
) -> None:
self.login("hamlet")
fp = StringIO("zulip!")
fp.name = name
result = self.client_post("/json/user_uploads", {"file": fp})
uri = self.assert_json_success(result)["uri"]
fp_path_id = re.sub("/user_uploads/", "", uri)
fp_path = os.path.split(fp_path_id)[0]
if download:
uri = uri.replace("/user_uploads/", "/user_uploads/download/")
with self.settings(DEVELOPMENT=False):
response = self.client_get(uri)
assert settings.LOCAL_UPLOADS_DIR is not None
test_run, worker = os.path.split(os.path.dirname(settings.LOCAL_UPLOADS_DIR))
self.assertEqual(
response["X-Accel-Redirect"],
"/internal/local/uploads/" + fp_path + "/" + name_str_for_test,
)
if content_disposition != "":
self.assertIn("attachment;", response["Content-disposition"])
self.assertIn(content_disposition, response["Content-disposition"])
else:
self.assertIn("inline;", response["Content-disposition"])
self.assertEqual(set(response["Cache-Control"].split(", ")), {"private", "immutable"}) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def test_avatar_url_local(self) -> None:
self.login("hamlet")
with get_test_image_file("img.png") as image_file:
result = self.client_post("/json/users/me/avatar", {"file": image_file})
response_dict = self.assert_json_success(result)
self.assertIn("avatar_url", response_dict)
base = "/user_avatars/"
url = self.assert_json_success(result)["avatar_url"]
self.assertEqual(base, url[: len(base)])
# That URL is accessible when logged out
self.logout()
result = self.client_get(url)
self.assertEqual(result.status_code, 200)
# We get a resized avatar from it
image_data = read_test_image_file("img.png")
resized_avatar = resize_avatar(image_data)
assert isinstance(result, StreamingHttpResponse)
self.assertEqual(resized_avatar, b"".join(result.streaming_content))
with self.settings(DEVELOPMENT=False):
# In production, this is an X-Accel-Redirect to the
# on-disk content, which nginx serves
result = self.client_get(url)
self.assertEqual(result.status_code, 200)
internal_redirect_path = urlparse(url).path.replace(
"/user_avatars/", "/internal/local/user_avatars/"
)
self.assertEqual(result["X-Accel-Redirect"], internal_redirect_path)
self.assertEqual(b"", result.content) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.