Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions metrics-plugin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }
anyhow = { version = "1" }
tracing = { version = "0.1" }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Comment thread
Nazarevsky marked this conversation as resolved.
Resolved
45 changes: 40 additions & 5 deletions metrics-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,30 @@ Core Lightning plugin that exposes node liquidity metrics via a Prometheus `/met

## Configuration

Both options are set as CLN plugin options (e.g. in `config` or passed via `--plugin`):
These are set as CLN plugin options (e.g. in `config` or passed via `--plugin`):

| Option | Required | Default | Description |
|---------------------|----------|---------|------------------------------------------------------------------------|
| `--metrics-addr` | yes | - | Address and port to expose `/metrics` on (e.g. `127.0.0.1:9750`) |
| `--metrics-refresh` | no | `30` | How often (seconds) to refresh node data for gauge metrics. Minimum 5. |
| Option | Required | Default | Description |
|---------------------------|---------------------------------------------------|---------|--------------------------------------------------------------------------------|
| `--metrics-addr` | yes | - | Address and port to expose `/metrics` on (e.g. `127.0.0.1:9750`) |
| `--metrics-refresh` | no | `30` | How often (seconds) to refresh node data for gauge metrics. Minimum 5. |
| `--metrics-disable-auth` | no | `false` | Serve `/metrics` without authentication. **Insecure** - local/dev use only. |

The bearer token required to access `/metrics` is read from the `METRICS_TOKEN` environment
variable (not a plugin option), so it can be injected the way your deployment already manages
secrets - a Kubernetes `secretKeyRef`, a systemd `EnvironmentFile`, a Docker secret, etc. - rather
than requiring a file on disk.

The plugin refuses to start unless either `METRICS_TOKEN` or `--metrics-disable-auth` is set, so a
deployment can't accidentally expose `/metrics` without making an explicit choice. When
`--metrics-disable-auth` is used, the plugin logs a warning on startup.

The plugin rejects tokens shorter than 16 characters at startup (and an empty value), to catch
weak or placeholder values before `/metrics` is ever exposed. Generate a long, random token rather
than a memorable password, e.g.:

```
export METRICS_TOKEN=$(openssl rand -hex 32)
```

Example CLN config:

Expand All @@ -21,6 +39,23 @@ metrics-addr=127.0.0.1:9750
metrics-refresh=15
```

Scrape it with:

```
curl -H "Authorization: Bearer $METRICS_TOKEN" http://127.0.0.1:9750/metrics
```

Prometheus scrape config equivalent:

```yaml
scrape_configs:
- job_name: cln-metrics
authorization:
credentials: "<METRICS_TOKEN value>"
static_configs:
- targets: ["127.0.0.1:9750"]
```

---

## Metrics
Expand Down
108 changes: 94 additions & 14 deletions metrics-plugin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ mod events;
mod metrics;

use anyhow::Result;
use cln_plugin::{Builder, Plugin, options::ConfigOption};
use cln_plugin::{
Builder, Plugin,
options::{
ConfigOption, DefaultBooleanConfigOption, DefaultIntegerConfigOption, StringConfigOption,
},
};
use cln_rpc::ClnRpc;
use cln_rpc::model::requests::GetinfoRequest;
use serde_json::Value;
Expand All @@ -15,26 +20,32 @@ use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tokio::net::TcpListener;
use tracing::{error, info};
use tracing::{error, info, warn};

use crate::cache::CachedData;
use crate::metrics::RefreshHealth;
use crate::metrics::{DerivedCollector, EventCounters};

const DEFAULT_REFRESH_SECS: u64 = 30;

const OPT_METRICS_ADDR: ConfigOption<'static, cln_plugin::options::config_type::String> =
ConfigOption::new_str_no_default(
"metrics-addr",
"Address and port to expose the Prometheus /metrics endpoint on",
);
const OPT_METRICS_ADDR: StringConfigOption = ConfigOption::new_str_no_default(
"metrics-addr",
"Address and port to expose the Prometheus /metrics endpoint on",
);

const OPT_REFRESH_SECS: ConfigOption<'static, cln_plugin::options::config_type::DefaultInteger> =
ConfigOption::new_i64_with_default(
"metrics-refresh",
DEFAULT_REFRESH_SECS as i64,
"How often (seconds) to refresh CLN node data for gauge metrics",
);
const OPT_REFRESH_SECS: DefaultIntegerConfigOption = ConfigOption::new_i64_with_default(
"metrics-refresh",
DEFAULT_REFRESH_SECS as i64,
"How often (seconds) to refresh CLN node data for gauge metrics",
);

const METRICS_TOKEN_ENV: &str = "METRICS_TOKEN";

const OPT_METRICS_DISABLE_AUTH: DefaultBooleanConfigOption = ConfigOption::new_bool_with_default(
"metrics-disable-auth",
false,
"Serve /metrics without authentication (INSECURE - local/dev use only)",
);

/// Shared plugin state - event counters and a read-cache of the last CLN poll.
/// Event counters are mutated atomically from subscription/hook handlers; the cache
Expand All @@ -51,6 +62,7 @@ async fn main() -> Result<()> {
let configured = Builder::new(tokio::io::stdin(), tokio::io::stdout())
.option(OPT_METRICS_ADDR)
.option(OPT_REFRESH_SECS)
.option(OPT_METRICS_DISABLE_AUTH)
.subscribe("channel_opened", events::on_channel_opened)
.subscribe("forward_event", events::on_forward_event)
.subscribe("channel_state_changed", events::on_channel_state_changed)
Expand All @@ -74,6 +86,21 @@ async fn main() -> Result<()> {
.unwrap_or(DEFAULT_REFRESH_SECS as i64)
.max(5) as u64; // floor at 5s to avoid hammering CLN RPC

let metrics_token_env = std::env::var(METRICS_TOKEN_ENV).ok();
let disable_auth = configured.option(&OPT_METRICS_DISABLE_AUTH)?;
let auth_token: Option<String> = match (metrics_token_env, disable_auth) {
(Some(token), _) => Some(validate_token(&token)?),
(None, true) => {
warn!("metrics-disable-auth is set: /metrics is being served WITHOUT authentication");
None
}
(None, false) => {
return Err(anyhow::anyhow!(
"{METRICS_TOKEN_ENV} env var is required to protect /metrics; set --metrics-disable-auth to run without authentication"
));
}
};

let socket_path = PathBuf::from(configured.configuration().lightning_dir)
.join(configured.configuration().rpc_file.clone());

Expand All @@ -99,7 +126,7 @@ async fn main() -> Result<()> {
let listener = TcpListener::bind(addr).await?;
let plugin = configured.start(state).await?;

metrics::start_metrics_server(listener).await?;
metrics::start_metrics_server(listener, auth_token).await?;

spawn_refresh_loop(cache, socket_path, refresh_secs, health);

Expand Down Expand Up @@ -141,6 +168,29 @@ fn spawn_refresh_loop(
});
}

/// Tokens shorter than this are rejected at startup - long enough to rule out trivially
/// guessable values without dictating a specific format.
const MIN_TOKEN_LEN: usize = 16;

/// Validates the bearer token read from the `METRICS_TOKEN` env var, trimming surrounding
/// whitespace so a stray newline from how the var was set doesn't become part of the expected
/// token.
fn validate_token(raw: &str) -> Result<String> {
let token = raw.trim();

if token.is_empty() {
return Err(anyhow::anyhow!("{METRICS_TOKEN_ENV} env var is empty"));
}

if token.len() < MIN_TOKEN_LEN {
return Err(anyhow::anyhow!(
"{METRICS_TOKEN_ENV} env var holds a token shorter than {MIN_TOKEN_LEN} characters; use a longer, random value"
));
}

Ok(token.to_string())
}

async fn rpc_status(plugin: Plugin<PluginState>, _args: Value) -> Result<Value, anyhow::Error> {
let cache = plugin.state().cache.read().expect("cache lock poisoned");
Ok(serde_json::json!({
Expand All @@ -149,3 +199,33 @@ async fn rpc_status(plugin: Plugin<PluginState>, _args: Value) -> Result<Value,
"blockheight": cache.node.blockheight,
}))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn trims_whitespace_and_trailing_newline() {
let token = validate_token(" a-long-enough-token\n").unwrap();
assert_eq!(&*token, "a-long-enough-token");
}

#[test]
fn rejects_empty_value() {
let err = validate_token(" \n").unwrap_err();
assert!(err.to_string().contains("is empty"));
}

#[test]
fn rejects_token_shorter_than_minimum() {
let err = validate_token("short\n").unwrap_err();
assert!(err.to_string().contains("shorter than"));
}

#[test]
fn accepts_token_at_exactly_the_minimum_length() {
let token = "a".repeat(MIN_TOKEN_LEN);
let read = validate_token(&token).unwrap();
assert_eq!(&*read, token.as_str());
}
}
116 changes: 113 additions & 3 deletions metrics-plugin/src/metrics.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::cache::CachedData;
use axum::{
Router,
http::StatusCode,
extract::{Request, State},
http::{StatusCode, header},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
};
Expand Down Expand Up @@ -521,12 +523,120 @@ async fn metrics_handler() -> Response {
.into_response()
}

pub async fn start_metrics_server(listener: TcpListener) -> anyhow::Result<()> {
let app = Router::new().route("/metrics", get(metrics_handler));
/// Constant-time comparison to avoid leaking the configured token via response-timing side
/// channels.
fn tokens_match(provided: &[u8], expected: &[u8]) -> bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we work with bytes? token is already stored as a string, so we can just compare strings

@Nazarevsky Nazarevsky Oct 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohhh, than question opens a pandora box that I'm really happy to share 😈

The thing is related to so-called remote timing attacks against string comparisons.

Let's consider a case where we compare strings rather than bytes. Rust comrpares string values character by character. This allows an attacker to brute-force a password based on response times. The guard checks the first character, then the second, then the third, and so on. As soon as it encounters an incorrect character, it immediately rejects the input and stops checking.

For example, a guess that matches the first five characters takes slightly longer to reject than one that only matches the first character, simply because the guard has to check more characters before giving up. This creates an opportunity to gradually figure out the correct sequence of characters.

In our case, the comparison function always takes a constant-time approach. It uses a combination of XOR and OR operations to check the result. Even if some characters are incorrect, it processes the entire provided string, making it much harder to determine whether a particular character is invalid based on execution time.

And yes, I know the probability of successfully exploiting this is relatively low, and we also have to account for external noise (e.g. network jitter). However, by performing thousands or even millions of requests and averaging the response times, the actual timing difference (caused by comparing one additional byte) can still emerge statistically.

if provided.len() != expected.len() {
return false;
}

provided
.iter()
.zip(expected.iter())
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
== 0
}

fn is_authorized(request: &Request, token: &str) -> bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, not sure, but usually i think it may be preferred to fix the token encoding, like URL-compatible Base64. I understand that you may want to leave the decision to the plugin user, but we should be sure that it cant be a potential attack vector

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The encoding choice itself isn't really an attack vector in my opninion - the comparison is already byte-equal and constant-time regardless of what characters are in the token. The HTTP layer (the axum header parser) already rejects control characters like newlines in header values before our code even sees them, so header injection via token should not be possible here

let Some(header) = request.headers().get(header::AUTHORIZATION) else {
return false;
};

let Ok(header) = header.to_str() else {
return false;
};

let Some(provided) = header.strip_prefix("Bearer ") else {
return false;
};

tokens_match(provided.as_bytes(), token.as_bytes())
}

async fn require_bearer_token(
State(token): State<String>,
request: Request,
next: Next,
) -> Response {
if is_authorized(&request, &token) {
return next.run(request).await;
}

(StatusCode::UNAUTHORIZED, "Unauthorized\n").into_response()
}

/// `auth_token` gates the `/metrics` route with bearer-token auth when set; `None` serves it
/// unauthenticated (only reachable via the explicit `metrics-disable-auth` opt-out).
pub async fn start_metrics_server(
listener: TcpListener,
auth_token: Option<String>,
) -> anyhow::Result<()> {
let mut app = Router::new().route("/metrics", get(metrics_handler));

if let Some(token) = auth_token {
app = app.route_layer(middleware::from_fn_with_state(token, require_bearer_token));
}

tokio::spawn(async move {
if let Err(e) = axum::serve(listener, app).await {
error!("metrics server error: {}", e);
}
});
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use tower::ServiceExt;

fn protected_app() -> Router {
Router::new()
.route("/metrics", get(metrics_handler))
.route_layer(middleware::from_fn_with_state(
"secret".to_string(),
require_bearer_token,
))
}

async fn get_metrics(app: Router, auth_header: Option<&str>) -> StatusCode {
let mut req = Request::builder().uri("/metrics");
if let Some(value) = auth_header {
req = req.header(header::AUTHORIZATION, value);
}
let response = app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
response.status()
}

#[tokio::test]
async fn rejects_missing_authorization_header() {
assert_eq!(
get_metrics(protected_app(), None).await,
StatusCode::UNAUTHORIZED
);
}

#[tokio::test]
async fn rejects_wrong_token() {
assert_eq!(
get_metrics(protected_app(), Some("Bearer wrong")).await,
StatusCode::UNAUTHORIZED
);
}

#[tokio::test]
async fn accepts_correct_token() {
assert_eq!(
get_metrics(protected_app(), Some("Bearer secret")).await,
StatusCode::OK
);
}

#[tokio::test]
async fn unprotected_app_serves_without_authorization() {
let app = Router::new().route("/metrics", get(metrics_handler));
assert_eq!(get_metrics(app, None).await, StatusCode::OK);
}
}
Loading