mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-28 04:49:57 +01:00
Merge commit from fork
* fix(share): always assign the authenticated user as share owner A share's UserID was taken from the request body and only defaulted when empty, so any authenticated user could create a share attributed to another user. For playlist shares the contents are resolved in the owner's library-access context, turning the spoofed owner into an access-escalation vector in multi-library setups. Force the owner from the request context at both the service boundary and the persistence layer, ignoring any client-supplied UserID. * fix(plugins): block SSRF to private IPs resolved from hostnames The HTTP host client only checked the literal host string, so a symbolic hostname (or a trailing-dot "localhost.") resolving to a private/loopback address bypassed the SSRF guard when a plugin declared no requiredHosts. Enforce the check at dial time via net.Dialer.Control on the resolved IP, which also covers redirect hops and DNS rebinding. When an explicit requiredHosts allowlist is set, defer to it as the operator's trust decision. * fix(plugins): gate private IPs on explicit IP/CIDR allowlist entries Following review feedback: an allowlisted hostname authorizes the external service, not whatever private IP it may resolve or rebind to. Enforce the resolved-IP guard even when requiredHosts is set, permitting a private address only when a literal IP or CIDR entry explicitly covers it. This keeps "reach this external API" and "reach my internal network" as two separate, explicit operator decisions. * fix(plugins): treat unspecified addresses as private in the SSRF guard Dialing 0.0.0.0 or :: reaches the local host, so they bypassed the private/loopback check. * fix(plugins): let a bare "*" allowlist reach private addresses Plugins such as AudioMuse-AI declare requiredHosts ["*"] to reach a user-configured service on the LAN, whose address the manifest cannot know. Requiring a literal IP/CIDR entry broke them. Named hosts and subdomain wildcards still cannot resolve to private addresses. * refactor(plugins): simplify the SSRF-guarded HTTP client and release its pool Build the client directly around the guarded transport instead of replacing a throwaway one, fail closed on an unparseable dial address, and close the per-plugin transport's idle connections when the plugin unloads. Trim stale comments. * fix(plugins): stop enabling extism's unguarded http_request host function Passing requiredHosts as the extism manifest's AllowedHosts enabled extism's own http_request (pdk.NewHTTPRequest), which only glob-matches the hostname and follows redirects without re-checking, bypassing the resolved-IP SSRF guard. Plugins must use host.HTTPSend. * fix(plugins): move bundled Rust examples to the host HTTP service Extism's built-in http_request is now disabled, so the webhook and Discord examples switch to nd_pdk::host::http::send. Update the README to say host.HTTPSend is the only supported way to make HTTP requests. * fix(plugins): move the Python example to the host HTTP service coverartarchive-py used extism's built-in Http.request, which is now disabled. Call Navidrome's http_send host function instead. The plugin can no longer run under the standalone extism CLI, so drop the CLI test targets and instructions.
This commit is contained in:
parent
4168377b65
commit
1a8463f7de
14 changed files with 238 additions and 81 deletions
|
|
@ -1,5 +1,5 @@
|
|||
# Build the Cover Art Archive Python plugin
|
||||
.PHONY: build test clean
|
||||
.PHONY: build clean
|
||||
|
||||
WASM_FILE = coverartarchive-py.wasm
|
||||
|
||||
|
|
@ -8,20 +8,5 @@ build: $(WASM_FILE)
|
|||
$(WASM_FILE): plugin/__init__.py
|
||||
extism-py plugin/__init__.py -o $(WASM_FILE)
|
||||
|
||||
test: build
|
||||
@echo "Testing nd_manifest..."
|
||||
extism call $(WASM_FILE) nd_manifest --wasi
|
||||
@echo ""
|
||||
@echo "Testing nd_get_album_images with Portishead's Dummy MBID..."
|
||||
extism call $(WASM_FILE) nd_get_album_images --wasi \
|
||||
--input '{"name":"Dummy","artist":"Portishead","mbid":"76df3287-6cda-33eb-8e9a-044b5e15ffdd"}' \
|
||||
--allow-host "coverartarchive.org" --allow-host "archive.org"
|
||||
|
||||
test-error: build
|
||||
@echo "Testing error case (missing MBID)..."
|
||||
-extism call $(WASM_FILE) nd_get_album_images --wasi \
|
||||
--input '{"name":"Test Album","artist":"Test Artist"}' \
|
||||
--allow-host "coverartarchive.org"
|
||||
|
||||
clean:
|
||||
rm -f $(WASM_FILE)
|
||||
|
|
|
|||
|
|
@ -51,14 +51,7 @@ zip -j coverartarchive-py.ndp manifest.json plugin.wasm
|
|||
|
||||
## Testing
|
||||
|
||||
Extract the wasm file and test:
|
||||
|
||||
```bash
|
||||
unzip -p coverartarchive-py.ndp plugin.wasm > coverartarchive-py.wasm
|
||||
extism call coverartarchive-py.wasm nd_get_album_images --wasi \
|
||||
--input '{"name":"Dummy","artist":"Portishead","mbid":"76df3287-6cda-33eb-8e9a-044b5e15ffdd"}' \
|
||||
--allow-host "coverartarchive.org" --allow-host "archive.org"
|
||||
```
|
||||
The plugin makes HTTP requests through Navidrome's `http_send` host function, so it only runs inside Navidrome (the `extism` CLI can't provide that function). Install the `.ndp` as described above, then open an album that has a MusicBrainz ID and check the Navidrome logs.
|
||||
|
||||
## How It Works
|
||||
|
||||
|
|
|
|||
|
|
@ -5,16 +5,25 @@
|
|||
#
|
||||
# Build with:
|
||||
# extism-py plugin/__init__.py -o coverartarchive-py.wasm
|
||||
#
|
||||
# Test with:
|
||||
# extism call coverartarchive-py.wasm nd_get_album_images --wasi \
|
||||
# --input '{"name":"Dummy","artist":"Portishead","mbid":"76df3287-6cda-33eb-8e9a-044b5e15ffdd"}' \
|
||||
# --allow-host "coverartarchive.org" --allow-host "archive.org"
|
||||
|
||||
import base64
|
||||
import extism
|
||||
import json
|
||||
|
||||
|
||||
@extism.import_fn("extism:host/user", "http_send")
|
||||
def http_send(req: dict) -> dict: ...
|
||||
|
||||
|
||||
def http_get(url):
|
||||
"""GET url via Navidrome's HTTP host service. Returns (status_code, body_bytes)."""
|
||||
resp = http_send({"request": {"method": "GET", "url": url}})
|
||||
if resp.get("error"):
|
||||
raise Exception(f"HTTP request failed: {resp['error']}")
|
||||
result = resp.get("result") or {}
|
||||
return result.get("statusCode", 0), base64.b64decode(result.get("body") or "")
|
||||
|
||||
|
||||
@extism.plugin_fn
|
||||
def nd_get_album_images():
|
||||
"""Retrieve album cover images from Cover Art Archive."""
|
||||
|
|
@ -26,13 +35,13 @@ def nd_get_album_images():
|
|||
|
||||
# Query Cover Art Archive API
|
||||
url = f"https://coverartarchive.org/release/{mbid}"
|
||||
response = extism.Http.request(url, meth="GET")
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"not found: CAA returned status {response.status_code}")
|
||||
|
||||
status, body = http_get(url)
|
||||
|
||||
if status != 200:
|
||||
raise Exception(f"not found: CAA returned status {status}")
|
||||
|
||||
try:
|
||||
data = json.loads(response.data_str())
|
||||
data = json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
raise Exception("not found: invalid JSON response")
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
//! presence updates, and heartbeat management.
|
||||
|
||||
use extism_pdk::*;
|
||||
use nd_pdk::host::{cache, scheduler, websocket};
|
||||
use nd_pdk::host::{cache, http, scheduler, websocket};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ============================================================================
|
||||
|
|
@ -359,19 +359,33 @@ fn find_username_for_connection(connection_id: &str) -> Result<Option<String>, E
|
|||
Ok(cache::get_string(&reverse_key)?.filter(|s| !s.is_empty()))
|
||||
}
|
||||
|
||||
fn get_discord_gateway() -> Result<String, Error> {
|
||||
let req = HttpRequest::new("https://discord.com/api/gateway")
|
||||
.with_method("GET");
|
||||
fn send_http(
|
||||
method: &str,
|
||||
url: &str,
|
||||
headers: std::collections::HashMap<String, String>,
|
||||
body: Vec<u8>,
|
||||
) -> Result<http::HTTPResponse, Error> {
|
||||
http::send(http::HTTPRequest {
|
||||
method: method.into(),
|
||||
url: url.into(),
|
||||
headers,
|
||||
no_follow_redirects: false,
|
||||
body,
|
||||
timeout_ms: 0,
|
||||
})?
|
||||
.ok_or_else(|| Error::msg("empty HTTP response"))
|
||||
}
|
||||
|
||||
let resp = http::request::<String>(&req, None::<String>)?;
|
||||
if resp.status_code() >= 400 {
|
||||
fn get_discord_gateway() -> Result<String, Error> {
|
||||
let resp = send_http("GET", "https://discord.com/api/gateway", Default::default(), Vec::new())?;
|
||||
if resp.status_code >= 400 {
|
||||
return Err(Error::msg(format!(
|
||||
"Failed to get Discord gateway: HTTP {}",
|
||||
resp.status_code()
|
||||
resp.status_code
|
||||
)));
|
||||
}
|
||||
|
||||
let body = resp.body();
|
||||
let body = resp.body;
|
||||
let data: std::collections::HashMap<String, String> = serde_json::from_slice(&body)
|
||||
.map_err(|e| Error::msg(format!("Failed to parse gateway response: {}", e)))?;
|
||||
|
||||
|
|
@ -487,23 +501,22 @@ fn process_image_inner(
|
|||
client_id
|
||||
);
|
||||
|
||||
let req = HttpRequest::new(&api_url)
|
||||
.with_method("POST")
|
||||
.with_header("Authorization", token)
|
||||
.with_header("Content-Type", "application/json");
|
||||
|
||||
let resp = http::request::<String>(&req, Some(body))?;
|
||||
if resp.status_code() >= 400 {
|
||||
let headers = std::collections::HashMap::from([
|
||||
("Authorization".to_string(), token.to_string()),
|
||||
("Content-Type".to_string(), "application/json".to_string()),
|
||||
]);
|
||||
let resp = send_http("POST", &api_url, headers, body.into_bytes())?;
|
||||
if resp.status_code >= 400 {
|
||||
if is_default {
|
||||
return Err(Error::msg(format!(
|
||||
"failed to process default image: HTTP {}",
|
||||
resp.status_code()
|
||||
resp.status_code
|
||||
)));
|
||||
}
|
||||
return process_image_inner(DEFAULT_IMAGE, client_id, token, true);
|
||||
}
|
||||
|
||||
let body = resp.body();
|
||||
let body = resp.body;
|
||||
let data: Vec<std::collections::HashMap<String, String>> = serde_json::from_slice(&body)
|
||||
.map_err(|e| Error::msg(format!("Failed to parse image response: {}", e)))?;
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@
|
|||
//! urls = "https://example.com/webhook1,https://example.com/webhook2"
|
||||
//! ```
|
||||
|
||||
use extism_pdk::{config, error, http, info, warn, HttpRequest};
|
||||
use extism_pdk::{config, error, info, warn};
|
||||
use nd_pdk::host::http::{self, HTTPRequest};
|
||||
use nd_pdk::scrobbler::{
|
||||
Error, IsAuthorizedRequest, NowPlayingRequest, PlaybackReportRequest, ScrobbleRequest,
|
||||
Scrobbler,
|
||||
|
|
@ -90,11 +91,18 @@ impl Scrobbler for WebhookPlugin {
|
|||
let full_url = format!("{}{}", url, query);
|
||||
info!("Sending webhook to: {}", full_url);
|
||||
|
||||
let http_req = HttpRequest::new(&full_url);
|
||||
match http::request::<()>(&http_req, None) {
|
||||
let http_req = HTTPRequest {
|
||||
method: "GET".into(),
|
||||
url: full_url,
|
||||
headers: Default::default(),
|
||||
no_follow_redirects: false,
|
||||
body: Vec::new(),
|
||||
timeout_ms: 0,
|
||||
};
|
||||
match http::send(http_req) {
|
||||
Ok(res) => {
|
||||
let status = res.status_code();
|
||||
if status >= 200 && status < 300 {
|
||||
let status = res.map_or(0, |r| r.status_code);
|
||||
if (200..300).contains(&status) {
|
||||
info!("Webhook succeeded: {} (status {})", url, status);
|
||||
} else {
|
||||
warn!("Webhook returned non-2xx status: {} (status {})", url, status);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue