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") {
|
match std::env::var_os("RMM_AGENT_UPDATE_ARTIFACT_DIR") {
|
||||||
Some(value) if FsPath::new(&value).is_absolute() => value.into(),
|
Some(value) if FsPath::new(&value).is_absolute() => value.into(),
|
||||||
Some(_) => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
|
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(),
|
metadata.uid(),
|
||||||
)?)
|
)?)
|
||||||
@@ -168,7 +171,9 @@ pub fn verify_envelope(
|
|||||||
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
|
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
|
||||||
) -> Result<ReleaseManifest, Error> {
|
) -> Result<ReleaseManifest, Error> {
|
||||||
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform;
|
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"));
|
return Err(fail("AGENT_UPDATE_DEVELOPMENT_CHANNEL_REQUIRED"));
|
||||||
}
|
}
|
||||||
let raw = keyring_bytes(platform)?;
|
let raw = keyring_bytes(platform)?;
|
||||||
@@ -255,7 +260,10 @@ fn verify_envelope_with_keyring(
|
|||||||
}
|
}
|
||||||
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||||
router
|
router
|
||||||
.route("/api/v1/tenants/{tenant}/enrollment-tokens", post(bootstrap::issue))
|
.route(
|
||||||
|
"/api/v1/tenants/{tenant}/enrollment-tokens",
|
||||||
|
post(bootstrap::issue),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/tenants/{tenant}/agent-releases",
|
"/api/v1/tenants/{tenant}/agent-releases",
|
||||||
get(list).post(import),
|
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> {
|
pub fn gateway_routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||||
router
|
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
|
RMM_BOOTSTRAP_PYTHON
|
||||||
/usr/bin/python3 -I \"$file\" install \"$@\"
|
/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/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/bootstrap/updater", get(bootstrap::updater))
|
||||||
.route("/agent/v1/releases/current", get(current))
|
.route("/agent/v1/releases/current", get(current))
|
||||||
.route("/agent/v1/releases/installed", get(installed))
|
.route("/agent/v1/releases/installed", get(installed))
|
||||||
@@ -456,7 +487,7 @@ pub async fn import(
|
|||||||
return Err(fail("AGENT_UPDATE_RELEASE_CONFLICT"));
|
return Err(fail("AGENT_UPDATE_RELEASE_CONFLICT"));
|
||||||
}
|
}
|
||||||
} else {
|
} 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?;
|
.bind(json!({"release_id":m.release_id,"manifest_sha256":manifest_sha,"testsimulation":p.testsimulation})).execute(&mut *tx).await?;
|
||||||
}
|
}
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
@@ -537,15 +568,23 @@ async fn device(
|
|||||||
.await
|
.await
|
||||||
.map_err(|status| Error(status, "UNAUTHENTICATED"))
|
.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 (tenant, agent) = device(&s, peer, &headers).await?;
|
||||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).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?;
|
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?;
|
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"),
|
"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
|
||||||
"connection_generation":row.get::<i64,_>("connection_generation"),
|
"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(
|
async fn check_device_platform(
|
||||||
@@ -562,7 +601,9 @@ async fn check_device_platform(
|
|||||||
let caps: Vec<String> = serde_json::from_value(caps)?;
|
let caps: Vec<String> = serde_json::from_value(caps)?;
|
||||||
let expected = match platform {
|
let expected = match platform {
|
||||||
Platform::LinuxX64 => "linux.base/1",
|
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::WindowsX64 => "windows.base/1",
|
||||||
Platform::WindowsGnuX64 => "agent.release.windows.gnu/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 mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||||
let (_, manifest) = checked_release(&mut tx, release).await?;
|
let (_, manifest) = checked_release(&mut tx, release).await?;
|
||||||
check_device_platform(&mut tx, agent, manifest.platform).await?;
|
check_device_platform(&mut tx, agent, manifest.platform).await?;
|
||||||
let descriptor = manifest.artifacts.into_iter()
|
let descriptor = manifest
|
||||||
.find(|entry| entry.artifact_id == artifact).ok_or_else(missing)?;
|
.artifacts
|
||||||
|
.into_iter()
|
||||||
|
.find(|entry| entry.artifact_id == artifact)
|
||||||
|
.ok_or_else(missing)?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
verified_binary(tenant, descriptor.sha256, descriptor.bytes).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 mut response = Response::new(Body::from_stream(stream));
|
||||||
let headers = response.headers_mut();
|
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-length", HeaderValue::from(size));
|
||||||
headers.insert("content-disposition", HeaderValue::from_static("attachment"));
|
headers.insert(
|
||||||
headers.insert("x-content-type-options", HeaderValue::from_static("nosniff"));
|
"content-disposition",
|
||||||
headers.insert("cache-control", HeaderValue::from_static("private, no-store"));
|
HeaderValue::from_static("attachment"),
|
||||||
headers.insert("x-artifact-sha256", HeaderValue::from_str(&sha256).map_err(|_| invalid())?);
|
);
|
||||||
|
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)
|
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 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 release = if let Some(id) = ids.first() {
|
||||||
let (envelope, manifest) = checked_release(&mut tx, *id).await?;
|
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}))
|
Some(json!({"release_envelope":envelope,"manifest":manifest}))
|
||||||
} else {
|
} else {
|
||||||
None
|
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 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 config: Config = serde_json::from_slice(&protected_file(FsPath::new(&path), 8192)?)?;
|
||||||
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
|
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
|
||||||
if url.scheme() != "https" || url.domain().is_none() || !url.username().is_empty()
|
if url.scheme() != "https"
|
||||||
|| url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|
|| url.domain().is_none()
|
||||||
|| url.path() != "/" || !rmm_domain::agent_update::digest(&config.updater_sha256)
|
|| !url.username().is_empty()
|
||||||
|| !(1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&config.updater_bytes) {
|
|| 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"));
|
return Err(fail("BOOTSTRAP_CONFIGURATION_INVALID"));
|
||||||
}
|
}
|
||||||
Ok(config)
|
Ok(config)
|
||||||
@@ -29,36 +35,82 @@ fn config(platform: Platform) -> Result<Config, Error> {
|
|||||||
fn private_json(body: Value) -> Response {
|
fn private_json(body: Value) -> Response {
|
||||||
([("cache-control", "private, no-store")], Json(body)).into_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> {
|
pub(super) async fn issue(
|
||||||
let p = s.auth.principal(&s, &headers, true).await.map_err(|status| Error(status, crate::auth::error_code(status)))?;
|
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)?;
|
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?;
|
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||||
crate::permissions::require_principal(&mut tx, &p, "devices:enroll").await?;
|
crate::permissions::require_principal(&mut tx, &p, "devices:enroll").await?;
|
||||||
let bootstrap_origin = std::env::var("RMM_BOOTSTRAP_ORIGIN").ok().map(|raw| {
|
let bootstrap_origin = std::env::var("RMM_BOOTSTRAP_ORIGIN")
|
||||||
let url = url::Url::parse(&raw).map_err(|_| invalid())?;
|
.ok()
|
||||||
if url.scheme() != "https" || url.domain().is_none() || !url.username().is_empty() || url.password().is_some()
|
.map(|raw| {
|
||||||
|| url.path() != "/" || url.query().is_some() || url.fragment().is_some() { return Err(invalid()); }
|
let url = url::Url::parse(&raw).map_err(|_| invalid())?;
|
||||||
Ok(url.origin().ascii_serialization())
|
if url.scheme() != "https"
|
||||||
}).transpose()?;
|
|| 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];
|
let mut bytes = [0; 32];
|
||||||
openssl::rand::rand_bytes(&mut bytes).map_err(|_| fail("TOKEN_GENERATION_FAILED"))?;
|
openssl::rand::rand_bytes(&mut bytes).map_err(|_| fail("TOKEN_GENERATION_FAILED"))?;
|
||||||
let token = hex::encode(bytes);
|
let token = hex::encode(bytes);
|
||||||
let expires: chrono::DateTime<chrono::Utc> = sqlx::query_scalar("SELECT issue_enrollment_token($1)")
|
let release_platforms: Vec<String> =
|
||||||
.bind(hash(token.as_bytes())).fetch_one(&mut *tx).await?;
|
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())")
|
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?;
|
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> {
|
async fn token_tenant(s: &crate::State, h: &HeaderMap) -> Result<Uuid, Error> {
|
||||||
let denied = || Error(StatusCode::UNAUTHORIZED, "ENROLLMENT_TOKEN_REQUIRED");
|
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)")
|
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)
|
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 t = token_tenant(&s, &headers).await?;
|
||||||
let c = config(q.platform)?;
|
let c = config(q.platform)?;
|
||||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
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?;
|
let (envelope, manifest) = checked_release(&mut tx, release).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
let ring: Value = serde_json::from_slice(&keyring_bytes(q.platform)?)?;
|
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())?;
|
let ca = s
|
||||||
Ok(private_json(json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
|
.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())?,
|
"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 tenant = token_tenant(&s, &headers).await?;
|
||||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||||
let (_, manifest) = checked_release(&mut tx, id).await?;
|
let (_, manifest) = checked_release(&mut tx, id).await?;
|
||||||
if manifest.platform != q.platform { return Err(missing()); }
|
if manifest.platform != q.platform {
|
||||||
let d = manifest.artifacts.into_iter().find(|v| v.artifact_id == artifact).ok_or_else(missing)?;
|
return Err(missing());
|
||||||
|
}
|
||||||
|
let d = manifest
|
||||||
|
.artifacts
|
||||||
|
.into_iter()
|
||||||
|
.find(|v| v.artifact_id == artifact)
|
||||||
|
.ok_or_else(missing)?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
verified_binary(tenant, d.sha256, d.bytes).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 tenant = token_tenant(&s, &headers).await?;
|
||||||
let c = config(q.platform)?;
|
let c = config(q.platform)?;
|
||||||
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
|
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
|
||||||
|
|||||||
@@ -179,8 +179,12 @@ async fn main() -> Result<()> {
|
|||||||
.route(
|
.route(
|
||||||
"/agent/v1/artifacts/{artifact}",
|
"/agent/v1/artifacts/{artifact}",
|
||||||
get(agent_artifacts::download),
|
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() {
|
if !role.api() {
|
||||||
// Public gateway never accepts browser or automation credentials.
|
// Public gateway never accepts browser or automation credentials.
|
||||||
routes = routes.route("/api/v1/job-signing-key", get(api::agent_job_signing_key));
|
routes = routes.route("/api/v1/job-signing-key", get(api::agent_job_signing_key));
|
||||||
|
|||||||
@@ -98,14 +98,21 @@ impl UpdateArtifacts {
|
|||||||
hasher: Sha256::new(),
|
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");
|
ensure!(descriptor(hash, bytes), "bounded update object descriptor");
|
||||||
let parent = self.parent(tenant)?;
|
let parent = self.parent(tenant)?;
|
||||||
let mut file = OpenOptions::new()
|
let file = OpenOptions::new()
|
||||||
.read(true)
|
.read(true)
|
||||||
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||||||
.open(parent.join(hash))?;
|
.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 hasher = Sha256::new();
|
||||||
let mut buffer = [0_u8; 32768];
|
let mut buffer = [0_u8; 32768];
|
||||||
let mut seen = 0;
|
let mut seen = 0;
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ $config = [ordered]@{
|
|||||||
ca_file = $caPath
|
ca_file = $caPath
|
||||||
state_directory = $state
|
state_directory = $state
|
||||||
enrollment_token_file = $tokenPath
|
enrollment_token_file = $tokenPath
|
||||||
transport = 'auto'
|
transport = 'https'
|
||||||
}
|
}
|
||||||
$configPath = Join-Path $root 'config.json'
|
$configPath = Join-Path $root 'config.json'
|
||||||
[IO.File]::WriteAllText($configPath, ($config | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
[IO.File]::WriteAllText($configPath, ($config | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- Migration 24 could not see FORCE ROW LEVEL SECURITY memberships without a
|
||||||
|
-- tenant context, even when run by the table owner. Use each tenant's policy.
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
current_tenant uuid;
|
||||||
|
BEGIN
|
||||||
|
FOR current_tenant IN SELECT tenant_id FROM tenants LOOP
|
||||||
|
PERFORM set_config('app.tenant_id', current_tenant::text, true);
|
||||||
|
UPDATE memberships SET permissions = array_append(permissions, 'devices:enroll')
|
||||||
|
WHERE tenant_id = current_tenant AND 'devices:revoke' = ANY(permissions)
|
||||||
|
AND NOT ('devices:enroll' = ANY(permissions));
|
||||||
|
END LOOP;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
+33
-9
@@ -8,6 +8,7 @@ import re
|
|||||||
import shlex
|
import shlex
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
sys.path.insert(0, str(ROOT / "deploy"))
|
sys.path.insert(0, str(ROOT / "deploy"))
|
||||||
@@ -72,7 +73,6 @@ $dir = Join-Path $root $hash
|
|||||||
$dst = Join-Path $dir $name
|
$dst = Join-Path $dir $name
|
||||||
foreach ($folder in @($root,$dir)) {
|
foreach ($folder in @($root,$dir)) {
|
||||||
if (!(Test-Path -LiteralPath $folder)) {
|
if (!(Test-Path -LiteralPath $folder)) {
|
||||||
if ($mode -eq 'probe') { 'missing'; exit 0 }
|
|
||||||
[void][IO.Directory]::CreateDirectory($folder)
|
[void][IO.Directory]::CreateDirectory($folder)
|
||||||
}
|
}
|
||||||
$item = Get-Item -LiteralPath $folder -Force
|
$item = Get-Item -LiteralPath $folder -Force
|
||||||
@@ -85,12 +85,15 @@ function Verify-File($file) {
|
|||||||
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or
|
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or
|
||||||
(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ne $hash) { throw 'Invalid artifact' }
|
(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ne $hash) { throw 'Invalid artifact' }
|
||||||
}
|
}
|
||||||
if (Test-Path -LiteralPath $dst) { Verify-File $dst; 'verified'; exit 0 }
|
$part = Join-Path $dir ('.upload.' + $upload)
|
||||||
|
if ($mode -eq 'cleanup') { [IO.File]::Delete($part); 'missing'; exit 0 }
|
||||||
|
if (Test-Path -LiteralPath $dst) {
|
||||||
|
Verify-File $dst
|
||||||
|
if ($mode -eq 'stage') { [IO.File]::Delete($part) }
|
||||||
|
'verified'; exit 0
|
||||||
|
}
|
||||||
if ($mode -eq 'probe') { 'missing'; exit 0 }
|
if ($mode -eq 'probe') { 'missing'; exit 0 }
|
||||||
$part = Join-Path $dir ('.upload.' + [Guid]::NewGuid())
|
|
||||||
$out = [IO.File]::Open($part, 'CreateNew', 'Write', 'None')
|
|
||||||
try {
|
try {
|
||||||
try { [Console]::OpenStandardInput().CopyTo($out) } finally { $out.Dispose() }
|
|
||||||
Verify-File $part
|
Verify-File $part
|
||||||
try { [IO.File]::Move($part,$dst) } catch [IO.IOException] { Verify-File $dst }
|
try { [IO.File]::Move($part,$dst) } catch [IO.IOException] { Verify-File $dst }
|
||||||
Verify-File $dst
|
Verify-File $dst
|
||||||
@@ -99,10 +102,10 @@ try {
|
|||||||
'''
|
'''
|
||||||
|
|
||||||
|
|
||||||
def remote_command(target, digest, name, mode):
|
def remote_command(target, digest, name, mode, upload=""):
|
||||||
if target == "windows":
|
if target == "windows":
|
||||||
# name and digest have a restricted alphabet before PowerShell sees them.
|
# name and digest have a restricted alphabet before PowerShell sees them.
|
||||||
script = f"$hash='{digest}'\n$name='{name}'\n$mode='{mode}'\n" + WINDOWS
|
script = f"$hash='{digest}'\n$name='{name}'\n$mode='{mode}'\n$upload='{upload}'\n" + WINDOWS
|
||||||
encoded = base64.b64encode(script.encode("utf-16le")).decode("ascii")
|
encoded = base64.b64encode(script.encode("utf-16le")).decode("ascii")
|
||||||
return "powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand " + encoded
|
return "powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand " + encoded
|
||||||
return shlex.join(["sh", "-c", UNIX, "dev-stage", digest, name, mode])
|
return shlex.join(["sh", "-c", UNIX, "dev-stage", digest, name, mode])
|
||||||
@@ -117,6 +120,23 @@ def transfer(prefix, command, file=None):
|
|||||||
return status
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
def windows_upload(prefix, path, digest):
|
||||||
|
# OpenSSH for Windows provides an SFTP subsystem for binary transfers.
|
||||||
|
# Refer to the validated basename so batch commands never contain a local directory name.
|
||||||
|
upload = uuid.uuid4().hex
|
||||||
|
remote = f"rmm-dev-stage/{digest}/.upload.{upload}"
|
||||||
|
sftp = ["sftp", *(part for part in prefix[1:-1] if part != "-T"), "-b", "-", prefix[-1]]
|
||||||
|
try:
|
||||||
|
result = subprocess.run(sftp, cwd=path.parent, input=f'put "{path.name}" "{remote}"\n'.encode(),
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
|
||||||
|
if result.returncode:
|
||||||
|
raise RuntimeError("Windows-SFTP-Transfer fehlgeschlagen")
|
||||||
|
return transfer(prefix, remote_command("windows", digest, path.name, "stage", upload))
|
||||||
|
except (OSError, RuntimeError, subprocess.TimeoutExpired):
|
||||||
|
transfer(prefix, remote_command("windows", digest, path.name, "cleanup", upload))
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description=__doc__, epilog=(
|
parser = argparse.ArgumentParser(description=__doc__, epilog=(
|
||||||
"Ziel: rmm-dev-stage/<SHA-256>/<Dateiname> im SSH-Benutzerprofil. "
|
"Ziel: rmm-dev-stage/<SHA-256>/<Dateiname> im SSH-Benutzerprofil. "
|
||||||
@@ -146,8 +166,12 @@ def main():
|
|||||||
if transfer(prefix, remote_command(args.target, digest, path.name, "probe")) == b"verified":
|
if transfer(prefix, remote_command(args.target, digest, path.name, "probe")) == b"verified":
|
||||||
print("vorhanden und geprüft", destination)
|
print("vorhanden und geprüft", destination)
|
||||||
continue
|
continue
|
||||||
file.seek(0)
|
if args.target == "windows":
|
||||||
if transfer(prefix, remote_command(args.target, digest, path.name, "stage"), file) != b"verified":
|
status = windows_upload(prefix, path, digest)
|
||||||
|
else:
|
||||||
|
file.seek(0)
|
||||||
|
status = transfer(prefix, remote_command(args.target, digest, path.name, "stage"), file)
|
||||||
|
if status != b"verified":
|
||||||
raise RuntimeError("Zielhash nicht bestätigt")
|
raise RuntimeError("Zielhash nicht bestätigt")
|
||||||
print("bereitgestellt und geprüft", destination)
|
print("bereitgestellt und geprüft", destination)
|
||||||
|
|
||||||
|
|||||||
+8
-5
@@ -176,7 +176,7 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session
|
|||||||
|
|
||||||
function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||||
const [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [source, setSource] = useState('{}'), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [receipts, setReceipts] = useState<unknown[]>([]);
|
const [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [source, setSource] = useState('{}'), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [receipts, setReceipts] = useState<unknown[]>([]);
|
||||||
const [enrollment, setEnrollment] = useState<{ token: string; expires: string; origin: string | null } | null>(null);
|
const [enrollment, setEnrollment] = useState<{ token: string; expires: string; origin: string | null; platforms: string[] } | null>(null);
|
||||||
const [enrollmentError, setEnrollmentError] = useState<string | null>(null);
|
const [enrollmentError, setEnrollmentError] = useState<string | null>(null);
|
||||||
const [issuing, setIssuing] = useState(false);
|
const [issuing, setIssuing] = useState(false);
|
||||||
const list = useResource(async signal => {
|
const list = useResource(async signal => {
|
||||||
@@ -212,14 +212,17 @@ function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Sessi
|
|||||||
try {
|
try {
|
||||||
const result = record(await request(tenantPath(tenantId, '/enrollment-tokens'), { body: {}, csrf: auth.csrf_token }));
|
const result = record(await request(tenantPath(tenantId, '/enrollment-tokens'), { body: {}, csrf: auth.csrf_token }));
|
||||||
if (typeof result.token !== 'string' || !/^[a-f0-9]{64}$/.test(result.token) || typeof result.expires_at !== 'string') throw new Error('Ungültiger Einmalcode');
|
if (typeof result.token !== 'string' || !/^[a-f0-9]{64}$/.test(result.token) || typeof result.expires_at !== 'string') throw new Error('Ungültiger Einmalcode');
|
||||||
setEnrollment({ token: result.token, expires: result.expires_at, origin: typeof result.bootstrap_origin === 'string' ? new URL(result.bootstrap_origin).origin : null });
|
setEnrollment({ token: result.token, expires: result.expires_at, origin: typeof result.bootstrap_origin === 'string' ? new URL(result.bootstrap_origin).origin : null,
|
||||||
|
platforms: Array.isArray(result.release_platforms) ? result.release_platforms.filter((p): p is string => typeof p === 'string') : [] });
|
||||||
} catch (error) { setEnrollmentError(errorText(error)); } finally { setIssuing(false); }
|
} catch (error) { setEnrollmentError(errorText(error)); } finally { setIssuing(false); }
|
||||||
}}>Einmalcode erstellen</button>
|
}}>Einmalcode erstellen</button>
|
||||||
<ErrorBox error={enrollmentError}/>
|
<ErrorBox error={enrollmentError}/>
|
||||||
{enrollment && <><label>Einmalcode gültig bis {new Date(enrollment.expires).toLocaleString()}<input readOnly value={enrollment.token}/></label><button onClick={() => setEnrollment(null)}>Code ausblenden</button>
|
{enrollment && <><label>Einmalcode gültig bis {new Date(enrollment.expires).toLocaleString()}<input readOnly value={enrollment.token}/></label><button onClick={() => setEnrollment(null)}>Code ausblenden</button>
|
||||||
{enrollment.origin && <><p>Linux, mit einem Administratorkonto ausführen</p><pre>{`curl --fail --show-error --silent '${enrollment.origin}/install/linux.sh' -o linux.sh && sudo sh linux.sh '${enrollment.origin}'`}</pre>
|
{enrollment.origin && enrollment.platforms.includes('x86_64-unknown-linux-gnu') && <><p>Linux, mit einem Administratorkonto ausführen</p><pre>{`curl --fail --show-error --silent '${enrollment.origin}/install/linux.sh' -o linux.sh && sudo sh linux.sh '${enrollment.origin}'`}</pre></>}
|
||||||
<p>Windows, in einer administrativen Windows PowerShell ausführen</p><pre>{`Invoke-WebRequest -UseBasicParsing '${enrollment.origin}/install/windows.ps1' -OutFile .\\windows.ps1
|
{enrollment.origin && ['x86_64-pc-windows-msvc','x86_64-pc-windows-gnu'].filter(p => enrollment.platforms.includes(p)).map(platform =>
|
||||||
.\\windows.ps1 -BootstrapBase '${enrollment.origin}'`}</pre></>}
|
<div key={platform}><p>Windows {platform.endsWith('-gnu') ? 'GNU (Entwicklungsrelease)' : 'MSVC'}, in einer administrativen Windows PowerShell ausführen</p>
|
||||||
|
<pre>{`Invoke-WebRequest -UseBasicParsing '${enrollment.origin}/install/windows.ps1' -OutFile .\\windows.ps1
|
||||||
|
.\\windows.ps1 -BootstrapBase '${enrollment.origin}' -Platform '${platform}'`}</pre></div>)}
|
||||||
</>}
|
</>}
|
||||||
</details>
|
</details>
|
||||||
</section>;
|
</section>;
|
||||||
|
|||||||
Reference in New Issue
Block a user