| 10 |
10 |
|
//!
|
| 11 |
11 |
|
//! macOS deployment is an Aqua LaunchAgent (`LimitLoadToSessionType = Aqua`) so
|
| 12 |
12 |
|
//! build+sign run in the GUI security session where codesign can use the key.
|
|
13 |
+ |
//!
|
|
14 |
+ |
//! ## Trust boundary (read before touching `/run`)
|
|
15 |
+ |
//!
|
|
16 |
+ |
//! The capability model gates the *action label* (`build`/`sign`/…), not the
|
|
17 |
+ |
//! command bytes: a `Step` carries arbitrary `argv`/`shell_script` that the
|
|
18 |
+ |
//! agent runs verbatim once the label is permitted. An allow-listed caller is
|
|
19 |
+ |
//! therefore trusted to run **arbitrary code** on this host under any action it
|
|
20 |
+ |
//! is granted — the perimeter is the Tailscale `whois` allow-list plus the
|
|
21 |
+ |
//! tailnet-only bind (`ops-agent` refuses a non-tailnet `listen`), not the
|
|
22 |
+ |
//! capability token. Do not treat a narrow grant as a command sandbox. Every
|
|
23 |
+ |
//! request-facing route here (`/run`, `/pull`, `/health`) resolves identity and
|
|
24 |
+ |
//! authorizes before doing work — there is no unauthenticated surface.
|
| 13 |
25 |
|
|
| 14 |
26 |
|
use crate::capability::CapabilitySet;
|
| 15 |
27 |
|
use crate::executor::Executor;
|
| 16 |
28 |
|
use crate::remote::LogSink;
|
| 17 |
|
- |
use crate::step::Action;
|
|
29 |
+ |
use crate::step::{Action, ObserveKind};
|
| 18 |
30 |
|
use crate::transport::LocalExec;
|
| 19 |
31 |
|
use crate::wire::{Frame, HealthResponse, RunRequest};
|
| 20 |
32 |
|
use anyhow::{Context, Result};
|
| 21 |
33 |
|
use async_trait::async_trait;
|
| 22 |
34 |
|
use serde::Deserialize;
|
| 23 |
35 |
|
use std::net::{IpAddr, SocketAddr};
|
| 24 |
|
- |
use std::path::PathBuf;
|
|
36 |
+ |
use std::path::{Component, Path, PathBuf};
|
| 25 |
37 |
|
use std::sync::Arc;
|
| 26 |
38 |
|
|
| 27 |
39 |
|
/// The agent's local configuration (TOML).
|
| 37 |
49 |
|
/// implies. The effective grant is `caller.caps ∩ self.grant`.
|
| 38 |
50 |
|
#[serde(default)]
|
| 39 |
51 |
|
pub allow: Vec<CallerGrant>,
|
|
52 |
+ |
/// Root directory `/pull` may read from. Requests are confined under this
|
|
53 |
+ |
/// canonicalized path; `..` and symlinks that escape it are rejected.
|
|
54 |
+ |
/// `None` disables `/pull` entirely (it returns 403).
|
|
55 |
+ |
#[serde(default)]
|
|
56 |
+ |
pub pull_root: Option<PathBuf>,
|
| 40 |
57 |
|
}
|
| 41 |
58 |
|
|
| 42 |
59 |
|
/// Grant tokens as they appear in config: `actuate = [...]`, `observe = [...]`.
|
| 97 |
114 |
|
Denied,
|
| 98 |
115 |
|
}
|
| 99 |
116 |
|
|
|
117 |
+ |
/// The effective grant for a caller: `caller_grant ∩ agent_grant`, or `None` if
|
|
118 |
+ |
/// the caller is not in this agent's allow-list. The single source of truth for
|
|
119 |
+ |
/// what an authenticated caller may do — every route authorizes against it.
|
|
120 |
+ |
fn effective_grant(config: &AgentConfig, caller: &CallerIdentity) -> Option<CapabilitySet> {
|
|
121 |
+ |
config
|
|
122 |
+ |
.allow
|
|
123 |
+ |
.iter()
|
|
124 |
+ |
.find(|c| caller.matches(&c.identity))
|
|
125 |
+ |
.map(|entry| entry.to_caps().intersect(&config.grant.to_caps()))
|
|
126 |
+ |
}
|
|
127 |
+ |
|
| 100 |
128 |
|
/// Pure authorization core — no IO, fully unit-testable. The effective grant is
|
| 101 |
129 |
|
/// `caller_grant ∩ agent_grant`; the action must be permitted by it.
|
| 102 |
130 |
|
pub fn authorize(config: &AgentConfig, caller: &CallerIdentity, action: &Action) -> AuthDecision {
|
| 103 |
|
- |
let Some(entry) = config.allow.iter().find(|c| caller.matches(&c.identity)) else {
|
| 104 |
|
- |
return AuthDecision::UnknownCaller;
|
| 105 |
|
- |
};
|
| 106 |
|
- |
let effective = entry.to_caps().intersect(&config.grant.to_caps());
|
| 107 |
|
- |
if effective.permits(action) {
|
| 108 |
|
- |
AuthDecision::Allow
|
| 109 |
|
- |
} else {
|
| 110 |
|
- |
AuthDecision::Denied
|
|
131 |
+ |
match effective_grant(config, caller) {
|
|
132 |
+ |
None => AuthDecision::UnknownCaller,
|
|
133 |
+ |
Some(effective) if effective.permits(action) => AuthDecision::Allow,
|
|
134 |
+ |
Some(_) => AuthDecision::Denied,
|
| 111 |
135 |
|
}
|
| 112 |
136 |
|
}
|
| 113 |
137 |
|
|
| 188 |
212 |
|
|
| 189 |
213 |
|
/// Build the axum router. Serve it with
|
| 190 |
214 |
|
/// `.into_make_service_with_connect_info::<SocketAddr>()` so handlers see the
|
| 191 |
|
- |
/// peer address.
|
|
215 |
+ |
/// peer address. Every route resolves the caller's tailnet identity and
|
|
216 |
+ |
/// authorizes before doing work — there is no unauthenticated surface.
|
| 192 |
217 |
|
pub fn router(state: AgentState) -> axum::Router {
|
| 193 |
218 |
|
use axum::routing::{get, post};
|
| 194 |
219 |
|
axum::Router::new()
|
| 198 |
223 |
|
.with_state(state)
|
| 199 |
224 |
|
}
|
| 200 |
225 |
|
|
|
226 |
+ |
/// Resolve the caller's tailnet identity and effective grant, or an early
|
|
227 |
+ |
/// 403 response. The single gate every route passes through: a `whois` failure
|
|
228 |
+ |
/// or an unknown caller never reaches handler logic.
|
|
229 |
+ |
async fn resolve_caller(
|
|
230 |
+ |
state: &AgentState,
|
|
231 |
+ |
peer: IpAddr,
|
|
232 |
+ |
) -> Result<(CallerIdentity, CapabilitySet), axum::response::Response> {
|
|
233 |
+ |
use axum::http::StatusCode;
|
|
234 |
+ |
use axum::response::IntoResponse;
|
|
235 |
+ |
let identity = (state.whois)(peer)
|
|
236 |
+ |
.await
|
|
237 |
+ |
.map_err(|e| (StatusCode::FORBIDDEN, format!("whois failed: {e}")).into_response())?;
|
|
238 |
+ |
let effective = effective_grant(&state.config, &identity).ok_or_else(|| {
|
|
239 |
+ |
(StatusCode::FORBIDDEN, format!("unknown caller: {}", identity.node)).into_response()
|
|
240 |
+ |
})?;
|
|
241 |
+ |
Ok((identity, effective))
|
|
242 |
+ |
}
|
|
243 |
+ |
|
| 201 |
244 |
|
async fn health(
|
| 202 |
245 |
|
axum::extract::State(state): axum::extract::State<AgentState>,
|
| 203 |
|
- |
) -> axum::Json<HealthResponse> {
|
| 204 |
|
- |
let caps = state.config.grant.to_caps();
|
| 205 |
|
- |
axum::Json(HealthResponse {
|
| 206 |
|
- |
ok: true,
|
| 207 |
|
- |
actuate: caps.actuate_tokens().map(String::from).collect(),
|
| 208 |
|
- |
observe: caps.observe_kinds().map(|k| k.token()).collect(),
|
| 209 |
|
- |
})
|
|
246 |
+ |
axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo<SocketAddr>,
|
|
247 |
+ |
) -> axum::response::Response {
|
|
248 |
+ |
use axum::response::IntoResponse;
|
|
249 |
+ |
// Liveness is observable to any caller, but the grant detail (what this host
|
|
250 |
+ |
// can do) is only disclosed to an authenticated, allow-listed caller — an
|
|
251 |
+ |
// unknown peer learns the agent is up, nothing more.
|
|
252 |
+ |
let (actuate, observe) = match resolve_caller(&state, peer.ip()).await {
|
|
253 |
+ |
Ok((_, effective)) => (
|
|
254 |
+ |
effective.actuate_tokens().map(String::from).collect(),
|
|
255 |
+ |
effective.observe_kinds().map(|k| k.token()).collect(),
|
|
256 |
+ |
),
|
|
257 |
+ |
Err(_) => (Vec::new(), Vec::new()),
|
|
258 |
+ |
};
|
|
259 |
+ |
axum::Json(HealthResponse { ok: true, actuate, observe }).into_response()
|
| 210 |
260 |
|
}
|
| 211 |
261 |
|
|
| 212 |
262 |
|
async fn run(
|
| 217 |
267 |
|
use axum::http::StatusCode;
|
| 218 |
268 |
|
use axum::response::IntoResponse;
|
| 219 |
269 |
|
|
| 220 |
|
- |
// Identity → authorization (agent-side enforcement).
|
| 221 |
|
- |
let identity = match (state.whois)(peer.ip()).await {
|
| 222 |
|
- |
Ok(id) => id,
|
| 223 |
|
- |
Err(e) => {
|
| 224 |
|
- |
return (StatusCode::FORBIDDEN, format!("whois failed: {e}")).into_response();
|
| 225 |
|
- |
}
|
|
270 |
+ |
// Identity → authorization (agent-side enforcement). Note: this authorizes
|
|
271 |
+ |
// the action *label*; the step's argv runs verbatim once permitted (see the
|
|
272 |
+ |
// trust-boundary note at the top of this module).
|
|
273 |
+ |
let (identity, effective) = match resolve_caller(&state, peer.ip()).await {
|
|
274 |
+ |
Ok(pair) => pair,
|
|
275 |
+ |
Err(resp) => return resp,
|
| 226 |
276 |
|
};
|
| 227 |
|
- |
match authorize(&state.config, &identity, &req.step.action) {
|
| 228 |
|
- |
AuthDecision::Allow => {}
|
| 229 |
|
- |
AuthDecision::UnknownCaller => {
|
| 230 |
|
- |
return (StatusCode::FORBIDDEN, format!("unknown caller: {}", identity.node)).into_response();
|
| 231 |
|
- |
}
|
| 232 |
|
- |
AuthDecision::Denied => {
|
| 233 |
|
- |
return (
|
| 234 |
|
- |
StatusCode::FORBIDDEN,
|
| 235 |
|
- |
format!("action `{:?}` denied for {}", req.step.action, identity.node),
|
| 236 |
|
- |
)
|
| 237 |
|
- |
.into_response();
|
| 238 |
|
- |
}
|
|
277 |
+ |
if !effective.permits(&req.step.action) {
|
|
278 |
+ |
return (
|
|
279 |
+ |
StatusCode::FORBIDDEN,
|
|
280 |
+ |
format!("action `{:?}` denied for {}", req.step.action, identity.node),
|
|
281 |
+ |
)
|
|
282 |
+ |
.into_response();
|
| 239 |
283 |
|
}
|
| 240 |
284 |
|
|
| 241 |
285 |
|
// Run locally under the effective grant, streaming NDJSON frames back.
|
| 242 |
|
- |
let effective = state
|
| 243 |
|
- |
.config
|
| 244 |
|
- |
.allow
|
| 245 |
|
- |
.iter()
|
| 246 |
|
- |
.find(|c| identity.matches(&c.identity))
|
| 247 |
|
- |
.map(|c| c.to_caps().intersect(&state.config.grant.to_caps()))
|
| 248 |
|
- |
.unwrap_or_default();
|
| 249 |
|
- |
|
| 250 |
286 |
|
let (tx, rx) = tokio::sync::mpsc::channel::<Result<axum::body::Bytes, std::io::Error>>(64);
|
| 251 |
287 |
|
tokio::spawn(async move {
|
| 252 |
288 |
|
let exec = LocalExec::new(effective);
|
| 267 |
303 |
|
path: PathBuf,
|
| 268 |
304 |
|
}
|
| 269 |
305 |
|
|
|
306 |
+ |
/// Confine `requested` to `root`: both are canonicalized (resolving `..` and
|
|
307 |
+ |
/// symlinks), and the result must lie under `root`. Returns `None` on any
|
|
308 |
+ |
/// escape or if the path does not resolve (caller maps that to 403/404).
|
|
309 |
+ |
fn confine_to_root(root: &Path, requested: &Path) -> Option<PathBuf> {
|
|
310 |
+ |
// Reject obviously-hostile shapes before hitting the filesystem.
|
|
311 |
+ |
if requested.components().any(|c| matches!(c, Component::ParentDir)) {
|
|
312 |
+ |
return None;
|
|
313 |
+ |
}
|
|
314 |
+ |
let canon_root = root.canonicalize().ok()?;
|
|
315 |
+ |
let canon = requested.canonicalize().ok()?;
|
|
316 |
+ |
canon.starts_with(&canon_root).then_some(canon)
|
|
317 |
+ |
}
|
|
318 |
+ |
|
| 270 |
319 |
|
async fn pull(
|
| 271 |
|
- |
axum::extract::State(_state): axum::extract::State<AgentState>,
|
|
320 |
+ |
axum::extract::State(state): axum::extract::State<AgentState>,
|
|
321 |
+ |
axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo<SocketAddr>,
|
| 272 |
322 |
|
axum::extract::Query(q): axum::extract::Query<PullQuery>,
|
| 273 |
323 |
|
) -> axum::response::Response {
|
| 274 |
324 |
|
use axum::http::StatusCode;
|
| 275 |
325 |
|
use axum::response::IntoResponse;
|
| 276 |
|
- |
match tokio::fs::read(&q.path).await {
|
| 277 |
|
- |
Ok(bytes) => bytes.into_response(),
|
| 278 |
|
- |
Err(e) => (StatusCode::NOT_FOUND, format!("pull {}: {e}", q.path.display())).into_response(),
|
|
326 |
+ |
|
|
327 |
+ |
// Identity → authorization. Reading host files is an observe-plane action,
|
|
328 |
+ |
// gated by the `build-log` observe grant.
|
|
329 |
+ |
let (_identity, effective) = match resolve_caller(&state, peer.ip()).await {
|
|
330 |
+ |
Ok(pair) => pair,
|
|
331 |
+ |
Err(resp) => return resp,
|
|
332 |
+ |
};
|
|
333 |
+ |
if !effective.permits_observe(&ObserveKind::BuildLog) {
|
|
334 |
+ |
return (StatusCode::FORBIDDEN, "pull denied: requires `build-log` observe grant").into_response();
|
| 279 |
335 |
|
}
|
|
336 |
+ |
|
|
337 |
+ |
// Confine to the configured artifacts root. No root configured ⇒ disabled.
|
|
338 |
+ |
let Some(root) = &state.config.pull_root else {
|
|
339 |
+ |
return (StatusCode::FORBIDDEN, "pull disabled: no pull_root configured").into_response();
|
|
340 |
+ |
};
|
|
341 |
+ |
let Some(path) = confine_to_root(root, &q.path) else {
|
|
342 |
+ |
return (StatusCode::NOT_FOUND, format!("pull {}: not found under pull_root", q.path.display()))
|
|
343 |
+ |
.into_response();
|
|
344 |
+ |
};
|
|
345 |
+ |
|
|
346 |
+ |
// Stream the file in chunks rather than buffering it whole (artifacts can be
|
|
347 |
+ |
// hundreds of MB) — same channel/Body pattern as `/run`.
|
|
348 |
+ |
let file = match tokio::fs::File::open(&path).await {
|
|
349 |
+ |
Ok(f) => f,
|
|
350 |
+ |
Err(e) => return (StatusCode::NOT_FOUND, format!("pull {}: {e}", path.display())).into_response(),
|
|
351 |
+ |
};
|
|
352 |
+ |
let (tx, rx) = tokio::sync::mpsc::channel::<Result<axum::body::Bytes, std::io::Error>>(8);
|
|
353 |
+ |
tokio::spawn(async move {
|
|
354 |
+ |
use tokio::io::AsyncReadExt;
|
|
355 |
+ |
let mut file = file;
|
|
356 |
+ |
let mut buf = vec![0u8; 64 * 1024];
|
|
357 |
+ |
loop {
|
|
358 |
+ |
match file.read(&mut buf).await {
|
|
359 |
+ |
Ok(0) => break,
|
|
360 |
+ |
Ok(n) => {
|
|
361 |
+ |
if tx.send(Ok(axum::body::Bytes::copy_from_slice(&buf[..n]))).await.is_err() {
|
|
362 |
+ |
break;
|
|
363 |
+ |
}
|
|
364 |
+ |
}
|
|
365 |
+ |
Err(e) => {
|
|
366 |
+ |
let _ = tx.send(Err(e)).await;
|
|
367 |
+ |
break;
|
|
368 |
+ |
}
|
|
369 |
+ |
}
|
|
370 |
+ |
}
|
|
371 |
+ |
});
|
|
372 |
+ |
let stream = tokio_stream::wrappers::ReceiverStream::new(rx);
|
|
373 |
+ |
axum::body::Body::from_stream(stream).into_response()
|
| 280 |
374 |
|
}
|
| 281 |
375 |
|
|
| 282 |
376 |
|
#[cfg(test)]
|
| 294 |
388 |
|
allow: vec![CallerGrant {
|
| 295 |
389 |
|
identity: "fw13".into(),
|
| 296 |
390 |
|
actuate: vec!["build".into(), "sign".into(), "notarize".into(), "staple".into()],
|
| 297 |
|
- |
observe: vec![],
|
|
391 |
+ |
observe: vec!["build-log".into()],
|
| 298 |
392 |
|
}],
|
|
393 |
+ |
pull_root: None,
|
| 299 |
394 |
|
}
|
| 300 |
395 |
|
}
|
| 301 |
396 |
|
|
| 337 |
432 |
|
let tagged = CallerIdentity { node: "whatever".into(), tags: vec!["tag:builder".into()] };
|
| 338 |
433 |
|
assert_eq!(authorize(&c, &tagged, &Action::Sign), AuthDecision::Allow);
|
| 339 |
434 |
|
}
|
|
435 |
+ |
|
|
436 |
+ |
#[test]
|
|
437 |
+ |
fn pull_requires_a_known_caller_with_build_log_observe() {
|
|
438 |
+ |
// An unknown caller has no effective grant at all.
|
|
439 |
+ |
let stranger = CallerIdentity { node: "stranger".into(), tags: vec![] };
|
|
440 |
+ |
assert!(effective_grant(&cfg(), &stranger).is_none());
|
|
441 |
+ |
|
|
442 |
+ |
// A known caller granted only actuate (no build-log observe) cannot pull.
|
|
443 |
+ |
let mut c = cfg();
|
|
444 |
+ |
c.allow[0].observe = vec![];
|
|
445 |
+ |
c.grant.observe = vec![];
|
|
446 |
+ |
let eff = effective_grant(&c, &fw13()).unwrap();
|
|
447 |
+ |
assert!(!eff.permits_observe(&ObserveKind::BuildLog), "no observe grant ⇒ pull denied");
|
|
448 |
+ |
|
|
449 |
+ |
// The default fixture grants build-log on both sides ⇒ pull permitted.
|
|
450 |
+ |
let eff = effective_grant(&cfg(), &fw13()).unwrap();
|
|
451 |
+ |
assert!(eff.permits_observe(&ObserveKind::BuildLog));
|
|
452 |
+ |
}
|
|
453 |
+ |
|
|
454 |
+ |
#[test]
|
|
455 |
+ |
fn confine_rejects_traversal_and_escape() {
|
|
456 |
+ |
let dir = tempfile::tempdir().unwrap();
|
|
457 |
+ |
let root = dir.path().join("artifacts");
|
|
458 |
+ |
std::fs::create_dir_all(&root).unwrap();
|
|
459 |
+ |
std::fs::write(root.join("ok.bin"), b"x").unwrap();
|
|
460 |
+ |
// A secret one level above the root.
|
|
461 |
+ |
std::fs::write(dir.path().join("secret"), b"s").unwrap();
|
|
462 |
+ |
|
|
463 |
+ |
// In-root file resolves.
|
|
464 |
+ |
assert!(confine_to_root(&root, &root.join("ok.bin")).is_some());
|
|
465 |
+ |
// `..` escape is rejected.
|
|
466 |
+ |
assert!(confine_to_root(&root, &root.join("../secret")).is_none());
|
|
467 |
+ |
// Absolute path outside the root is rejected.
|
|
468 |
+ |
assert!(confine_to_root(&root, &dir.path().join("secret")).is_none());
|
|
469 |
+ |
// A non-existent in-root path does not resolve (caller maps to 404).
|
|
470 |
+ |
assert!(confine_to_root(&root, &root.join("missing")).is_none());
|
|
471 |
+ |
}
|
| 340 |
472 |
|
}
|