Skip to content

Commit eb0ffa4

Browse files
authored
Metrics get their own token (sc-8726): /internal/renderer/metrics takes METRICS_TOKEN (generated in the cluster, Secret visualci-metrics-token, on the web pods and the scraper only; optional elsewhere, so the worker and CronJobs start without it) and refuses the renderer token, so a renderer running an untrusted PDF can't read metrics and the scraper can't claim renders (#27)
1 parent e2ee3a5 commit eb0ffa4

7 files changed

Lines changed: 55 additions & 14 deletions

File tree

‎docs/deploy.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ web and worker tolerate `talira.ai/products=true:NoSchedule` and select `talira.
4141
| `JWT_SECRET` | random, generated in the cluster |
4242
| `HOST`, `PUBLIC_URL` | `https://visualci.com` |
4343
| `RENDERER_TOKEN` | random, generated in the cluster; the same value in the renderer's `VISUALCI_RENDERER_TOKEN` |
44+
| `METRICS_TOKEN` | random, generated in the cluster (Secret `visualci-metrics-token`); the web pods and the metrics scraper only, never the renderers. Optional elsewhere: without it, metrics refuse every request |
4445
| `S3_ENDPOINT` | `https://<account>.r2.cloudflarestorage.com` (DocSpring Products account) |
4546
| `S3_BUCKET` | `visualci` |
4647
| `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` | an R2 token scoped to that bucket |
@@ -102,7 +103,7 @@ The renderer takes `VISUALCI_API_URL=http://web.visualci.svc:5150` and `VISUALCI
102103
`/status` also catches a person left unchecked.
103104
- Image retention (`retention:prune`, a daily CronJob at 03:30 UTC) pushes its result to the internal Gatus endpoint
104105
"VisualCI / Image retention", which alerts on a failed run and on a day with none.
105-
- Render metrics: `/internal/renderer/metrics` (cluster-internal host, renderer token), Prometheus text, scraped by
106+
- Render metrics: `/internal/renderer/metrics` (cluster-internal host, `METRICS_TOKEN`; the renderer token is refused), Prometheus text, scraped by
106107
the PodMonitor visualci-renders. Each web pod reports the same database's numbers: aggregate with `max`, not `sum`.
107108
- What's deployed: `curl -s https://api.visualci.com/status` gives the server's `commit` (it also serves the app),
108109
and `curl -s https://visualci.com/version.txt` the static site's.

‎server/config/development.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ auth:
132132
settings:
133133
public_url: <%= get_env(name="PUBLIC_URL", default="http://localhost:5250") %>
134134
renderer_token: <%= get_env(name="RENDERER_TOKEN", default="dev-renderer-token") %>
135+
metrics_token: <%= get_env(name="METRICS_TOKEN", default="dev-metrics-token") %>
135136
renderer_version: <%= get_env(name="RENDERER_VERSION", default="dev") %>
136137
dev_login: true
137138
<% if get_env(name="VISUALCI_GITLAB_CLIENT_ID", default="") != "" %>

‎server/config/production.yaml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ settings:
131131
api_url: <%= get_env(name="API_URL", default="https://api.visualci.com") %>
132132
mcp_url: <%= get_env(name="MCP_URL", default="https://mcp.visualci.com") %>
133133
renderer_token: "<%= get_env(name="RENDERER_TOKEN") %>"
134+
# Only the web pods have it (the worker, migrations and CronJobs don't serve metrics): empty elsewhere.
135+
metrics_token: "<%= get_env(name="METRICS_TOKEN", default="") %>"
134136
# Baked into both images from docker/renderer.version, so the server and the renderers always agree.
135137
renderer_version: "<%= get_env(name="RENDERER_VERSION") %>"
136138
dev_login: false

‎server/config/test.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ settings:
117117
api_url: https://api.visualci.test
118118
mcp_url: https://mcp.visualci.test
119119
renderer_token: <%= get_env(name="RENDERER_TOKEN", default="dev-renderer-token") %>
120+
metrics_token: <%= get_env(name="METRICS_TOKEN", default="dev-metrics-token") %>
120121
renderer_version: <%= get_env(name="RENDERER_VERSION", default="dev") %>
121122
dev_login: true
122123
# The GitHub webhook tests sign deliveries with webhook_secret; nothing in the tests calls GitHub.

‎server/src/controllers/renderer.rs‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,48 @@ impl axum::extract::FromRequestParts<AppContext> for RendererAuth {
2222

2323
async fn from_request_parts(parts: &mut Parts, ctx: &AppContext) -> Result<Self> {
2424
let settings = Settings::from_context(ctx)?;
25-
let given = parts
26-
.headers
27-
.get(axum::http::header::AUTHORIZATION)
28-
.and_then(|v| v.to_str().ok())
29-
.and_then(|v| v.strip_prefix("Bearer "))
30-
.unwrap_or_default();
31-
let expected = settings.renderer_token.as_bytes();
32-
let ok = !expected.is_empty()
33-
&& given.len() == expected.len()
34-
&& given.bytes().zip(expected).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0;
35-
if ok { Ok(Self) } else { Err(Error::Unauthorized("invalid renderer token".into())) }
25+
if same_secret(bearer(parts), &settings.renderer_token) {
26+
Ok(Self)
27+
} else {
28+
Err(Error::Unauthorized("invalid renderer token".into()))
29+
}
30+
}
31+
}
32+
33+
/// The metrics scraper, with its own token: a renderer (which runs untrusted PDFs) can't read metrics, and the
34+
/// scraper can't claim renders.
35+
pub struct MetricsAuth;
36+
37+
impl axum::extract::FromRequestParts<AppContext> for MetricsAuth {
38+
type Rejection = Error;
39+
40+
async fn from_request_parts(parts: &mut Parts, ctx: &AppContext) -> Result<Self> {
41+
let settings = Settings::from_context(ctx)?;
42+
if same_secret(bearer(parts), &settings.metrics_token) {
43+
Ok(Self)
44+
} else {
45+
Err(Error::Unauthorized("invalid metrics token".into()))
46+
}
3647
}
3748
}
3849

50+
fn bearer(parts: &Parts) -> &str {
51+
parts
52+
.headers
53+
.get(axum::http::header::AUTHORIZATION)
54+
.and_then(|v| v.to_str().ok())
55+
.and_then(|v| v.strip_prefix("Bearer "))
56+
.unwrap_or_default()
57+
}
58+
59+
/// A constant-time comparison; an empty expected secret matches nothing.
60+
fn same_secret(given: &str, expected: &str) -> bool {
61+
let expected = expected.as_bytes();
62+
!expected.is_empty()
63+
&& given.len() == expected.len()
64+
&& given.bytes().zip(expected).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
65+
}
66+
3967
#[derive(Debug, Deserialize)]
4068
struct ClaimParams {
4169
/// The renderer image's version; only renders keyed to it are handed out.
@@ -177,7 +205,7 @@ async fn complete(
177205
/// Prometheus metrics for the renderers, from the last 24 hours of renders: seconds per page and queue wait
178206
/// (quantiles), renders finished by state, pages drawn, and what's queued or rendering now. For pricing and scaling.
179207
/// Scraped with the renderer token.
180-
async fn metrics(_auth: RendererAuth, State(ctx): State<AppContext>) -> Result<Response> {
208+
async fn metrics(_auth: MetricsAuth, State(ctx): State<AppContext>) -> Result<Response> {
181209
let row = ctx
182210
.db
183211
.query_one_raw(Statement::from_string(

‎server/src/settings.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ pub struct Settings {
1414
pub storage: StorageSettings,
1515
/// Shared secret the renderers authenticate with.
1616
pub renderer_token: String,
17+
/// The metrics scraper's own secret for `/internal/renderer/metrics`: the renderers never hold it, and the
18+
/// renderer token doesn't open metrics. Empty: metrics refuse everyone.
19+
#[serde(default)]
20+
pub metrics_token: String,
1721
/// 32 random bytes, base64 (`VISUALCI_SECRETS_KEY`): derives each project's GitLab webhook secret. Lives in
1822
/// 1Password and nowhere else, so a rebuilt cluster derives the same secrets.
1923
#[serde(default)]

‎server/tests/requests/render_metrics.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,12 @@ async fn renders_record_their_wait_and_duration_and_metrics_report_them() {
6767

6868
let unauthorized = request.get("/internal/renderer/metrics").await;
6969
assert_eq!(unauthorized.status_code(), 401);
70-
let response =
70+
// The renderers' token doesn't open metrics: a renderer runs untrusted PDFs (sc-8726).
71+
let renderer =
7172
request.get("/internal/renderer/metrics").add_header("authorization", "Bearer dev-renderer-token").await;
73+
assert_eq!(renderer.status_code(), 401);
74+
let response =
75+
request.get("/internal/renderer/metrics").add_header("authorization", "Bearer dev-metrics-token").await;
7276
assert_eq!(response.status_code(), 200, "{}", response.text());
7377
let text = response.text();
7478
assert!(text.contains("# TYPE visualci_render_page_seconds summary"), "{text}");

0 commit comments

Comments
 (0)