asanypath-native 2.3.0__tar.gz → 2.3.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/Cargo.lock +1 -1
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/Cargo.toml +1 -1
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/PKG-INFO +1 -1
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/asanypath_native.pyi +4 -1
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/azure.rs +18 -17
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/cache.rs +40 -5
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/gcs.rs +11 -5
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/http.rs +129 -23
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/lib.rs +3 -0
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/s3.rs +3 -2
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/ssh.rs +295 -293
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/pyproject.toml +0 -0
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/artifactory.rs +0 -0
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/backend.rs +0 -0
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/src/xml.rs +0 -0
- {asanypath_native-2.3.0 → asanypath_native-2.3.2}/uv.lock +0 -0
|
@@ -142,5 +142,8 @@ async def ssh_unlink(*args: Any, **kwargs: Any) -> None: ...
|
|
|
142
142
|
async def ssh_rename(*args: Any, **kwargs: Any) -> None: ...
|
|
143
143
|
def ssh_resolve_config(
|
|
144
144
|
host: str, config_paths: list[str]
|
|
145
|
-
) -> tuple[str | None, int | None, str | None, str | None]: ...
|
|
145
|
+
) -> tuple[str | None, int | None, str | None, str | None, str | None, str | None]: ...
|
|
146
146
|
def ssh_disconnect_all() -> None: ...
|
|
147
|
+
def ssh_known_host(host: str, port: int, known_hosts: str) -> bool: ...
|
|
148
|
+
async def ssh_scan_host_key(host: str, port: int) -> tuple[str, str]: ...
|
|
149
|
+
def ssh_learn_host_key(host: str, port: int, public_key: str, known_hosts: str) -> None: ...
|
|
@@ -16,6 +16,7 @@ use futures::future::join_all;
|
|
|
16
16
|
use hmac::{Hmac, KeyInit, Mac};
|
|
17
17
|
use pyo3::exceptions::{PyRuntimeError, PyValueError};
|
|
18
18
|
use pyo3::prelude::*;
|
|
19
|
+
use pyo3::pybacked::PyBackedBytes;
|
|
19
20
|
use quick_xml::Reader;
|
|
20
21
|
use quick_xml::events::Event;
|
|
21
22
|
use serde::{Deserialize, Serialize};
|
|
@@ -956,7 +957,7 @@ pub fn az_put_block<'py>(
|
|
|
956
957
|
container: String,
|
|
957
958
|
blob: String,
|
|
958
959
|
block_id: String,
|
|
959
|
-
data:
|
|
960
|
+
data: PyBackedBytes,
|
|
960
961
|
account_name: String,
|
|
961
962
|
account_key: Option<String>,
|
|
962
963
|
sas_token: Option<String>,
|
|
@@ -976,9 +977,10 @@ pub fn az_put_block<'py>(
|
|
|
976
977
|
let mut headers = vec![("content-length".to_string(), data.len().to_string())];
|
|
977
978
|
let params = [("blockid", block_id.as_str()), ("comp", "block")];
|
|
978
979
|
creds.sign("PUT", &url, &mut headers, Some(¶ms));
|
|
979
|
-
let (status, body) =
|
|
980
|
-
|
|
981
|
-
|
|
980
|
+
let (status, body) =
|
|
981
|
+
do_request_light("PUT", &url, &headers, Some(Bytes::from_owner(data)), h2)
|
|
982
|
+
.await
|
|
983
|
+
.map_err(PyRuntimeError::new_err)?;
|
|
982
984
|
if !status.is_success() {
|
|
983
985
|
return Err(status_to_pyerr(status, &creds.error_path(&blob), &body));
|
|
984
986
|
}
|
|
@@ -1127,8 +1129,10 @@ pub fn az_is_dir_batch<'py>(
|
|
|
1127
1129
|
|
|
1128
1130
|
/// Generate a presigned URL for an Azure blob using a Service SAS token.
|
|
1129
1131
|
///
|
|
1130
|
-
///
|
|
1131
|
-
///
|
|
1132
|
+
/// The SAS is signed with `account_key`, scoped to this blob, `method` and
|
|
1133
|
+
/// `expires`. A configured `sas_token` is a credential that may grant far
|
|
1134
|
+
/// more (other blobs, write access, a longer lifetime), so it is never handed
|
|
1135
|
+
/// out as a presigned URL.
|
|
1132
1136
|
#[pyfunction]
|
|
1133
1137
|
pub fn az_presign(
|
|
1134
1138
|
endpoint: String,
|
|
@@ -1149,21 +1153,18 @@ pub fn az_presign(
|
|
|
1149
1153
|
format!("{}/{}/{}", base, container, blob_path)
|
|
1150
1154
|
};
|
|
1151
1155
|
|
|
1152
|
-
// If SAS token already exists, just append it
|
|
1153
|
-
if let Some(ref sas) = sas_token {
|
|
1154
|
-
if !sas.is_empty() {
|
|
1155
|
-
let sep = if blob_url.contains('?') { "&" } else { "?" };
|
|
1156
|
-
return Ok(format!("{}{}{}", blob_url, sep, sas));
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
1156
|
let key_str = account_key
|
|
1161
1157
|
.as_ref()
|
|
1162
1158
|
.filter(|k| !k.is_empty())
|
|
1163
1159
|
.ok_or_else(|| {
|
|
1164
|
-
|
|
1165
|
-
"
|
|
1166
|
-
|
|
1160
|
+
let hint = if sas_token.as_deref().is_some_and(|s| !s.is_empty()) {
|
|
1161
|
+
"; the configured SAS token is a credential and is not shared"
|
|
1162
|
+
} else {
|
|
1163
|
+
""
|
|
1164
|
+
};
|
|
1165
|
+
pyo3::exceptions::PyValueError::new_err(format!(
|
|
1166
|
+
"presign requires account_key to sign a blob-scoped SAS{hint}"
|
|
1167
|
+
))
|
|
1167
1168
|
})?;
|
|
1168
1169
|
|
|
1169
1170
|
let key_bytes = B64
|
|
@@ -17,6 +17,43 @@ fn database_error(error: rusqlite::Error) -> PyErr {
|
|
|
17
17
|
PyOSError::new_err(format!("Download cache database: {error}"))
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
/// Create (or tighten) the cache directory and database file so only the
|
|
21
|
+
/// owner can read them: entries hold bytes fetched with private credentials.
|
|
22
|
+
/// SQLite gives its journal file the database file's mode.
|
|
23
|
+
fn prepare_private_files(directory: &std::path::Path, database: &std::path::Path) -> PyResult<()> {
|
|
24
|
+
let create_error = |error: std::io::Error| {
|
|
25
|
+
PyOSError::new_err(format!("Create download cache directory: {error}"))
|
|
26
|
+
};
|
|
27
|
+
#[cfg(unix)]
|
|
28
|
+
{
|
|
29
|
+
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
|
|
30
|
+
if let Some(parent) = directory.parent() {
|
|
31
|
+
std::fs::create_dir_all(parent).map_err(create_error)?;
|
|
32
|
+
}
|
|
33
|
+
match std::fs::DirBuilder::new().mode(0o700).create(directory) {
|
|
34
|
+
Ok(()) => {}
|
|
35
|
+
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
|
36
|
+
// Best effort for directories created by earlier versions.
|
|
37
|
+
let _ = std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700));
|
|
38
|
+
}
|
|
39
|
+
Err(error) => return Err(create_error(error)),
|
|
40
|
+
}
|
|
41
|
+
std::fs::OpenOptions::new()
|
|
42
|
+
.create(true)
|
|
43
|
+
.append(true)
|
|
44
|
+
.mode(0o600)
|
|
45
|
+
.open(database)
|
|
46
|
+
.map_err(create_error)?;
|
|
47
|
+
let _ = std::fs::set_permissions(database, std::fs::Permissions::from_mode(0o600));
|
|
48
|
+
}
|
|
49
|
+
#[cfg(not(unix))]
|
|
50
|
+
{
|
|
51
|
+
let _ = database;
|
|
52
|
+
std::fs::create_dir_all(directory).map_err(create_error)?;
|
|
53
|
+
}
|
|
54
|
+
Ok(())
|
|
55
|
+
}
|
|
56
|
+
|
|
20
57
|
fn now() -> PyResult<f64> {
|
|
21
58
|
SystemTime::now()
|
|
22
59
|
.duration_since(UNIX_EPOCH)
|
|
@@ -58,11 +95,9 @@ impl DownloadCache {
|
|
|
58
95
|
py.detach(|| {
|
|
59
96
|
// Never open or migrate a legacy DiskCache database.
|
|
60
97
|
let directory = directory.join("native-v1");
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
let connection =
|
|
65
|
-
Connection::open(directory.join("cache.sqlite3")).map_err(database_error)?;
|
|
98
|
+
let database = directory.join("cache.sqlite3");
|
|
99
|
+
prepare_private_files(&directory, &database)?;
|
|
100
|
+
let connection = Connection::open(&database).map_err(database_error)?;
|
|
66
101
|
connection
|
|
67
102
|
.busy_timeout(Duration::from_secs(60))
|
|
68
103
|
.map_err(database_error)?;
|
|
@@ -18,6 +18,7 @@ use futures::future::join_all;
|
|
|
18
18
|
use pyo3::exceptions::PyRuntimeError;
|
|
19
19
|
use pyo3::exceptions::PyValueError;
|
|
20
20
|
use pyo3::prelude::*;
|
|
21
|
+
use pyo3::pybacked::PyBackedBytes;
|
|
21
22
|
use serde::{Deserialize, Serialize};
|
|
22
23
|
use sonic_rs::JsonValueTrait;
|
|
23
24
|
use std::collections::{HashMap, HashSet};
|
|
@@ -995,7 +996,7 @@ pub fn gcs_start_resumable<'py>(
|
|
|
995
996
|
pub fn gcs_upload_chunk<'py>(
|
|
996
997
|
py: Python<'py>,
|
|
997
998
|
session_uri: String,
|
|
998
|
-
data:
|
|
999
|
+
data: PyBackedBytes,
|
|
999
1000
|
offset: u64,
|
|
1000
1001
|
total: u64,
|
|
1001
1002
|
use_h2: Option<bool>,
|
|
@@ -1011,10 +1012,15 @@ pub fn gcs_upload_chunk<'py>(
|
|
|
1011
1012
|
format!("bytes {offset}-{end}/{total}"),
|
|
1012
1013
|
),
|
|
1013
1014
|
];
|
|
1014
|
-
let (status, body, _h) =
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1015
|
+
let (status, body, _h) = do_request(
|
|
1016
|
+
"PUT",
|
|
1017
|
+
&session_uri,
|
|
1018
|
+
&headers,
|
|
1019
|
+
Some(Bytes::from_owner(data)),
|
|
1020
|
+
h2,
|
|
1021
|
+
)
|
|
1022
|
+
.await
|
|
1023
|
+
.map_err(PyRuntimeError::new_err)?;
|
|
1018
1024
|
// 308 Resume Incomplete = intermediate chunk accepted; 2xx = final chunk done.
|
|
1019
1025
|
if status.as_u16() == 308 || status.is_success() {
|
|
1020
1026
|
Ok(())
|
|
@@ -21,7 +21,8 @@ use backon::{ExponentialBuilder, Retryable};
|
|
|
21
21
|
use bytes::Bytes;
|
|
22
22
|
use pyo3::PyErr;
|
|
23
23
|
use pyo3::exceptions::{PyFileNotFoundError, PyPermissionError, PyRuntimeError};
|
|
24
|
-
use reqwest::{
|
|
24
|
+
use reqwest::header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, LOCATION};
|
|
25
|
+
use reqwest::{Client, Method, Response, StatusCode, Url};
|
|
25
26
|
|
|
26
27
|
/// Check whether a reqwest error is transient and worth retrying.
|
|
27
28
|
fn is_retryable(e: &String) -> bool {
|
|
@@ -64,6 +65,9 @@ fn base_builder() -> reqwest::ClientBuilder {
|
|
|
64
65
|
.no_brotli()
|
|
65
66
|
.no_deflate()
|
|
66
67
|
.no_proxy()
|
|
68
|
+
// Redirects are followed by `send_following_redirects`, which drops
|
|
69
|
+
// credential-bearing headers when a redirect leaves the origin.
|
|
70
|
+
.redirect(reqwest::redirect::Policy::none())
|
|
67
71
|
}
|
|
68
72
|
|
|
69
73
|
pub fn get_client(use_h2: bool) -> &'static Client {
|
|
@@ -79,6 +83,118 @@ pub fn get_client(use_h2: bool) -> &'static Client {
|
|
|
79
83
|
}
|
|
80
84
|
}
|
|
81
85
|
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
// Redirects and error messages
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
const MAX_REDIRECTS: usize = 10;
|
|
91
|
+
|
|
92
|
+
/// Request headers that may follow a redirect to another origin. Anything
|
|
93
|
+
/// else (Authorization, API-key headers, signed-request headers, ...) may
|
|
94
|
+
/// carry credentials for the original origin only.
|
|
95
|
+
const CROSS_ORIGIN_HEADERS: &[&str] = &[
|
|
96
|
+
"accept",
|
|
97
|
+
"accept-encoding",
|
|
98
|
+
"accept-language",
|
|
99
|
+
"if-match",
|
|
100
|
+
"if-modified-since",
|
|
101
|
+
"if-none-match",
|
|
102
|
+
"if-range",
|
|
103
|
+
"if-unmodified-since",
|
|
104
|
+
"range",
|
|
105
|
+
"user-agent",
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
/// `url` without userinfo, query or fragment, for error messages: SAS
|
|
109
|
+
/// tokens and presigned signatures live in the query string.
|
|
110
|
+
pub fn redact_url(url: &str) -> String {
|
|
111
|
+
match Url::parse(url) {
|
|
112
|
+
Ok(mut u) => {
|
|
113
|
+
let _ = u.set_username("");
|
|
114
|
+
let _ = u.set_password(None);
|
|
115
|
+
u.set_query(None);
|
|
116
|
+
u.set_fragment(None);
|
|
117
|
+
u.to_string()
|
|
118
|
+
}
|
|
119
|
+
Err(_) => url.split(['?', '#']).next().unwrap_or("").to_string(),
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/// Describe a reqwest error without the request URL it embeds.
|
|
124
|
+
fn error_string(e: reqwest::Error, url: &str) -> String {
|
|
125
|
+
format!("{} for url ({})", e.without_url(), redact_url(url))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// Send a request, following redirects the way reqwest would, except that
|
|
129
|
+
/// headers outside `CROSS_ORIGIN_HEADERS` are dropped once a redirect leaves
|
|
130
|
+
/// the original scheme, host and port.
|
|
131
|
+
async fn send_following_redirects(
|
|
132
|
+
client: &Client,
|
|
133
|
+
method: Method,
|
|
134
|
+
url: &str,
|
|
135
|
+
headers: &[(String, String)],
|
|
136
|
+
body: Option<Bytes>,
|
|
137
|
+
) -> Result<Response, String> {
|
|
138
|
+
let mut method = method;
|
|
139
|
+
let mut url = Url::parse(url).map_err(|e| format!("invalid url ({}): {e}", redact_url(url)))?;
|
|
140
|
+
let origin = url.origin();
|
|
141
|
+
let mut headers = headers.to_vec();
|
|
142
|
+
let mut body = body;
|
|
143
|
+
for _ in 0..=MAX_REDIRECTS {
|
|
144
|
+
let mut req = client.request(method.clone(), url.clone());
|
|
145
|
+
for (k, v) in &headers {
|
|
146
|
+
req = req.header(k.as_str(), v.as_str());
|
|
147
|
+
}
|
|
148
|
+
if let Some(b) = body.clone() {
|
|
149
|
+
req = req.body(b);
|
|
150
|
+
}
|
|
151
|
+
let resp = req
|
|
152
|
+
.send()
|
|
153
|
+
.await
|
|
154
|
+
.map_err(|e| error_string(e, url.as_str()))?;
|
|
155
|
+
let status = resp.status();
|
|
156
|
+
let next = match status {
|
|
157
|
+
StatusCode::MOVED_PERMANENTLY
|
|
158
|
+
| StatusCode::FOUND
|
|
159
|
+
| StatusCode::SEE_OTHER
|
|
160
|
+
| StatusCode::TEMPORARY_REDIRECT
|
|
161
|
+
| StatusCode::PERMANENT_REDIRECT => resp
|
|
162
|
+
.headers()
|
|
163
|
+
.get(LOCATION)
|
|
164
|
+
.and_then(|v| v.to_str().ok())
|
|
165
|
+
.and_then(|loc| url.join(loc).ok())
|
|
166
|
+
.filter(|u| matches!(u.scheme(), "http" | "https")),
|
|
167
|
+
_ => None,
|
|
168
|
+
};
|
|
169
|
+
let Some(next) = next else {
|
|
170
|
+
return Ok(resp);
|
|
171
|
+
};
|
|
172
|
+
if matches!(
|
|
173
|
+
status,
|
|
174
|
+
StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER
|
|
175
|
+
) && method != Method::HEAD
|
|
176
|
+
{
|
|
177
|
+
method = Method::GET;
|
|
178
|
+
body = None;
|
|
179
|
+
headers.retain(|(k, _)| {
|
|
180
|
+
let k = k.to_ascii_lowercase();
|
|
181
|
+
k != CONTENT_TYPE.as_str()
|
|
182
|
+
&& k != CONTENT_LENGTH.as_str()
|
|
183
|
+
&& k != CONTENT_ENCODING.as_str()
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if next.origin() != origin {
|
|
187
|
+
headers
|
|
188
|
+
.retain(|(k, _)| CROSS_ORIGIN_HEADERS.contains(&k.to_ascii_lowercase().as_str()));
|
|
189
|
+
}
|
|
190
|
+
url = next;
|
|
191
|
+
}
|
|
192
|
+
Err(format!(
|
|
193
|
+
"too many redirects for url ({})",
|
|
194
|
+
redact_url(url.as_str())
|
|
195
|
+
))
|
|
196
|
+
}
|
|
197
|
+
|
|
82
198
|
// ---------------------------------------------------------------------------
|
|
83
199
|
// Generic HTTP request executor
|
|
84
200
|
// ---------------------------------------------------------------------------
|
|
@@ -98,14 +214,9 @@ pub async fn do_request(
|
|
|
98
214
|
let body = body_bytes.clone();
|
|
99
215
|
|
|
100
216
|
(async || {
|
|
101
|
-
let
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
if let Some(b) = body.clone() {
|
|
106
|
-
req = req.body(b);
|
|
107
|
-
}
|
|
108
|
-
let resp = req.send().await.map_err(|e| e.to_string())?;
|
|
217
|
+
let resp =
|
|
218
|
+
send_following_redirects(client, method_parsed.clone(), url, &headers, body.clone())
|
|
219
|
+
.await?;
|
|
109
220
|
let status = resp.status();
|
|
110
221
|
if is_retryable_status(status) {
|
|
111
222
|
return Err(format!("HTTP {} (retryable)", status.as_u16()));
|
|
@@ -115,7 +226,7 @@ pub async fn do_request(
|
|
|
115
226
|
.iter()
|
|
116
227
|
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
|
|
117
228
|
.collect();
|
|
118
|
-
let resp_body = resp.bytes().await.map_err(|e| e
|
|
229
|
+
let resp_body = resp.bytes().await.map_err(|e| error_string(e, url))?;
|
|
119
230
|
Ok((status, resp_body, resp_headers))
|
|
120
231
|
})
|
|
121
232
|
.retry(retry_backoff())
|
|
@@ -138,19 +249,14 @@ pub async fn do_request_light(
|
|
|
138
249
|
let body = body_bytes.clone();
|
|
139
250
|
|
|
140
251
|
(async || {
|
|
141
|
-
let
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}
|
|
145
|
-
if let Some(b) = body.clone() {
|
|
146
|
-
req = req.body(b);
|
|
147
|
-
}
|
|
148
|
-
let resp = req.send().await.map_err(|e| e.to_string())?;
|
|
252
|
+
let resp =
|
|
253
|
+
send_following_redirects(client, method_parsed.clone(), url, &headers, body.clone())
|
|
254
|
+
.await?;
|
|
149
255
|
let status = resp.status();
|
|
150
256
|
if is_retryable_status(status) {
|
|
151
257
|
return Err(format!("HTTP {} (retryable)", status.as_u16()));
|
|
152
258
|
}
|
|
153
|
-
let resp_body = resp.bytes().await.map_err(|e| e
|
|
259
|
+
let resp_body = resp.bytes().await.map_err(|e| error_string(e, url))?;
|
|
154
260
|
Ok((status, resp_body))
|
|
155
261
|
})
|
|
156
262
|
.retry(retry_backoff())
|
|
@@ -185,12 +291,12 @@ pub async fn do_request_stream_file(
|
|
|
185
291
|
req = req
|
|
186
292
|
.header("content-length", content_length.to_string())
|
|
187
293
|
.body(reqwest::Body::wrap_stream(stream));
|
|
188
|
-
let resp = req.send().await.map_err(|e| e
|
|
294
|
+
let resp = req.send().await.map_err(|e| error_string(e, url))?;
|
|
189
295
|
let status = resp.status();
|
|
190
296
|
if is_retryable_status(status) {
|
|
191
297
|
return Err(format!("HTTP {} (retryable)", status.as_u16()));
|
|
192
298
|
}
|
|
193
|
-
let resp_body = resp.bytes().await.map_err(|e| e
|
|
299
|
+
let resp_body = resp.bytes().await.map_err(|e| error_string(e, url))?;
|
|
194
300
|
Ok((status, resp_body))
|
|
195
301
|
})
|
|
196
302
|
.retry(retry_backoff())
|
|
@@ -250,7 +356,7 @@ async fn _http_request(
|
|
|
250
356
|
.await
|
|
251
357
|
.map_err(|e| PyRuntimeError::new_err(e))?;
|
|
252
358
|
if !status.is_success() {
|
|
253
|
-
return Err(status_to_pyerr(status, url, &resp_body));
|
|
359
|
+
return Err(status_to_pyerr(status, &redact_url(url), &resp_body));
|
|
254
360
|
}
|
|
255
361
|
Ok((resp_body, resp_headers))
|
|
256
362
|
}
|
|
@@ -468,7 +574,7 @@ pub fn http_scrape_links(
|
|
|
468
574
|
.await
|
|
469
575
|
.map_err(|e| PyRuntimeError::new_err(e))?;
|
|
470
576
|
if !status.is_success() {
|
|
471
|
-
return Err(status_to_pyerr(status, &url, &body));
|
|
577
|
+
return Err(status_to_pyerr(status, &redact_url(&url), &body));
|
|
472
578
|
}
|
|
473
579
|
|
|
474
580
|
let html_str = String::from_utf8_lossy(&body).into_owned();
|
|
@@ -126,6 +126,9 @@ fn asanypath_native(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
|
126
126
|
m.add_function(wrap_pyfunction!(ssh::ssh_rename, m)?)?;
|
|
127
127
|
m.add_function(wrap_pyfunction!(ssh::ssh_resolve_config, m)?)?;
|
|
128
128
|
m.add_function(wrap_pyfunction!(ssh::ssh_disconnect_all, m)?)?;
|
|
129
|
+
m.add_function(wrap_pyfunction!(ssh::ssh_known_host, m)?)?;
|
|
130
|
+
m.add_function(wrap_pyfunction!(ssh::ssh_scan_host_key, m)?)?;
|
|
131
|
+
m.add_function(wrap_pyfunction!(ssh::ssh_learn_host_key, m)?)?;
|
|
129
132
|
// Unified
|
|
130
133
|
m.add_function(wrap_pyfunction!(backend::range_read, m)?)?;
|
|
131
134
|
Ok(())
|
|
@@ -25,6 +25,7 @@ use bytes::Bytes;
|
|
|
25
25
|
use pyo3::exceptions::PyRuntimeError;
|
|
26
26
|
use pyo3::exceptions::PyValueError;
|
|
27
27
|
use pyo3::prelude::*;
|
|
28
|
+
use pyo3::pybacked::PyBackedBytes;
|
|
28
29
|
use quick_xml::Reader;
|
|
29
30
|
use quick_xml::{XmlVersion, events::Event};
|
|
30
31
|
use serde::{Deserialize, Serialize};
|
|
@@ -1154,7 +1155,7 @@ pub fn s3_upload_part<'py>(
|
|
|
1154
1155
|
key: String,
|
|
1155
1156
|
upload_id: String,
|
|
1156
1157
|
part_number: u32,
|
|
1157
|
-
data:
|
|
1158
|
+
data: PyBackedBytes,
|
|
1158
1159
|
region: String,
|
|
1159
1160
|
access_key: String,
|
|
1160
1161
|
secret_key: String,
|
|
@@ -1181,7 +1182,7 @@ pub fn s3_upload_part<'py>(
|
|
|
1181
1182
|
"PUT",
|
|
1182
1183
|
&s3_path,
|
|
1183
1184
|
&query,
|
|
1184
|
-
Some(Bytes::
|
|
1185
|
+
Some(Bytes::from_owner(data)),
|
|
1185
1186
|
h2,
|
|
1186
1187
|
&[],
|
|
1187
1188
|
)
|
|
@@ -13,13 +13,16 @@ use std::collections::HashMap;
|
|
|
13
13
|
use std::io::SeekFrom;
|
|
14
14
|
use std::sync::Arc;
|
|
15
15
|
|
|
16
|
-
use pyo3::exceptions::PyRuntimeError;
|
|
16
|
+
use pyo3::exceptions::{PyRuntimeError, PyTypeError};
|
|
17
17
|
use pyo3::prelude::*;
|
|
18
|
-
use pyo3::types::PyBytes;
|
|
18
|
+
use pyo3::types::{PyBytes, PyDict};
|
|
19
19
|
use russh::client::{self, Handle};
|
|
20
20
|
#[cfg(unix)]
|
|
21
21
|
use russh::keys::agent::client::AgentClient;
|
|
22
|
-
use russh::keys::{
|
|
22
|
+
use russh::keys::known_hosts::{known_host_keys_path, learn_known_hosts_path};
|
|
23
|
+
use russh::keys::{
|
|
24
|
+
HashAlg, PrivateKeyWithHashAlg, PublicKey, check_known_hosts_path, load_secret_key,
|
|
25
|
+
};
|
|
23
26
|
use russh_sftp::client::SftpSession;
|
|
24
27
|
use russh_sftp::protocol::{FileAttributes, OpenFlags};
|
|
25
28
|
use ssh2_config::{ParseRule, SshConfig};
|
|
@@ -32,9 +35,12 @@ fn err<E: std::fmt::Display>(e: E) -> PyErr {
|
|
|
32
35
|
}
|
|
33
36
|
|
|
34
37
|
// ---------------------------------------------------------------------------
|
|
35
|
-
//
|
|
38
|
+
// Connection descriptor, parsed from the ``**self._native_kwargs`` every
|
|
39
|
+
// SSHPath op spreads into its native call.
|
|
36
40
|
// ---------------------------------------------------------------------------
|
|
37
41
|
|
|
42
|
+
#[derive(FromPyObject)]
|
|
43
|
+
#[pyo3(from_item_all)]
|
|
38
44
|
struct ConnParams {
|
|
39
45
|
host: String,
|
|
40
46
|
port: u16,
|
|
@@ -43,28 +49,24 @@ struct ConnParams {
|
|
|
43
49
|
key_path: Option<String>,
|
|
44
50
|
key_passphrase: Option<String>,
|
|
45
51
|
use_agent: bool,
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
/// Build a `ConnParams` from the flat connection kwargs spread by
|
|
50
|
-
/// `SSHPath._native_kwargs`. Repeated verbatim at the top of each op.
|
|
51
|
-
macro_rules! conn {
|
|
52
|
-
($host:ident, $port:ident, $user:ident, $password:ident, $key_path:ident,
|
|
53
|
-
$key_passphrase:ident, $use_agent:ident, $strict_host_key:ident) => {
|
|
54
|
-
ConnParams {
|
|
55
|
-
host: $host,
|
|
56
|
-
port: $port,
|
|
57
|
-
user: $user,
|
|
58
|
-
password: $password,
|
|
59
|
-
key_path: $key_path,
|
|
60
|
-
key_passphrase: $key_passphrase,
|
|
61
|
-
use_agent: $use_agent,
|
|
62
|
-
strict_host_key: $strict_host_key,
|
|
63
|
-
}
|
|
64
|
-
};
|
|
52
|
+
host_key_policy: String,
|
|
53
|
+
known_hosts: String,
|
|
65
54
|
}
|
|
66
55
|
|
|
56
|
+
const CONN_FIELDS: usize = 9;
|
|
57
|
+
|
|
67
58
|
impl ConnParams {
|
|
59
|
+
fn from_kwargs(kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<Self> {
|
|
60
|
+
let kwargs = kwargs.ok_or_else(|| PyTypeError::new_err("missing SSH connection kwargs"))?;
|
|
61
|
+
if kwargs.len() != CONN_FIELDS {
|
|
62
|
+
return Err(PyTypeError::new_err(format!(
|
|
63
|
+
"expected {CONN_FIELDS} SSH connection kwargs, got {}",
|
|
64
|
+
kwargs.len()
|
|
65
|
+
)));
|
|
66
|
+
}
|
|
67
|
+
kwargs.extract()
|
|
68
|
+
}
|
|
69
|
+
|
|
68
70
|
fn auth(&self) -> AuthSpec {
|
|
69
71
|
AuthSpec {
|
|
70
72
|
password: self.password.clone(),
|
|
@@ -76,14 +78,82 @@ impl ConnParams {
|
|
|
76
78
|
}
|
|
77
79
|
|
|
78
80
|
// ---------------------------------------------------------------------------
|
|
79
|
-
// russh client handler — verifies the server key against
|
|
80
|
-
//
|
|
81
|
+
// russh client handler — verifies the server key against a known_hosts file
|
|
82
|
+
// following OpenSSH's StrictHostKeyChecking semantics.
|
|
81
83
|
// ---------------------------------------------------------------------------
|
|
82
84
|
|
|
85
|
+
/// OpenSSH `StrictHostKeyChecking`, plus `Disabled` for an explicit opt-out
|
|
86
|
+
/// (`known_hosts=()` / `SSH_KNOWN_HOSTS=none`) that never touches any file.
|
|
87
|
+
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
88
|
+
enum HostKeyPolicy {
|
|
89
|
+
/// Unknown and changed keys are refused.
|
|
90
|
+
Yes,
|
|
91
|
+
/// As `Yes`; the Python layer prompts for unknown hosts when interactive.
|
|
92
|
+
Ask,
|
|
93
|
+
/// Unknown keys are recorded and accepted; changed keys are refused.
|
|
94
|
+
AcceptNew,
|
|
95
|
+
/// Unknown keys are recorded; changed keys are accepted.
|
|
96
|
+
No,
|
|
97
|
+
Disabled,
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
impl HostKeyPolicy {
|
|
101
|
+
fn parse(value: &str) -> Result<Self, String> {
|
|
102
|
+
match value.to_ascii_lowercase().as_str() {
|
|
103
|
+
"yes" | "true" => Ok(Self::Yes),
|
|
104
|
+
"ask" => Ok(Self::Ask),
|
|
105
|
+
"accept-new" => Ok(Self::AcceptNew),
|
|
106
|
+
"no" | "off" | "false" => Ok(Self::No),
|
|
107
|
+
"disabled" => Ok(Self::Disabled),
|
|
108
|
+
other => Err(format!("unsupported host key policy {other:?}")),
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
fn host_label(host: &str, port: u16) -> String {
|
|
114
|
+
if port == 22 {
|
|
115
|
+
host.to_string()
|
|
116
|
+
} else {
|
|
117
|
+
format!("[{host}]:{port}")
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
fn describe_key(key: &PublicKey) -> String {
|
|
122
|
+
format!(
|
|
123
|
+
"{} key fingerprint is {}",
|
|
124
|
+
key.algorithm(),
|
|
125
|
+
key.fingerprint(HashAlg::Sha256)
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/// Host names that can be written to known_hosts as-is: no separators,
|
|
130
|
+
/// patterns or markers that would make the entry match other hosts.
|
|
131
|
+
fn is_plain_host(host: &str) -> bool {
|
|
132
|
+
!host.is_empty()
|
|
133
|
+
&& host
|
|
134
|
+
.bytes()
|
|
135
|
+
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':'))
|
|
136
|
+
}
|
|
137
|
+
|
|
83
138
|
struct Handler {
|
|
84
139
|
host: String,
|
|
85
140
|
port: u16,
|
|
86
|
-
|
|
141
|
+
policy: HostKeyPolicy,
|
|
142
|
+
known_hosts: String,
|
|
143
|
+
/// Why the server key was refused, reported instead of russh's generic error.
|
|
144
|
+
rejected: Arc<Mutex<Option<String>>>,
|
|
145
|
+
/// The server key, kept for `ssh_scan_host_key`.
|
|
146
|
+
seen: Arc<Mutex<Option<PublicKey>>>,
|
|
147
|
+
/// Set when `StrictHostKeyChecking no` let a changed key through; like
|
|
148
|
+
/// OpenSSH, password authentication is then refused.
|
|
149
|
+
key_changed: Arc<std::sync::atomic::AtomicBool>,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
impl Handler {
|
|
153
|
+
fn reject(&self, reason: String) -> Result<bool, anyhow::Error> {
|
|
154
|
+
*self.rejected.lock().unwrap() = Some(reason);
|
|
155
|
+
Ok(false)
|
|
156
|
+
}
|
|
87
157
|
}
|
|
88
158
|
|
|
89
159
|
impl client::Handler for Handler {
|
|
@@ -93,15 +163,44 @@ impl client::Handler for Handler {
|
|
|
93
163
|
&mut self,
|
|
94
164
|
server_public_key: &russh::keys::PublicKeyOrCertificate,
|
|
95
165
|
) -> Result<bool, Self::Error> {
|
|
96
|
-
if
|
|
166
|
+
if let russh::keys::PublicKeyOrCertificate::PublicKey { key, .. } = server_public_key {
|
|
167
|
+
*self.seen.lock().unwrap() = Some(key.clone());
|
|
168
|
+
}
|
|
169
|
+
if self.policy == HostKeyPolicy::Disabled {
|
|
97
170
|
return Ok(true);
|
|
98
171
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
172
|
+
let russh::keys::PublicKeyOrCertificate::PublicKey { key, .. } = server_public_key else {
|
|
173
|
+
return self.reject("host certificates are not supported".to_string());
|
|
174
|
+
};
|
|
175
|
+
let label = host_label(&self.host, self.port);
|
|
176
|
+
match check_known_hosts_path(&self.host, self.port, key, &self.known_hosts) {
|
|
177
|
+
Ok(true) => Ok(true),
|
|
178
|
+
Ok(false) => match self.policy {
|
|
179
|
+
HostKeyPolicy::AcceptNew | HostKeyPolicy::No if !is_plain_host(&self.host) => self
|
|
180
|
+
.reject(format!(
|
|
181
|
+
"refusing to record a host key for {label:?}: not a plain host name"
|
|
182
|
+
)),
|
|
183
|
+
HostKeyPolicy::AcceptNew | HostKeyPolicy::No => {
|
|
184
|
+
learn_known_hosts_path(&self.host, self.port, key, &self.known_hosts)?;
|
|
185
|
+
Ok(true)
|
|
186
|
+
}
|
|
187
|
+
_ => self.reject(format!(
|
|
188
|
+
"no host key is known for {label} in {}; {}",
|
|
189
|
+
self.known_hosts,
|
|
190
|
+
describe_key(key)
|
|
191
|
+
)),
|
|
192
|
+
},
|
|
193
|
+
Err(russh::keys::Error::KeyChanged { .. }) if self.policy == HostKeyPolicy::No => {
|
|
194
|
+
self.key_changed
|
|
195
|
+
.store(true, std::sync::atomic::Ordering::Relaxed);
|
|
196
|
+
Ok(true)
|
|
103
197
|
}
|
|
104
|
-
russh::keys::
|
|
198
|
+
Err(russh::keys::Error::KeyChanged { line }) => self.reject(format!(
|
|
199
|
+
"REMOTE HOST IDENTIFICATION HAS CHANGED for {label}: {} does not match {}:{line}",
|
|
200
|
+
describe_key(key),
|
|
201
|
+
self.known_hosts
|
|
202
|
+
)),
|
|
203
|
+
Err(e) => Err(e.into()),
|
|
105
204
|
}
|
|
106
205
|
}
|
|
107
206
|
}
|
|
@@ -119,13 +218,27 @@ struct AuthSpec {
|
|
|
119
218
|
}
|
|
120
219
|
|
|
121
220
|
impl AuthSpec {
|
|
221
|
+
/// Pool-key component: a digest of every credential, so a pooled session
|
|
222
|
+
/// is only reused by callers presenting the same credentials.
|
|
122
223
|
fn fingerprint(&self) -> String {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
self.
|
|
127
|
-
self.
|
|
128
|
-
|
|
224
|
+
use sha2::{Digest, Sha256};
|
|
225
|
+
let mut hasher = Sha256::new();
|
|
226
|
+
for part in [
|
|
227
|
+
Some(if self.use_agent { "agent" } else { "" }),
|
|
228
|
+
self.key_path.as_deref(),
|
|
229
|
+
self.key_passphrase.as_deref(),
|
|
230
|
+
self.password.as_deref(),
|
|
231
|
+
] {
|
|
232
|
+
let bytes = part.map(str::as_bytes).unwrap_or_default();
|
|
233
|
+
hasher.update([part.is_some() as u8]);
|
|
234
|
+
hasher.update((bytes.len() as u64).to_le_bytes());
|
|
235
|
+
hasher.update(bytes);
|
|
236
|
+
}
|
|
237
|
+
hasher
|
|
238
|
+
.finalize()
|
|
239
|
+
.iter()
|
|
240
|
+
.map(|b| format!("{b:02x}"))
|
|
241
|
+
.collect()
|
|
129
242
|
}
|
|
130
243
|
}
|
|
131
244
|
|
|
@@ -250,12 +363,15 @@ fn sftp_pool() -> &'static Pool {
|
|
|
250
363
|
|
|
251
364
|
async fn session_for(conn: &ConnParams) -> Result<Arc<SftpConn>, String> {
|
|
252
365
|
let auth = conn.auth();
|
|
366
|
+
let policy = HostKeyPolicy::parse(&conn.host_key_policy)?;
|
|
253
367
|
let key = format!(
|
|
254
|
-
"{}@{}:{}#{}",
|
|
368
|
+
"{}@{}:{}#{}#{}#{}",
|
|
255
369
|
conn.user,
|
|
256
370
|
conn.host,
|
|
257
371
|
conn.port,
|
|
258
|
-
auth.fingerprint()
|
|
372
|
+
auth.fingerprint(),
|
|
373
|
+
conn.host_key_policy.to_ascii_lowercase(),
|
|
374
|
+
conn.known_hosts
|
|
259
375
|
);
|
|
260
376
|
{
|
|
261
377
|
let guard = sftp_pool().lock().unwrap();
|
|
@@ -265,14 +381,33 @@ async fn session_for(conn: &ConnParams) -> Result<Arc<SftpConn>, String> {
|
|
|
265
381
|
}
|
|
266
382
|
|
|
267
383
|
let config = Arc::new(client::Config::default());
|
|
384
|
+
let rejected = Arc::new(Mutex::new(None));
|
|
385
|
+
let key_changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
|
268
386
|
let handler = Handler {
|
|
269
387
|
host: conn.host.clone(),
|
|
270
388
|
port: conn.port,
|
|
271
|
-
|
|
389
|
+
policy,
|
|
390
|
+
known_hosts: conn.known_hosts.clone(),
|
|
391
|
+
rejected: rejected.clone(),
|
|
392
|
+
seen: Arc::new(Mutex::new(None)),
|
|
393
|
+
key_changed: key_changed.clone(),
|
|
272
394
|
};
|
|
273
|
-
let mut handle = client::connect(config, (conn.host.as_str(), conn.port), handler)
|
|
274
|
-
|
|
275
|
-
|
|
395
|
+
let mut handle = match client::connect(config, (conn.host.as_str(), conn.port), handler).await {
|
|
396
|
+
Ok(handle) => handle,
|
|
397
|
+
Err(e) => {
|
|
398
|
+
if let Some(reason) = rejected.lock().unwrap().take() {
|
|
399
|
+
return Err(format!("Host key verification failed: {reason}"));
|
|
400
|
+
}
|
|
401
|
+
return Err(format!("ssh connect {}:{}: {e}", conn.host, conn.port));
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
if key_changed.load(std::sync::atomic::Ordering::Relaxed) && auth.password.is_some() {
|
|
405
|
+
return Err(format!(
|
|
406
|
+
"Host key for {} has changed; password authentication is disabled \
|
|
407
|
+
to avoid a man-in-the-middle attack (StrictHostKeyChecking no)",
|
|
408
|
+
host_label(&conn.host, conn.port)
|
|
409
|
+
));
|
|
410
|
+
}
|
|
276
411
|
authenticate(&mut handle, &conn.user, &auth).await?;
|
|
277
412
|
let channel = handle
|
|
278
413
|
.channel_open_session()
|
|
@@ -307,29 +442,13 @@ pub fn ssh_disconnect_all() {
|
|
|
307
442
|
|
|
308
443
|
/// Read a remote file fully. Returns bytes.
|
|
309
444
|
#[pyfunction]
|
|
310
|
-
#[
|
|
445
|
+
#[pyo3(signature = (path, **conn))]
|
|
311
446
|
pub fn ssh_read<'py>(
|
|
312
447
|
py: Python<'py>,
|
|
313
448
|
path: String,
|
|
314
|
-
|
|
315
|
-
port: u16,
|
|
316
|
-
user: String,
|
|
317
|
-
password: Option<String>,
|
|
318
|
-
key_path: Option<String>,
|
|
319
|
-
key_passphrase: Option<String>,
|
|
320
|
-
use_agent: bool,
|
|
321
|
-
strict_host_key: bool,
|
|
449
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
322
450
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
323
|
-
let conn = conn
|
|
324
|
-
host,
|
|
325
|
-
port,
|
|
326
|
-
user,
|
|
327
|
-
password,
|
|
328
|
-
key_path,
|
|
329
|
-
key_passphrase,
|
|
330
|
-
use_agent,
|
|
331
|
-
strict_host_key
|
|
332
|
-
);
|
|
451
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
333
452
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
334
453
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
335
454
|
let data = session.sftp.read(&path).await.map_err(err)?;
|
|
@@ -339,31 +458,15 @@ pub fn ssh_read<'py>(
|
|
|
339
458
|
|
|
340
459
|
/// Read a byte range [start, end] (inclusive). Returns bytes (short at EOF).
|
|
341
460
|
#[pyfunction]
|
|
342
|
-
#[
|
|
461
|
+
#[pyo3(signature = (path, start, end, **conn))]
|
|
343
462
|
pub fn ssh_read_range<'py>(
|
|
344
463
|
py: Python<'py>,
|
|
345
464
|
path: String,
|
|
346
465
|
start: u64,
|
|
347
466
|
end: u64,
|
|
348
|
-
|
|
349
|
-
port: u16,
|
|
350
|
-
user: String,
|
|
351
|
-
password: Option<String>,
|
|
352
|
-
key_path: Option<String>,
|
|
353
|
-
key_passphrase: Option<String>,
|
|
354
|
-
use_agent: bool,
|
|
355
|
-
strict_host_key: bool,
|
|
467
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
356
468
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
357
|
-
let conn = conn
|
|
358
|
-
host,
|
|
359
|
-
port,
|
|
360
|
-
user,
|
|
361
|
-
password,
|
|
362
|
-
key_path,
|
|
363
|
-
key_passphrase,
|
|
364
|
-
use_agent,
|
|
365
|
-
strict_host_key
|
|
366
|
-
);
|
|
469
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
367
470
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
368
471
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
369
472
|
let mut file = session.sftp.open(&path).await.map_err(err)?;
|
|
@@ -385,30 +488,14 @@ pub fn ssh_read_range<'py>(
|
|
|
385
488
|
|
|
386
489
|
/// Write bytes to a remote file (create + truncate). Returns the byte count.
|
|
387
490
|
#[pyfunction]
|
|
388
|
-
#[
|
|
491
|
+
#[pyo3(signature = (path, data, **conn))]
|
|
389
492
|
pub fn ssh_write<'py>(
|
|
390
493
|
py: Python<'py>,
|
|
391
494
|
path: String,
|
|
392
495
|
data: Vec<u8>,
|
|
393
|
-
|
|
394
|
-
port: u16,
|
|
395
|
-
user: String,
|
|
396
|
-
password: Option<String>,
|
|
397
|
-
key_path: Option<String>,
|
|
398
|
-
key_passphrase: Option<String>,
|
|
399
|
-
use_agent: bool,
|
|
400
|
-
strict_host_key: bool,
|
|
496
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
401
497
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
402
|
-
let conn = conn
|
|
403
|
-
host,
|
|
404
|
-
port,
|
|
405
|
-
user,
|
|
406
|
-
password,
|
|
407
|
-
key_path,
|
|
408
|
-
key_passphrase,
|
|
409
|
-
use_agent,
|
|
410
|
-
strict_host_key
|
|
411
|
-
);
|
|
498
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
412
499
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
413
500
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
414
501
|
let n = data.len();
|
|
@@ -430,31 +517,15 @@ pub fn ssh_write<'py>(
|
|
|
430
517
|
/// resets the file; later chunks open with APPEND so no offset tracking is
|
|
431
518
|
/// needed. Returns the byte count written.
|
|
432
519
|
#[pyfunction]
|
|
433
|
-
#[
|
|
520
|
+
#[pyo3(signature = (path, data, truncate, **conn))]
|
|
434
521
|
pub fn ssh_write_chunk<'py>(
|
|
435
522
|
py: Python<'py>,
|
|
436
523
|
path: String,
|
|
437
524
|
data: Vec<u8>,
|
|
438
525
|
truncate: bool,
|
|
439
|
-
|
|
440
|
-
port: u16,
|
|
441
|
-
user: String,
|
|
442
|
-
password: Option<String>,
|
|
443
|
-
key_path: Option<String>,
|
|
444
|
-
key_passphrase: Option<String>,
|
|
445
|
-
use_agent: bool,
|
|
446
|
-
strict_host_key: bool,
|
|
526
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
447
527
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
448
|
-
let conn = conn
|
|
449
|
-
host,
|
|
450
|
-
port,
|
|
451
|
-
user,
|
|
452
|
-
password,
|
|
453
|
-
key_path,
|
|
454
|
-
key_passphrase,
|
|
455
|
-
use_agent,
|
|
456
|
-
strict_host_key
|
|
457
|
-
);
|
|
528
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
458
529
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
459
530
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
460
531
|
let n = data.len();
|
|
@@ -476,29 +547,13 @@ pub fn ssh_write_chunk<'py>(
|
|
|
476
547
|
|
|
477
548
|
/// Check whether a remote path exists.
|
|
478
549
|
#[pyfunction]
|
|
479
|
-
#[
|
|
550
|
+
#[pyo3(signature = (path, **conn))]
|
|
480
551
|
pub fn ssh_exists<'py>(
|
|
481
552
|
py: Python<'py>,
|
|
482
553
|
path: String,
|
|
483
|
-
|
|
484
|
-
port: u16,
|
|
485
|
-
user: String,
|
|
486
|
-
password: Option<String>,
|
|
487
|
-
key_path: Option<String>,
|
|
488
|
-
key_passphrase: Option<String>,
|
|
489
|
-
use_agent: bool,
|
|
490
|
-
strict_host_key: bool,
|
|
554
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
491
555
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
492
|
-
let conn = conn
|
|
493
|
-
host,
|
|
494
|
-
port,
|
|
495
|
-
user,
|
|
496
|
-
password,
|
|
497
|
-
key_path,
|
|
498
|
-
key_passphrase,
|
|
499
|
-
use_agent,
|
|
500
|
-
strict_host_key
|
|
501
|
-
);
|
|
556
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
502
557
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
503
558
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
504
559
|
let exists = session.sftp.try_exists(&path).await.map_err(err)?;
|
|
@@ -509,29 +564,13 @@ pub fn ssh_exists<'py>(
|
|
|
509
564
|
/// Return (size, mtime, atime, uid, gid, permissions) for a remote path.
|
|
510
565
|
/// Fields are `None` when the server omits them — mirrors asyncssh SFTPAttrs.
|
|
511
566
|
#[pyfunction]
|
|
512
|
-
#[
|
|
567
|
+
#[pyo3(signature = (path, **conn))]
|
|
513
568
|
pub fn ssh_stat<'py>(
|
|
514
569
|
py: Python<'py>,
|
|
515
570
|
path: String,
|
|
516
|
-
|
|
517
|
-
port: u16,
|
|
518
|
-
user: String,
|
|
519
|
-
password: Option<String>,
|
|
520
|
-
key_path: Option<String>,
|
|
521
|
-
key_passphrase: Option<String>,
|
|
522
|
-
use_agent: bool,
|
|
523
|
-
strict_host_key: bool,
|
|
571
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
524
572
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
525
|
-
let conn = conn
|
|
526
|
-
host,
|
|
527
|
-
port,
|
|
528
|
-
user,
|
|
529
|
-
password,
|
|
530
|
-
key_path,
|
|
531
|
-
key_passphrase,
|
|
532
|
-
use_agent,
|
|
533
|
-
strict_host_key
|
|
534
|
-
);
|
|
573
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
535
574
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
536
575
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
537
576
|
let md = session.sftp.metadata(&path).await.map_err(err)?;
|
|
@@ -541,29 +580,13 @@ pub fn ssh_stat<'py>(
|
|
|
541
580
|
|
|
542
581
|
/// Like `ssh_stat` but does not follow symlinks (SFTP `lstat`).
|
|
543
582
|
#[pyfunction]
|
|
544
|
-
#[
|
|
583
|
+
#[pyo3(signature = (path, **conn))]
|
|
545
584
|
pub fn ssh_lstat<'py>(
|
|
546
585
|
py: Python<'py>,
|
|
547
586
|
path: String,
|
|
548
|
-
|
|
549
|
-
port: u16,
|
|
550
|
-
user: String,
|
|
551
|
-
password: Option<String>,
|
|
552
|
-
key_path: Option<String>,
|
|
553
|
-
key_passphrase: Option<String>,
|
|
554
|
-
use_agent: bool,
|
|
555
|
-
strict_host_key: bool,
|
|
587
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
556
588
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
557
|
-
let conn = conn
|
|
558
|
-
host,
|
|
559
|
-
port,
|
|
560
|
-
user,
|
|
561
|
-
password,
|
|
562
|
-
key_path,
|
|
563
|
-
key_passphrase,
|
|
564
|
-
use_agent,
|
|
565
|
-
strict_host_key
|
|
566
|
-
);
|
|
589
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
567
590
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
568
591
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
569
592
|
let md = session.sftp.symlink_metadata(&path).await.map_err(err)?;
|
|
@@ -574,6 +597,7 @@ pub fn ssh_lstat<'py>(
|
|
|
574
597
|
/// Set remote file metadata (SFTP `setstat`). Only the provided fields are
|
|
575
598
|
/// changed — covers chmod (permissions), chown (uid/gid) and utime (atime/mtime).
|
|
576
599
|
#[pyfunction]
|
|
600
|
+
#[pyo3(signature = (path, permissions, uid, gid, atime, mtime, **conn))]
|
|
577
601
|
#[allow(clippy::too_many_arguments)]
|
|
578
602
|
pub fn ssh_setstat<'py>(
|
|
579
603
|
py: Python<'py>,
|
|
@@ -583,25 +607,9 @@ pub fn ssh_setstat<'py>(
|
|
|
583
607
|
gid: Option<u32>,
|
|
584
608
|
atime: Option<u32>,
|
|
585
609
|
mtime: Option<u32>,
|
|
586
|
-
|
|
587
|
-
port: u16,
|
|
588
|
-
user: String,
|
|
589
|
-
password: Option<String>,
|
|
590
|
-
key_path: Option<String>,
|
|
591
|
-
key_passphrase: Option<String>,
|
|
592
|
-
use_agent: bool,
|
|
593
|
-
strict_host_key: bool,
|
|
610
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
594
611
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
595
|
-
let conn = conn
|
|
596
|
-
host,
|
|
597
|
-
port,
|
|
598
|
-
user,
|
|
599
|
-
password,
|
|
600
|
-
key_path,
|
|
601
|
-
key_passphrase,
|
|
602
|
-
use_agent,
|
|
603
|
-
strict_host_key
|
|
604
|
-
);
|
|
612
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
605
613
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
606
614
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
607
615
|
let attrs = FileAttributes {
|
|
@@ -621,29 +629,13 @@ pub fn ssh_setstat<'py>(
|
|
|
621
629
|
/// (name, size, mtime, atime, uid, gid, permissions) per entry — the same
|
|
622
630
|
/// attribute shape as `ssh_stat`, so children can cache them without a restat.
|
|
623
631
|
#[pyfunction]
|
|
624
|
-
#[
|
|
632
|
+
#[pyo3(signature = (path, **conn))]
|
|
625
633
|
pub fn ssh_list<'py>(
|
|
626
634
|
py: Python<'py>,
|
|
627
635
|
path: String,
|
|
628
|
-
|
|
629
|
-
port: u16,
|
|
630
|
-
user: String,
|
|
631
|
-
password: Option<String>,
|
|
632
|
-
key_path: Option<String>,
|
|
633
|
-
key_passphrase: Option<String>,
|
|
634
|
-
use_agent: bool,
|
|
635
|
-
strict_host_key: bool,
|
|
636
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
636
637
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
637
|
-
let conn = conn
|
|
638
|
-
host,
|
|
639
|
-
port,
|
|
640
|
-
user,
|
|
641
|
-
password,
|
|
642
|
-
key_path,
|
|
643
|
-
key_passphrase,
|
|
644
|
-
use_agent,
|
|
645
|
-
strict_host_key
|
|
646
|
-
);
|
|
638
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
647
639
|
type Entry = (
|
|
648
640
|
String,
|
|
649
641
|
Option<u64>,
|
|
@@ -676,30 +668,14 @@ pub fn ssh_list<'py>(
|
|
|
676
668
|
|
|
677
669
|
/// Create a remote directory (optionally creating parents).
|
|
678
670
|
#[pyfunction]
|
|
679
|
-
#[
|
|
671
|
+
#[pyo3(signature = (path, parents, **conn))]
|
|
680
672
|
pub fn ssh_mkdir<'py>(
|
|
681
673
|
py: Python<'py>,
|
|
682
674
|
path: String,
|
|
683
675
|
parents: bool,
|
|
684
|
-
|
|
685
|
-
port: u16,
|
|
686
|
-
user: String,
|
|
687
|
-
password: Option<String>,
|
|
688
|
-
key_path: Option<String>,
|
|
689
|
-
key_passphrase: Option<String>,
|
|
690
|
-
use_agent: bool,
|
|
691
|
-
strict_host_key: bool,
|
|
676
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
692
677
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
693
|
-
let conn = conn
|
|
694
|
-
host,
|
|
695
|
-
port,
|
|
696
|
-
user,
|
|
697
|
-
password,
|
|
698
|
-
key_path,
|
|
699
|
-
key_passphrase,
|
|
700
|
-
use_agent,
|
|
701
|
-
strict_host_key
|
|
702
|
-
);
|
|
678
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
703
679
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
704
680
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
705
681
|
if parents {
|
|
@@ -719,29 +695,13 @@ pub fn ssh_mkdir<'py>(
|
|
|
719
695
|
|
|
720
696
|
/// Remove an empty remote directory.
|
|
721
697
|
#[pyfunction]
|
|
722
|
-
#[
|
|
698
|
+
#[pyo3(signature = (path, **conn))]
|
|
723
699
|
pub fn ssh_rmdir<'py>(
|
|
724
700
|
py: Python<'py>,
|
|
725
701
|
path: String,
|
|
726
|
-
|
|
727
|
-
port: u16,
|
|
728
|
-
user: String,
|
|
729
|
-
password: Option<String>,
|
|
730
|
-
key_path: Option<String>,
|
|
731
|
-
key_passphrase: Option<String>,
|
|
732
|
-
use_agent: bool,
|
|
733
|
-
strict_host_key: bool,
|
|
702
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
734
703
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
735
|
-
let conn = conn
|
|
736
|
-
host,
|
|
737
|
-
port,
|
|
738
|
-
user,
|
|
739
|
-
password,
|
|
740
|
-
key_path,
|
|
741
|
-
key_passphrase,
|
|
742
|
-
use_agent,
|
|
743
|
-
strict_host_key
|
|
744
|
-
);
|
|
704
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
745
705
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
746
706
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
747
707
|
session.sftp.remove_dir(&path).await.map_err(err)?;
|
|
@@ -751,29 +711,13 @@ pub fn ssh_rmdir<'py>(
|
|
|
751
711
|
|
|
752
712
|
/// Remove a remote file.
|
|
753
713
|
#[pyfunction]
|
|
754
|
-
#[
|
|
714
|
+
#[pyo3(signature = (path, **conn))]
|
|
755
715
|
pub fn ssh_unlink<'py>(
|
|
756
716
|
py: Python<'py>,
|
|
757
717
|
path: String,
|
|
758
|
-
|
|
759
|
-
port: u16,
|
|
760
|
-
user: String,
|
|
761
|
-
password: Option<String>,
|
|
762
|
-
key_path: Option<String>,
|
|
763
|
-
key_passphrase: Option<String>,
|
|
764
|
-
use_agent: bool,
|
|
765
|
-
strict_host_key: bool,
|
|
718
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
766
719
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
767
|
-
let conn = conn
|
|
768
|
-
host,
|
|
769
|
-
port,
|
|
770
|
-
user,
|
|
771
|
-
password,
|
|
772
|
-
key_path,
|
|
773
|
-
key_passphrase,
|
|
774
|
-
use_agent,
|
|
775
|
-
strict_host_key
|
|
776
|
-
);
|
|
720
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
777
721
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
778
722
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
779
723
|
session.sftp.remove_file(&path).await.map_err(err)?;
|
|
@@ -783,30 +727,14 @@ pub fn ssh_unlink<'py>(
|
|
|
783
727
|
|
|
784
728
|
/// Rename a remote path.
|
|
785
729
|
#[pyfunction]
|
|
786
|
-
#[
|
|
730
|
+
#[pyo3(signature = (src, dst, **conn))]
|
|
787
731
|
pub fn ssh_rename<'py>(
|
|
788
732
|
py: Python<'py>,
|
|
789
733
|
src: String,
|
|
790
734
|
dst: String,
|
|
791
|
-
|
|
792
|
-
port: u16,
|
|
793
|
-
user: String,
|
|
794
|
-
password: Option<String>,
|
|
795
|
-
key_path: Option<String>,
|
|
796
|
-
key_passphrase: Option<String>,
|
|
797
|
-
use_agent: bool,
|
|
798
|
-
strict_host_key: bool,
|
|
735
|
+
conn: Option<&Bound<'py, PyDict>>,
|
|
799
736
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
800
|
-
let conn = conn
|
|
801
|
-
host,
|
|
802
|
-
port,
|
|
803
|
-
user,
|
|
804
|
-
password,
|
|
805
|
-
key_path,
|
|
806
|
-
key_passphrase,
|
|
807
|
-
use_agent,
|
|
808
|
-
strict_host_key
|
|
809
|
-
);
|
|
737
|
+
let conn = ConnParams::from_kwargs(conn)?;
|
|
810
738
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
811
739
|
let session = session_for(&conn).await.map_err(PyRuntimeError::new_err)?;
|
|
812
740
|
session.sftp.rename(&src, &dst).await.map_err(err)?;
|
|
@@ -819,10 +747,18 @@ pub fn ssh_rename<'py>(
|
|
|
819
747
|
/// (HostName, Port, User, first IdentityFile). Replaces the asyncssh config
|
|
820
748
|
/// parser so SSHPath needs no Python SSH library at runtime.
|
|
821
749
|
#[pyfunction]
|
|
750
|
+
#[allow(clippy::type_complexity)]
|
|
822
751
|
pub fn ssh_resolve_config(
|
|
823
752
|
host: String,
|
|
824
753
|
config_paths: Vec<String>,
|
|
825
|
-
) -> PyResult<(
|
|
754
|
+
) -> PyResult<(
|
|
755
|
+
Option<String>,
|
|
756
|
+
Option<u16>,
|
|
757
|
+
Option<String>,
|
|
758
|
+
Option<String>,
|
|
759
|
+
Option<String>,
|
|
760
|
+
Option<String>,
|
|
761
|
+
)> {
|
|
826
762
|
let mut combined = String::new();
|
|
827
763
|
for path in &config_paths {
|
|
828
764
|
if let Ok(content) = std::fs::read_to_string(path) {
|
|
@@ -831,7 +767,7 @@ pub fn ssh_resolve_config(
|
|
|
831
767
|
}
|
|
832
768
|
}
|
|
833
769
|
if combined.trim().is_empty() {
|
|
834
|
-
return Ok((None, None, None, None));
|
|
770
|
+
return Ok((None, None, None, None, None, None));
|
|
835
771
|
}
|
|
836
772
|
let mut reader = std::io::BufReader::new(std::io::Cursor::new(combined.into_bytes()));
|
|
837
773
|
let config = SshConfig::default()
|
|
@@ -842,5 +778,71 @@ pub fn ssh_resolve_config(
|
|
|
842
778
|
.identity_file
|
|
843
779
|
.and_then(|files| files.into_iter().next())
|
|
844
780
|
.map(|p| p.to_string_lossy().into_owned());
|
|
845
|
-
|
|
781
|
+
let first = |field: &str| {
|
|
782
|
+
params
|
|
783
|
+
.unsupported_fields
|
|
784
|
+
.get(field)
|
|
785
|
+
.and_then(|args| args.first())
|
|
786
|
+
.cloned()
|
|
787
|
+
};
|
|
788
|
+
Ok((
|
|
789
|
+
params.host_name,
|
|
790
|
+
params.port,
|
|
791
|
+
params.user,
|
|
792
|
+
identity,
|
|
793
|
+
first("stricthostkeychecking"),
|
|
794
|
+
first("userknownhostsfile"),
|
|
795
|
+
))
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/// True when `known_hosts` records any key for `host:port`.
|
|
799
|
+
#[pyfunction]
|
|
800
|
+
pub fn ssh_known_host(host: String, port: u16, known_hosts: String) -> PyResult<bool> {
|
|
801
|
+
known_host_keys_path(&host, port, &known_hosts)
|
|
802
|
+
.map(|keys| !keys.is_empty())
|
|
803
|
+
.map_err(err)
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/// Connect without authenticating and return the server's host key as
|
|
807
|
+
/// `(description, openssh_public_key)` for an interactive trust prompt.
|
|
808
|
+
#[pyfunction]
|
|
809
|
+
pub fn ssh_scan_host_key(py: Python<'_>, host: String, port: u16) -> PyResult<Bound<'_, PyAny>> {
|
|
810
|
+
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
811
|
+
let seen = Arc::new(Mutex::new(None));
|
|
812
|
+
let handler = Handler {
|
|
813
|
+
host: host.clone(),
|
|
814
|
+
port,
|
|
815
|
+
policy: HostKeyPolicy::Disabled,
|
|
816
|
+
known_hosts: String::new(),
|
|
817
|
+
rejected: Arc::new(Mutex::new(None)),
|
|
818
|
+
seen: seen.clone(),
|
|
819
|
+
key_changed: Default::default(),
|
|
820
|
+
};
|
|
821
|
+
let config = Arc::new(client::Config::default());
|
|
822
|
+
let connected = client::connect(config, (host.as_str(), port), handler).await;
|
|
823
|
+
drop(connected);
|
|
824
|
+
let key =
|
|
825
|
+
seen.lock().unwrap().take().ok_or_else(|| {
|
|
826
|
+
PyRuntimeError::new_err(format!("ssh {host}:{port}: no host key"))
|
|
827
|
+
})?;
|
|
828
|
+
let openssh = key.to_openssh().map_err(err)?;
|
|
829
|
+
Ok((describe_key(&key), openssh))
|
|
830
|
+
})
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/// Append `host:port`'s key (OpenSSH public-key format) to `known_hosts`.
|
|
834
|
+
#[pyfunction]
|
|
835
|
+
pub fn ssh_learn_host_key(
|
|
836
|
+
host: String,
|
|
837
|
+
port: u16,
|
|
838
|
+
public_key: String,
|
|
839
|
+
known_hosts: String,
|
|
840
|
+
) -> PyResult<()> {
|
|
841
|
+
if !is_plain_host(&host) {
|
|
842
|
+
return Err(PyRuntimeError::new_err(format!(
|
|
843
|
+
"refusing to record a host key for {host:?}: not a plain host name"
|
|
844
|
+
)));
|
|
845
|
+
}
|
|
846
|
+
let key = PublicKey::from_openssh(&public_key).map_err(err)?;
|
|
847
|
+
learn_known_hosts_path(&host, port, &key, &known_hosts).map_err(err)
|
|
846
848
|
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|