Scope enrollment membership migration and use pull-only deployed gateway
This commit is contained in:
@@ -128,7 +128,10 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
|
||||
match std::env::var_os("RMM_AGENT_UPDATE_ARTIFACT_DIR") {
|
||||
Some(value) if FsPath::new(&value).is_absolute() => value.into(),
|
||||
Some(_) => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
|
||||
None => path.parent().ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?.join("agent-update-artifacts"),
|
||||
None => path
|
||||
.parent()
|
||||
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?
|
||||
.join("agent-update-artifacts"),
|
||||
},
|
||||
metadata.uid(),
|
||||
)?)
|
||||
@@ -168,7 +171,9 @@ pub fn verify_envelope(
|
||||
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
|
||||
) -> Result<ReleaseManifest, Error> {
|
||||
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform;
|
||||
if platform == Platform::WindowsGnuX64 && std::env::var("RMM_PROFILE").as_deref() != Ok("development") {
|
||||
if platform == Platform::WindowsGnuX64
|
||||
&& std::env::var("RMM_PROFILE").as_deref() != Ok("development")
|
||||
{
|
||||
return Err(fail("AGENT_UPDATE_DEVELOPMENT_CHANNEL_REQUIRED"));
|
||||
}
|
||||
let raw = keyring_bytes(platform)?;
|
||||
@@ -255,7 +260,10 @@ fn verify_envelope_with_keyring(
|
||||
}
|
||||
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route("/api/v1/tenants/{tenant}/enrollment-tokens", post(bootstrap::issue))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/enrollment-tokens",
|
||||
post(bootstrap::issue),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/agent-releases",
|
||||
get(list).post(import),
|
||||
@@ -267,13 +275,36 @@ pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
}
|
||||
pub fn gateway_routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route("/install/linux.sh", get(|| async { ([("content-type", "text/x-shellscript")], concat!(include_str!("bootstrap/install.sh"),include_str!("bootstrap/lifecycle.py"),"
|
||||
.route(
|
||||
"/install/linux.sh",
|
||||
get(|| async {
|
||||
(
|
||||
[("content-type", "text/x-shellscript")],
|
||||
concat!(
|
||||
include_str!("bootstrap/install.sh"),
|
||||
include_str!("bootstrap/lifecycle.py"),
|
||||
"
|
||||
RMM_BOOTSTRAP_PYTHON
|
||||
/usr/bin/python3 -I \"$file\" install \"$@\"
|
||||
")) }))
|
||||
.route("/install/windows.ps1", get(|| async { ([("content-type", "text/plain; charset=utf-8")], include_str!("bootstrap/install.ps1")) }))
|
||||
"
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/install/windows.ps1",
|
||||
get(|| async {
|
||||
(
|
||||
[("content-type", "text/plain; charset=utf-8")],
|
||||
include_str!("bootstrap/install.ps1"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route("/agent/v1/bootstrap/current", get(bootstrap::current))
|
||||
.route("/agent/v1/bootstrap/releases/{release}/artifacts/{artifact}", get(bootstrap::artifact))
|
||||
.route(
|
||||
"/agent/v1/bootstrap/releases/{release}/artifacts/{artifact}",
|
||||
get(bootstrap::artifact),
|
||||
)
|
||||
.route("/agent/v1/bootstrap/updater", get(bootstrap::updater))
|
||||
.route("/agent/v1/releases/current", get(current))
|
||||
.route("/agent/v1/releases/installed", get(installed))
|
||||
@@ -456,7 +487,7 @@ pub async fn import(
|
||||
return Err(fail("AGENT_UPDATE_RELEASE_CONFLICT"));
|
||||
}
|
||||
} else {
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'agent_update_release_imported',$4,now())").bind(t).bind(Uuid::new_v4()).bind(p.name)
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'agent_update_release_imported',$4,now())").bind(t).bind(Uuid::new_v4()).bind(p.name)
|
||||
.bind(json!({"release_id":m.release_id,"manifest_sha256":manifest_sha,"testsimulation":p.testsimulation})).execute(&mut *tx).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
@@ -537,15 +568,23 @@ async fn device(
|
||||
.await
|
||||
.map_err(|status| Error(status, "UNAUTHENTICATED"))
|
||||
}
|
||||
async fn installed(State(s): State<crate::State>, Extension(peer): Extension<crate::Peer>, headers: HeaderMap) -> Result<Response, Error> {
|
||||
async fn installed(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let row = sqlx::query("SELECT reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(([("cache-control","private, no-store")], Json(json!({"agent_id":agent,
|
||||
Ok((
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(json!({"agent_id":agent,
|
||||
"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
|
||||
"connection_generation":row.get::<i64,_>("connection_generation"),
|
||||
"last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")}))).into_response())
|
||||
"last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")})),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn check_device_platform(
|
||||
@@ -562,7 +601,9 @@ async fn check_device_platform(
|
||||
let caps: Vec<String> = serde_json::from_value(caps)?;
|
||||
let expected = match platform {
|
||||
Platform::LinuxX64 => "linux.base/1",
|
||||
Platform::WindowsX64 if caps.iter().any(|c| c == "agent.release.windows.gnu/1") => return Err(missing()),
|
||||
Platform::WindowsX64 if caps.iter().any(|c| c == "agent.release.windows.gnu/1") => {
|
||||
return Err(missing());
|
||||
}
|
||||
Platform::WindowsX64 => "windows.base/1",
|
||||
Platform::WindowsGnuX64 => "agent.release.windows.gnu/1",
|
||||
};
|
||||
@@ -585,8 +626,11 @@ async fn release_artifact(
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let (_, manifest) = checked_release(&mut tx, release).await?;
|
||||
check_device_platform(&mut tx, agent, manifest.platform).await?;
|
||||
let descriptor = manifest.artifacts.into_iter()
|
||||
.find(|entry| entry.artifact_id == artifact).ok_or_else(missing)?;
|
||||
let descriptor = manifest
|
||||
.artifacts
|
||||
.into_iter()
|
||||
.find(|entry| entry.artifact_id == artifact)
|
||||
.ok_or_else(missing)?;
|
||||
tx.commit().await?;
|
||||
verified_binary(tenant, descriptor.sha256, descriptor.bytes).await
|
||||
}
|
||||
@@ -608,12 +652,27 @@ async fn verified_binary(tenant: Uuid, sha256: String, size: u64) -> Result<Resp
|
||||
});
|
||||
let mut response = Response::new(Body::from_stream(stream));
|
||||
let headers = response.headers_mut();
|
||||
headers.insert("content-type", HeaderValue::from_static("application/octet-stream"));
|
||||
headers.insert(
|
||||
"content-type",
|
||||
HeaderValue::from_static("application/octet-stream"),
|
||||
);
|
||||
headers.insert("content-length", HeaderValue::from(size));
|
||||
headers.insert("content-disposition", HeaderValue::from_static("attachment"));
|
||||
headers.insert("x-content-type-options", HeaderValue::from_static("nosniff"));
|
||||
headers.insert("cache-control", HeaderValue::from_static("private, no-store"));
|
||||
headers.insert("x-artifact-sha256", HeaderValue::from_str(&sha256).map_err(|_| invalid())?);
|
||||
headers.insert(
|
||||
"content-disposition",
|
||||
HeaderValue::from_static("attachment"),
|
||||
);
|
||||
headers.insert(
|
||||
"x-content-type-options",
|
||||
HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
headers.insert(
|
||||
"cache-control",
|
||||
HeaderValue::from_static("private, no-store"),
|
||||
);
|
||||
headers.insert(
|
||||
"x-artifact-sha256",
|
||||
HeaderValue::from_str(&sha256).map_err(|_| invalid())?,
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
@@ -629,7 +688,12 @@ async fn current(
|
||||
let ids:Vec<Uuid>=sqlx::query_scalar("SELECT release_id FROM agent_update_releases WHERE platform=$1 ORDER BY release_sequence DESC LIMIT 1").bind(platform_name(q.platform)).fetch_all(&mut *tx).await?;
|
||||
let release = if let Some(id) = ids.first() {
|
||||
let (envelope, manifest) = checked_release(&mut tx, *id).await?;
|
||||
resolve_artifacts(&mut tx, tenant, &manifest.artifacts).await?;
|
||||
// Polling is frequent. The catalog binds immutable descriptors by FK.
|
||||
// Publication and actual downloads verify the full stream.
|
||||
let objects = store()?;
|
||||
for item in &manifest.artifacts {
|
||||
objects.available(tenant, &item.sha256, item.bytes)?;
|
||||
}
|
||||
Some(json!({"release_envelope":envelope,"manifest":manifest}))
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -18,10 +18,16 @@ fn config(platform: Platform) -> Result<Config, Error> {
|
||||
let path = std::env::var(slot).map_err(|_| fail("BOOTSTRAP_NOT_CONFIGURED"))?;
|
||||
let config: Config = serde_json::from_slice(&protected_file(FsPath::new(&path), 8192)?)?;
|
||||
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
|
||||
if url.scheme() != "https" || url.domain().is_none() || !url.username().is_empty()
|
||||
|| url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|
||||
|| url.path() != "/" || !rmm_domain::agent_update::digest(&config.updater_sha256)
|
||||
|| !(1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&config.updater_bytes) {
|
||||
if url.scheme() != "https"
|
||||
|| url.domain().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
|| url.path() != "/"
|
||||
|| !rmm_domain::agent_update::digest(&config.updater_sha256)
|
||||
|| !(1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&config.updater_bytes)
|
||||
{
|
||||
return Err(fail("BOOTSTRAP_CONFIGURATION_INVALID"));
|
||||
}
|
||||
Ok(config)
|
||||
@@ -29,36 +35,82 @@ fn config(platform: Platform) -> Result<Config, Error> {
|
||||
fn private_json(body: Value) -> Response {
|
||||
([("cache-control", "private, no-store")], Json(body)).into_response()
|
||||
}
|
||||
pub(super) async fn issue(State(s): State<crate::State>, headers: HeaderMap, Path(t): Path<Uuid>) -> Result<Response, Error> {
|
||||
let p = s.auth.principal(&s, &headers, true).await.map_err(|status| Error(status, crate::auth::error_code(status)))?;
|
||||
pub(super) async fn issue(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
) -> Result<Response, Error> {
|
||||
let p = s
|
||||
.auth
|
||||
.principal(&s, &headers, true)
|
||||
.await
|
||||
.map_err(|status| Error(status, crate::auth::error_code(status)))?;
|
||||
crate::jobs::scope(&p, t, true)?;
|
||||
if p.session_hash.is_none() { return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED")); }
|
||||
if p.session_hash.is_none() {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "devices:enroll").await?;
|
||||
let bootstrap_origin = std::env::var("RMM_BOOTSTRAP_ORIGIN").ok().map(|raw| {
|
||||
let url = url::Url::parse(&raw).map_err(|_| invalid())?;
|
||||
if url.scheme() != "https" || url.domain().is_none() || !url.username().is_empty() || url.password().is_some()
|
||||
|| url.path() != "/" || url.query().is_some() || url.fragment().is_some() { return Err(invalid()); }
|
||||
Ok(url.origin().ascii_serialization())
|
||||
}).transpose()?;
|
||||
let bootstrap_origin = std::env::var("RMM_BOOTSTRAP_ORIGIN")
|
||||
.ok()
|
||||
.map(|raw| {
|
||||
let url = url::Url::parse(&raw).map_err(|_| invalid())?;
|
||||
if url.scheme() != "https"
|
||||
|| url.domain().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.path() != "/"
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(url.origin().ascii_serialization())
|
||||
})
|
||||
.transpose()?;
|
||||
let mut bytes = [0; 32];
|
||||
openssl::rand::rand_bytes(&mut bytes).map_err(|_| fail("TOKEN_GENERATION_FAILED"))?;
|
||||
let token = hex::encode(bytes);
|
||||
let expires: chrono::DateTime<chrono::Utc> = sqlx::query_scalar("SELECT issue_enrollment_token($1)")
|
||||
.bind(hash(token.as_bytes())).fetch_one(&mut *tx).await?;
|
||||
let release_platforms: Vec<String> =
|
||||
sqlx::query_scalar("SELECT DISTINCT platform FROM agent_update_releases ORDER BY platform")
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let expires: chrono::DateTime<chrono::Utc> =
|
||||
sqlx::query_scalar("SELECT issue_enrollment_token($1)")
|
||||
.bind(hash(token.as_bytes()))
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'enrollment_token_issued',$4,now())")
|
||||
.bind(t).bind(Uuid::new_v4()).bind(p.name).bind(json!({"expires_at":expires})).execute(&mut *tx).await?;
|
||||
.bind(t)
|
||||
.bind(Uuid::new_v4())
|
||||
.bind(p.name)
|
||||
.bind(json!({"expires_at":expires}))
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"token":token,"expires_at":expires,"bootstrap_origin":bootstrap_origin})))
|
||||
Ok(private_json(
|
||||
json!({"token":token,"expires_at":expires,"bootstrap_origin":bootstrap_origin,"release_platforms":release_platforms}),
|
||||
))
|
||||
}
|
||||
async fn token_tenant(s: &crate::State, h: &HeaderMap) -> Result<Uuid, Error> {
|
||||
let denied = || Error(StatusCode::UNAUTHORIZED, "ENROLLMENT_TOKEN_REQUIRED");
|
||||
let token = h.get("authorization").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Enrollment ")).filter(|v| rmm_domain::agent_update::digest(v)).ok_or_else(denied)?;
|
||||
let token = h
|
||||
.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Enrollment "))
|
||||
.filter(|v| rmm_domain::agent_update::digest(v))
|
||||
.ok_or_else(denied)?;
|
||||
let t: Option<Uuid> = sqlx::query_scalar("SELECT bootstrap_enrollment_tenant($1)")
|
||||
.bind(hash(token.as_bytes())).fetch_one(&s.pool).await?;
|
||||
.bind(hash(token.as_bytes()))
|
||||
.fetch_one(&s.pool)
|
||||
.await?;
|
||||
t.ok_or_else(denied)
|
||||
}
|
||||
pub(super) async fn current(State(s): State<crate::State>, headers: HeaderMap, Query(q): Query<Current>) -> Result<Response, Error> {
|
||||
pub(super) async fn current(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<Current>,
|
||||
) -> Result<Response, Error> {
|
||||
let t = token_tenant(&s, &headers).await?;
|
||||
let c = config(q.platform)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
@@ -67,21 +119,44 @@ pub(super) async fn current(State(s): State<crate::State>, headers: HeaderMap, Q
|
||||
let (envelope, manifest) = checked_release(&mut tx, release).await?;
|
||||
tx.commit().await?;
|
||||
let ring: Value = serde_json::from_slice(&keyring_bytes(q.platform)?)?;
|
||||
let ca = s.signer.as_ref().ok_or_else(missing)?.ca.to_pem().map_err(|_| invalid())?;
|
||||
Ok(private_json(json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
|
||||
let ca = s
|
||||
.signer
|
||||
.as_ref()
|
||||
.ok_or_else(missing)?
|
||||
.ca
|
||||
.to_pem()
|
||||
.map_err(|_| invalid())?;
|
||||
Ok(private_json(
|
||||
json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
|
||||
"gateway_origin":c.gateway_origin,"ca_pem":String::from_utf8(ca).map_err(|_| invalid())?,
|
||||
"keyring":ring,"updater":{"sha256":c.updater_sha256,"bytes":c.updater_bytes}})))
|
||||
"keyring":ring,"updater":{"sha256":c.updater_sha256,"bytes":c.updater_bytes}}),
|
||||
))
|
||||
}
|
||||
pub(super) async fn artifact(State(s): State<crate::State>, headers: HeaderMap, Path((id, artifact)): Path<(Uuid,Uuid)>, Query(q): Query<Current>) -> Result<Response, Error> {
|
||||
pub(super) async fn artifact(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((id, artifact)): Path<(Uuid, Uuid)>,
|
||||
Query(q): Query<Current>,
|
||||
) -> Result<Response, Error> {
|
||||
let tenant = token_tenant(&s, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let (_, manifest) = checked_release(&mut tx, id).await?;
|
||||
if manifest.platform != q.platform { return Err(missing()); }
|
||||
let d = manifest.artifacts.into_iter().find(|v| v.artifact_id == artifact).ok_or_else(missing)?;
|
||||
if manifest.platform != q.platform {
|
||||
return Err(missing());
|
||||
}
|
||||
let d = manifest
|
||||
.artifacts
|
||||
.into_iter()
|
||||
.find(|v| v.artifact_id == artifact)
|
||||
.ok_or_else(missing)?;
|
||||
tx.commit().await?;
|
||||
verified_binary(tenant, d.sha256, d.bytes).await
|
||||
}
|
||||
pub(super) async fn updater(State(s): State<crate::State>, headers: HeaderMap, Query(q): Query<Current>) -> Result<Response, Error> {
|
||||
pub(super) async fn updater(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<Current>,
|
||||
) -> Result<Response, Error> {
|
||||
let tenant = token_tenant(&s, &headers).await?;
|
||||
let c = config(q.platform)?;
|
||||
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
|
||||
|
||||
@@ -179,8 +179,12 @@ async fn main() -> Result<()> {
|
||||
.route(
|
||||
"/agent/v1/artifacts/{artifact}",
|
||||
get(agent_artifacts::download),
|
||||
)
|
||||
.route("/agent/v1/connect", get(gateway::connect));
|
||||
);
|
||||
// The deployed gateway delivers work only in HTTP responses to the agent.
|
||||
// The combined local development fixture still exercises the historical wire codec.
|
||||
if dev && role.api() {
|
||||
routes = routes.route("/agent/v1/connect", get(gateway::connect));
|
||||
}
|
||||
if !role.api() {
|
||||
// Public gateway never accepts browser or automation credentials.
|
||||
routes = routes.route("/api/v1/job-signing-key", get(api::agent_job_signing_key));
|
||||
|
||||
@@ -98,14 +98,21 @@ impl UpdateArtifacts {
|
||||
hasher: Sha256::new(),
|
||||
})
|
||||
}
|
||||
pub(crate) fn verified_file(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<File> {
|
||||
fn open_object(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<(File, fs::Metadata)> {
|
||||
ensure!(descriptor(hash, bytes), "bounded update object descriptor");
|
||||
let parent = self.parent(tenant)?;
|
||||
let mut file = OpenOptions::new()
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||||
.open(parent.join(hash))?;
|
||||
let before = regular(&file, self.owner, bytes)?;
|
||||
let metadata = regular(&file, self.owner, bytes)?;
|
||||
Ok((file, metadata))
|
||||
}
|
||||
pub(crate) fn available(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<()> {
|
||||
self.open_object(tenant, hash, bytes).map(|_| ())
|
||||
}
|
||||
pub(crate) fn verified_file(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<File> {
|
||||
let (mut file, before) = self.open_object(tenant, hash, bytes)?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0_u8; 32768];
|
||||
let mut seen = 0;
|
||||
|
||||
Reference in New Issue
Block a user