mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-29 07:34:13 +01:00
fix(network): recognize WebDAV NAS addresses behind tunnels
Recognize an advertised LAN origin only when the WebDAV response identifies the requested collection unambiguously. Keep browsing and playback on the saved connection so tunnel access and HTTPS trust continue to apply. Validation: 76 Flutter tests and 7 Rust parser tests passed. Dart analyzer, Clippy with warnings denied, formatter checks, and git diff --check passed. Includes HTTP and HTTPS transport fixtures and rejected ambiguous origins; the reporter's NAS still needs a retest.
This commit is contained in:
1 parent
d6daf4542e
commit
b2eaf5ed45
5 files changed
+228
-100
No files matched your search
@@ -1028,6 +1028,7 @@ class NetworkStorageService {
|
||||
if (baseSegments.isNotEmpty && baseSegments.last.isEmpty) {
|
||||
baseSegments.removeLast();
|
||||
}
|
||||
String? advertisedOrigin;
|
||||
final found = <String, NetworkEntry>{};
|
||||
void add(
|
||||
String href,
|
||||
@@ -1037,13 +1038,14 @@ class NetworkStorageService {
|
||||
String? etag,
|
||||
}) {
|
||||
final uri = base.resolve(href);
|
||||
// A DAV server behind a TLS proxy can advertise its HTTPS port even
|
||||
// when contacted over HTTP. Retain only the child path, never its
|
||||
// advertised origin: reads and writes still use the saved connection.
|
||||
// A DAV server can advertise its LAN address behind a tunnel. Accept
|
||||
// that origin only when it identifies the requested collection itself.
|
||||
// Reads and writes still use child paths on the saved connection.
|
||||
final sameServer =
|
||||
(uri.scheme == 'http' || uri.scheme == 'https') &&
|
||||
(uri.origin == base.origin ||
|
||||
(c.protocol == NetworkProtocol.webdav && uri.host == base.host));
|
||||
(c.protocol == NetworkProtocol.webdav &&
|
||||
(uri.host == base.host || uri.origin == advertisedOrigin)));
|
||||
if (!sameServer ||
|
||||
uri.hasQuery ||
|
||||
uri.hasFragment ||
|
||||
@@ -1090,23 +1092,53 @@ class NetworkStorageService {
|
||||
);
|
||||
}
|
||||
final successfulStatus = RegExp(r'^HTTP/\S+\s+200(?:\s|$)');
|
||||
for (final response in doc.descendants.whereType<XmlElement>().where(
|
||||
final responses = doc.descendants.whereType<XmlElement>().where(
|
||||
(e) => e.name.local == 'response',
|
||||
)) {
|
||||
);
|
||||
Iterable<XmlElement> properties(XmlElement response) =>
|
||||
response.descendants.whereType<XmlElement>().where(
|
||||
(e) =>
|
||||
e.name.local == 'propstat' &&
|
||||
e.childElements.any(
|
||||
(s) =>
|
||||
s.name.local == 'status' &&
|
||||
successfulStatus.hasMatch(s.innerText.trim()),
|
||||
),
|
||||
);
|
||||
final origins = <String>{};
|
||||
for (final response in responses) {
|
||||
final href = response.descendants
|
||||
.whereType<XmlElement>()
|
||||
.where((e) => e.name.local == 'href')
|
||||
.firstOrNull
|
||||
?.innerText;
|
||||
if (href == null) continue;
|
||||
final uri = base.resolve(href);
|
||||
if ((uri.scheme != 'http' && uri.scheme != 'https') ||
|
||||
uri.hasQuery ||
|
||||
uri.hasFragment ||
|
||||
uri.userInfo.isNotEmpty) {
|
||||
continue;
|
||||
}
|
||||
final segments = [...uri.pathSegments];
|
||||
if (segments.isNotEmpty && segments.last.isEmpty) segments.removeLast();
|
||||
if (listEquals(segments, baseSegments) &&
|
||||
properties(response).any(
|
||||
(prop) => prop.descendants.whereType<XmlElement>().any(
|
||||
(e) => e.name.local == 'collection',
|
||||
),
|
||||
)) {
|
||||
origins.add(uri.origin);
|
||||
}
|
||||
}
|
||||
if (origins.length == 1) advertisedOrigin = origins.single;
|
||||
for (final response in responses) {
|
||||
final elements = response.descendants.whereType<XmlElement>();
|
||||
final href = elements
|
||||
.where((e) => e.name.local == 'href')
|
||||
.firstOrNull
|
||||
?.innerText;
|
||||
final props = elements
|
||||
.where((e) => e.name.local == 'propstat')
|
||||
.where(
|
||||
(e) => e.childElements.any(
|
||||
(s) =>
|
||||
s.name.local == 'status' &&
|
||||
successfulStatus.hasMatch(s.innerText.trim()),
|
||||
),
|
||||
);
|
||||
final props = properties(response);
|
||||
final values = props.expand(
|
||||
(p) => p.descendants.whereType<XmlElement>(),
|
||||
);
|
||||
|
||||
@@ -25,6 +25,19 @@ pub(crate) fn execute(request: &Value, bytes: Option<&[u8]>) -> Result<Value, St
|
||||
}
|
||||
let base_segments = decoded_segments(&base)?;
|
||||
let webdav = request["protocol"] == "webdav";
|
||||
let document = if webdav {
|
||||
mornye_core::xml::check_depth(&body)?;
|
||||
let document = roxmltree::Document::parse(&body).map_err(|e| e.to_string())?;
|
||||
if !named(document.root_element(), "multistatus") {
|
||||
return Err("Server did not return a WebDAV directory listing".into());
|
||||
}
|
||||
Some(document)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let advertised_origin = document
|
||||
.as_ref()
|
||||
.and_then(|document| dav_collection_origin(document, &base, &base_segments));
|
||||
let mut entries = Vec::<Value>::new();
|
||||
let mut positions = HashMap::<String, usize>::new();
|
||||
let mut add = |href: &str,
|
||||
@@ -34,10 +47,13 @@ pub(crate) fn execute(request: &Value, bytes: Option<&[u8]>) -> Result<Value, St
|
||||
etag: Option<String>|
|
||||
-> Result<(), String> {
|
||||
let uri = base.join(&dart_href(href)).map_err(|e| e.to_string())?;
|
||||
// DAV hrefs can advertise the HTTPS listener of the same server.
|
||||
// A tunnel can expose a different host from the DAV collection href.
|
||||
// Only child paths leave this parser; transport keeps the saved origin.
|
||||
let same_server = uri.origin() == base.origin()
|
||||
|| (webdav && uri.host() == base.host() && matches!(uri.scheme(), "http" | "https"));
|
||||
|| (webdav
|
||||
&& matches!(uri.scheme(), "http" | "https")
|
||||
&& (uri.host() == base.host()
|
||||
|| advertised_origin.as_ref() == Some(&uri.origin())));
|
||||
if !same_server
|
||||
|| uri.query().is_some()
|
||||
|| uri.fragment().is_some()
|
||||
@@ -78,26 +94,13 @@ pub(crate) fn execute(request: &Value, bytes: Option<&[u8]>) -> Result<Value, St
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
if webdav {
|
||||
mornye_core::xml::check_depth(&body)?;
|
||||
let document = roxmltree::Document::parse(&body).map_err(|e| e.to_string())?;
|
||||
if !named(document.root_element(), "multistatus") {
|
||||
return Err("Server did not return a WebDAV directory listing".into());
|
||||
}
|
||||
if let Some(document) = document {
|
||||
for response in document
|
||||
.descendants()
|
||||
.filter(|node| named(*node, "response"))
|
||||
{
|
||||
let href = response.descendants().find(|node| named(*node, "href"));
|
||||
let props: Vec<_> = response
|
||||
.descendants()
|
||||
.filter(|node| {
|
||||
named(*node, "propstat")
|
||||
&& node.children().any(|child| {
|
||||
named(child, "status") && successful_status(&inner_text(child))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let props: Vec<_> = successful_properties(response).collect();
|
||||
if let Some(href) = href.filter(|_| !props.is_empty()) {
|
||||
let values: Vec<_> = props
|
||||
.iter()
|
||||
@@ -185,6 +188,54 @@ fn named(node: roxmltree::Node<'_, '_>, name: &str) -> bool {
|
||||
node.is_element() && node.tag_name().name() == name
|
||||
}
|
||||
|
||||
fn successful_properties<'a, 'input>(
|
||||
response: roxmltree::Node<'a, 'input>,
|
||||
) -> impl Iterator<Item = roxmltree::Node<'a, 'input>> {
|
||||
response.descendants().filter(|node| {
|
||||
named(*node, "propstat")
|
||||
&& node
|
||||
.children()
|
||||
.any(|child| named(child, "status") && successful_status(&inner_text(child)))
|
||||
})
|
||||
}
|
||||
|
||||
fn dav_collection_origin(
|
||||
document: &roxmltree::Document<'_>,
|
||||
base: &Url,
|
||||
base_segments: &[String],
|
||||
) -> Option<url::Origin> {
|
||||
let mut origin = None;
|
||||
for response in document
|
||||
.descendants()
|
||||
.filter(|node| named(*node, "response"))
|
||||
{
|
||||
let Some(href) = response.descendants().find(|node| named(*node, "href")) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(uri) = base.join(&dart_href(&inner_text(href))) else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(uri.scheme(), "http" | "https")
|
||||
|| uri.query().is_some()
|
||||
|| uri.fragment().is_some()
|
||||
|| !uri.username().is_empty()
|
||||
|| uri.password().is_some()
|
||||
|| decoded_segments(&uri).ok().as_deref() != Some(base_segments)
|
||||
|| !successful_properties(response)
|
||||
.flat_map(|prop| prop.descendants())
|
||||
.any(|node| named(node, "collection"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let next = uri.origin();
|
||||
if origin.as_ref().is_some_and(|origin| *origin != next) {
|
||||
return None;
|
||||
}
|
||||
origin = Some(next);
|
||||
}
|
||||
origin
|
||||
}
|
||||
|
||||
fn successful_status(value: &str) -> bool {
|
||||
let mut parts = value.split_whitespace();
|
||||
parts
|
||||
|
||||
+36
@@ -114,6 +114,42 @@
|
||||
"path": "",
|
||||
"body": "<d:multistatus xmlns:d='DAV:'/>",
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"protocol": "webdav",
|
||||
"address": "http://100.90.80.70:5005/dav/",
|
||||
"base_url": "http://100.90.80.70:5005/dav/Album/",
|
||||
"path": "Album/",
|
||||
"body": "<d:multistatus xmlns:d='DAV:'><d:response><d:href>http://192.168.1.20:5005/dav/Album/A%20B.flac</d:href><d:propstat><d:prop><d:getcontentlength>123</d:getcontentlength></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response><d:response><d:href>http://192.168.1.20:5005/dav/Album/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response><d:response><d:href>http://other.test/dav/Album/foreign.flac</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response><d:response><d:href>http://192.168.1.20:5005/outside/secret.flac</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>",
|
||||
"entries": [
|
||||
{"path": "Album/A B.flac", "name": "A B.flac", "directory": false, "size": 123}
|
||||
]
|
||||
},
|
||||
{
|
||||
"protocol": "webdav",
|
||||
"address": "https://nas.fixture.ts.net/dav/",
|
||||
"base_url": "https://nas.fixture.ts.net/dav/",
|
||||
"path": "",
|
||||
"body": "<d:multistatus xmlns:d='DAV:'><d:response><d:href>http://192.168.1.20:5005/dav/Album/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response><d:response><d:href>http://192.168.1.20:5005/dav/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>",
|
||||
"entries": [
|
||||
{"path": "Album/", "name": "Album", "directory": true, "size": null}
|
||||
]
|
||||
},
|
||||
{
|
||||
"protocol": "webdav",
|
||||
"address": "http://100.90.80.70:5005/dav/",
|
||||
"base_url": "http://100.90.80.70:5005/dav/",
|
||||
"path": "",
|
||||
"body": "<d:multistatus xmlns:d='DAV:'><d:response><d:href>http://192.168.1.20/dav/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response><d:response><d:href>http://other.test/dav/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response><d:response><d:href>http://192.168.1.20/dav/song.flac</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>",
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"protocol": "webdav",
|
||||
"address": "http://100.90.80.70:5005/dav/",
|
||||
"base_url": "http://100.90.80.70:5005/dav/",
|
||||
"path": "",
|
||||
"body": "<d:multistatus xmlns:d='DAV:'><d:response><d:href>http://192.168.1.20/dav/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat></d:response><d:response><d:href>http://192.168.1.20/dav/song.flac</d:href><d:propstat><d:prop/><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>",
|
||||
"entries": []
|
||||
}
|
||||
],
|
||||
"playlists": [
|
||||
|
||||
@@ -21,74 +21,80 @@ void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = null;
|
||||
|
||||
test(
|
||||
'HTTP WebDAV uses advertised HTTPS paths on the configured server',
|
||||
() async {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
final requests = <String>[];
|
||||
server.listen((request) async {
|
||||
expect(
|
||||
request.headers.value('authorization'),
|
||||
'Basic ${base64Encode(utf8.encode('test:secret'))}',
|
||||
);
|
||||
await request.drain<void>();
|
||||
requests.add('${request.method} ${request.uri}');
|
||||
if (request.method == 'PROPFIND') {
|
||||
request.response.statusCode = HttpStatus.multiStatus;
|
||||
final root = 'https://127.0.0.1:5006${request.uri.path}';
|
||||
request.response.write(
|
||||
_listing(
|
||||
request.uri.path == '/music/'
|
||||
? _entry('${root}Album/', directory: true)
|
||||
: _entry('${root}A%20B.flac'),
|
||||
),
|
||||
for (final advertised in [
|
||||
'https://127.0.0.1:5006',
|
||||
'http://192.168.1.20:5005',
|
||||
]) {
|
||||
test(
|
||||
'HTTP WebDAV retains its transport when the NAS advertises $advertised',
|
||||
() async {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
final requests = <String>[];
|
||||
server.listen((request) async {
|
||||
expect(
|
||||
request.headers.value('authorization'),
|
||||
'Basic ${base64Encode(utf8.encode('test:secret'))}',
|
||||
);
|
||||
} else {
|
||||
expect(request.uri.toString(), '/music/Album/A%20B.flac');
|
||||
expect(request.headers.value('range'), 'bytes=1-2');
|
||||
request.response.statusCode = HttpStatus.partialContent;
|
||||
request.response.headers.set('content-range', 'bytes 1-2/4');
|
||||
request.response.contentLength = 2;
|
||||
request.response.add([1, 2]);
|
||||
}
|
||||
await request.response.close();
|
||||
});
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
final connection = NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'NAS',
|
||||
protocol: NetworkProtocol.webdav,
|
||||
address: 'http://127.0.0.1:${server.port}/music/',
|
||||
username: 'test',
|
||||
password: 'secret',
|
||||
);
|
||||
await storage.save(connection);
|
||||
final albums = await storage.list(connection);
|
||||
expect(albums.single.path, 'Album/');
|
||||
final tracks = await storage.list(connection, albums.single.path);
|
||||
expect(tracks.single.path, 'Album/A B.flac');
|
||||
final location = await storage.resolve(
|
||||
NetworkStorageService.source(connection.id, tracks.single.path),
|
||||
);
|
||||
final client = HttpClient();
|
||||
addTearDown(() => client.close(force: true));
|
||||
final request = await client.getUrl(Uri.parse(location));
|
||||
request.headers.set('range', 'bytes=1-2');
|
||||
final response = await request.close();
|
||||
expect(response.statusCode, HttpStatus.partialContent);
|
||||
expect(await response.expand((chunk) => chunk).toList(), [1, 2]);
|
||||
expect(requests, [
|
||||
'PROPFIND /music/',
|
||||
'PROPFIND /music/Album/',
|
||||
'GET /music/Album/A%20B.flac',
|
||||
]);
|
||||
},
|
||||
);
|
||||
await request.drain<void>();
|
||||
requests.add('${request.method} ${request.uri}');
|
||||
if (request.method == 'PROPFIND') {
|
||||
request.response.statusCode = HttpStatus.multiStatus;
|
||||
final root = '$advertised${request.uri.path}';
|
||||
request.response.write(
|
||||
_listing(
|
||||
(request.uri.path == '/music/'
|
||||
? _entry('${root}Album/', directory: true)
|
||||
: _entry('${root}A%20B.flac')) +
|
||||
_entry(root, directory: true),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
expect(request.uri.toString(), '/music/Album/A%20B.flac');
|
||||
expect(request.headers.value('range'), 'bytes=1-2');
|
||||
request.response.statusCode = HttpStatus.partialContent;
|
||||
request.response.headers.set('content-range', 'bytes 1-2/4');
|
||||
request.response.contentLength = 2;
|
||||
request.response.add([1, 2]);
|
||||
}
|
||||
await request.response.close();
|
||||
});
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
final connection = NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'NAS',
|
||||
protocol: NetworkProtocol.webdav,
|
||||
address: 'http://127.0.0.1:${server.port}/music/',
|
||||
username: 'test',
|
||||
password: 'secret',
|
||||
);
|
||||
await storage.save(connection);
|
||||
final albums = await storage.list(connection);
|
||||
expect(albums.single.path, 'Album/');
|
||||
final tracks = await storage.list(connection, albums.single.path);
|
||||
expect(tracks.single.path, 'Album/A B.flac');
|
||||
final location = await storage.resolve(
|
||||
NetworkStorageService.source(connection.id, tracks.single.path),
|
||||
);
|
||||
final client = HttpClient();
|
||||
addTearDown(() => client.close(force: true));
|
||||
final request = await client.getUrl(Uri.parse(location));
|
||||
request.headers.set('range', 'bytes=1-2');
|
||||
final response = await request.close();
|
||||
expect(response.statusCode, HttpStatus.partialContent);
|
||||
expect(await response.expand((chunk) => chunk).toList(), [1, 2]);
|
||||
expect(requests, [
|
||||
'PROPFIND /music/',
|
||||
'PROPFIND /music/Album/',
|
||||
'GET /music/Album/A%20B.flac',
|
||||
]);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
'successful WebDAV property statuses do not require a reason phrase',
|
||||
|
||||
@@ -38,9 +38,12 @@ void main() {
|
||||
expect(await utf8.decoder.bind(request).join(), contains('propfind'));
|
||||
request.response.statusCode = 207;
|
||||
request.response.write('''<d:multistatus xmlns:d="DAV:">
|
||||
<d:response><d:href>http://127.0.0.1:5005/music/A%20B.flac</d:href><d:propstat>
|
||||
<d:response><d:href>http://192.168.1.20:5005/music/A%20B.flac</d:href><d:propstat>
|
||||
<d:prop><d:getcontentlength>4</d:getcontentlength></d:prop>
|
||||
<d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>
|
||||
<d:response><d:href>http://192.168.1.20:5005/music/</d:href><d:propstat>
|
||||
<d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop>
|
||||
<d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>
|
||||
</d:multistatus>''');
|
||||
} else {
|
||||
expect(request.headers.value('range'), 'bytes=1-2');
|
||||
|
||||
Reference in new issue
Block a user