worker: persist known-worker control grants

This commit is contained in:
2026-08-16 23:08:32 +09:00
parent 46a44b232b
commit f41ab0e277
7 changed files with 1082 additions and 212 deletions
+379 -73
View File
@@ -103,8 +103,8 @@ use crate::skills;
use crate::store::{
AccountRecord, ApiTokenRecord, AuthChallengeRecord, BrowserSessionRecord, ControlPlaneStore,
DeviceLoginFlowRecord, FlowSourceRecord, PasskeyCredentialRecord, RepositoryRecord,
TicketWorkerAssignmentRecord, UserRecord, WorkdirRegistryRecord, WorkerRegistryRecord,
WorkerWorkdirLinkRecord, WorkspaceRecord,
TicketWorkerAssignmentRecord, UserRecord, WorkdirRegistryRecord, WorkerControlGrantRecord,
WorkerRegistryRecord, WorkerWorkdirLinkRecord, WorkspaceRecord,
};
use crate::{Error, Result};
use worker_runtime::catalog::{
@@ -335,20 +335,10 @@ impl WorkspaceWorkerRemoveExecutor {
let runtime = self.runtime.upgrade().ok_or_else(|| {
"Workspace Runtime registry is unavailable during WorkerRemove".to_string()
})?;
let source_is_current_orchestrator =
runtime.list_workers(1_000).items.into_iter().any(|worker| {
worker.worker.runtime_id == source.runtime_id
&& worker.worker.worker_id == source.worker_id
&& worker.singleton_key.as_deref()
== Some(crate::hosts::WORKSPACE_ORCHESTRATOR_SINGLETON_KEY)
});
if !source_is_current_orchestrator {
return Ok(worker_remove_error_response(
StatusCode::FORBIDDEN,
"orchestrator_required",
"WorkerRemove is restricted to the current Workspace Orchestrator",
));
}
let target = RuntimeWorkerRef {
runtime_id: target_runtime_id.to_string(),
worker_id: target_worker_id.to_string(),
};
if source.runtime_id == target_runtime_id && source.worker_id == target_worker_id {
return Ok(worker_remove_error_response(
StatusCode::CONFLICT,
@@ -356,11 +346,25 @@ impl WorkspaceWorkerRemoveExecutor {
"The current Orchestrator cannot remove itself",
));
}
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
let granted = self
.store
.get_active_worker_control_grant(&self.workspace_id, &controller, &target)
.map_err(|_| "Worker control grant authority is unavailable".to_string())?
.is_some_and(|grant| {
grant
.permissions
.iter()
.any(|permission| permission == "remove")
});
if !granted {
return Ok(worker_remove_error_response(
StatusCode::NOT_FOUND,
"unknown_worker",
"The target Worker is not known to the current Worker",
));
}
let target = RuntimeWorkerRef {
runtime_id: target_runtime_id.to_string(),
worker_id: target_worker_id.to_string(),
};
let remove_lock = {
let mut locks = self
.worker_remove_locks
@@ -1435,6 +1439,26 @@ pub fn build_router(api: WorkspaceApi) -> Router {
get(scoped_workspace_orchestrator_status)
.post(scoped_start_workspace_orchestrator),
)
.route(
"/api/w/{workspace_id}/worker-control/workers",
get(list_known_workers).post(spawn_known_worker),
)
.route(
"/api/w/{workspace_id}/worker-control/workers/{runtime_id}/{worker_id}/input",
post(send_known_worker_input),
)
.route(
"/api/w/{workspace_id}/worker-control/workers/{runtime_id}/{worker_id}/cancel",
post(cancel_known_worker),
)
.route(
"/api/w/{workspace_id}/worker-control/workers/{runtime_id}/{worker_id}/stop",
post(stop_known_worker),
)
.route(
"/api/w/{workspace_id}/worker-control/workers/{runtime_id}/{worker_id}/restore",
post(restore_known_worker),
)
.route(
"/api/w/{workspace_id}/worker-observation/sessions",
get(scoped_list_worker_observation_sessions),
@@ -2066,6 +2090,9 @@ pub struct CreateWorkspaceWorkerRequest {
pub initial_submit: Vec<Segment>,
#[serde(default)]
pub working_directory: Option<BrowserWorkerWorkingDirectorySelection>,
/// Backend idempotency key used only for authenticated Worker-owned spawn/control.
#[serde(default)]
pub control_operation_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -5832,6 +5859,229 @@ async fn scoped_workspace_orchestrator_status(
Ok(Json(workspace_orchestrator_response(&api, "observed")))
}
#[derive(Debug, Serialize, Deserialize)]
struct KnownWorkerRecord {
subject: RuntimeWorkerRef,
relation: String,
origin: String,
permissions: Vec<String>,
summary: WorkerSummary,
}
#[derive(Debug, Serialize, Deserialize)]
struct KnownWorkersResponse {
workspace_id: String,
items: Vec<KnownWorkerRecord>,
truncated: bool,
}
async fn list_known_workers(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedWorkspacePath>,
headers: HeaderMap,
) -> ApiResult<Json<KnownWorkersResponse>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
let limit = api.config.max_records.clamp(1, 500);
let grants =
api.store
.list_active_worker_control_grants(&path.workspace_id, &controller, limit + 1)?;
let truncated = grants.len() > limit;
let mut items = Vec::with_capacity(grants.len().min(limit));
for grant in grants.into_iter().take(limit) {
let summary = api
.runtime
.worker(&grant.subject)
.map_err(|error| error.into_error())?;
items.push(KnownWorkerRecord {
subject: grant.subject,
relation: grant.relation,
origin: grant.origin,
permissions: grant.permissions,
summary,
});
}
Ok(Json(KnownWorkersResponse {
workspace_id: path.workspace_id,
items,
truncated,
}))
}
async fn spawn_known_worker(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedWorkspacePath>,
headers: HeaderMap,
Json(request): Json<CreateWorkspaceWorkerRequest>,
) -> ApiResult<Json<BrowserCreateWorkerResponse>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
let relation = if request.ticket_assignment.is_some() {
"assigned"
} else {
"spawned"
};
let operation_id = request
.control_operation_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| Error::InvalidInput("control_operation_id is required".to_string()))?
.to_string();
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
if request.ticket_assignment.is_none()
&& let Some(existing) = api.store.get_worker_control_grant_by_operation(
&path.workspace_id,
&controller,
&operation_id,
)?
{
let worker = api
.runtime
.worker(&existing.subject)
.map_err(|error| error.into_error())?;
return Ok(Json(BrowserCreateWorkerResponse {
workspace_id: path.workspace_id,
console_href: format!(
"/w/{}/runtimes/{}/workers/{}/console",
encode_path_segment(&existing.workspace_id),
encode_path_segment(&existing.subject.runtime_id),
encode_path_segment(&existing.subject.worker_id),
),
worker_ref: existing.subject,
worker,
diagnostics: Vec::new(),
}));
}
let response = create_workspace_worker(State(api.clone()), headers, Json(request)).await?;
if let Err(error) = api
.store
.create_worker_control_grant(&WorkerControlGrantRecord {
workspace_id: path.workspace_id.clone(),
grant_id: new_id("wcg"),
controller,
subject: response.0.worker_ref.clone(),
relation: relation.to_string(),
origin: "worker_spawn".to_string(),
permissions: vec![
"send_input".to_string(),
"notify".to_string(),
"cancel".to_string(),
"stop".to_string(),
"restore".to_string(),
"remove".to_string(),
"observe".to_string(),
],
operation_id,
created_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
revoked_at: None,
})
{
let subject = response.0.worker_ref.clone();
let _ = api.runtime.delete_worker(&subject);
let _ = api
.store
.delete_worker_registry(&path.workspace_id, &subject);
return Err(ApiError::from(error));
}
Ok(response)
}
fn authorize_known_worker_permission(
api: &WorkspaceApi,
workspace_id: &str,
controller: &RuntimeWorkerRef,
subject: &RuntimeWorkerRef,
permission: &str,
) -> Result<()> {
let grant = api
.store
.get_active_worker_control_grant(workspace_id, controller, subject)?
.ok_or_else(|| Error::UnknownWorker {
worker: subject.clone(),
})?;
if !grant
.permissions
.iter()
.any(|candidate| candidate == permission)
{
return Err(Error::InvalidInput(format!(
"worker control permission `{permission}` was not granted"
)));
}
Ok(())
}
async fn send_known_worker_input(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedRuntimeWorkerPath>,
headers: HeaderMap,
Json(request): Json<WorkerInputRequest>,
) -> ApiResult<Json<WorkerInputResult>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
let permission = match request.kind {
WorkerInputKind::Notify => "notify",
_ => "send_input",
};
authorize_known_worker_permission(
&api,
&path.workspace_id,
&controller,
&path.worker,
permission,
)?;
scoped_send_runtime_worker_input(State(api), AxumPath(path), Json(request)).await
}
async fn cancel_known_worker(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedRuntimeWorkerPath>,
headers: HeaderMap,
Json(request): Json<WorkerLifecycleRequest>,
) -> ApiResult<Json<WorkerLifecycleResult>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
authorize_known_worker_permission(
&api,
&path.workspace_id,
&controller,
&path.worker,
"cancel",
)?;
scoped_cancel_runtime_worker(State(api), AxumPath(path), Json(request)).await
}
async fn stop_known_worker(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedRuntimeWorkerPath>,
headers: HeaderMap,
Json(request): Json<WorkerLifecycleRequest>,
) -> ApiResult<Json<WorkerLifecycleResult>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
let subject = path.worker.clone();
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
authorize_known_worker_permission(&api, &path.workspace_id, &controller, &subject, "stop")?;
scoped_stop_runtime_worker(State(api), AxumPath(path), Json(request)).await
}
async fn restore_known_worker(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedRuntimeWorkerPath>,
headers: HeaderMap,
) -> ApiResult<Json<WorkerRestoreResponse>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
let subject = path.worker.clone();
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
authorize_known_worker_permission(&api, &path.workspace_id, &controller, &subject, "restore")?;
scoped_restore_runtime_worker(State(api), AxumPath(path), Query(Default::default())).await
}
async fn scoped_list_worker_observation_sessions(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedWorkspacePath>,
@@ -5839,26 +6089,34 @@ async fn scoped_list_worker_observation_sessions(
) -> ApiResult<Json<serde_json::Value>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
authorize_workspace_orchestrator_observation(&api, &source)?;
let sessions = workers_response(api.clone())?
.items
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
let sessions = api
.store
.list_active_worker_control_grants(&path.workspace_id, &controller, 100)?
.into_iter()
.filter(|worker| {
!matches!(
.filter(|grant| {
grant
.permissions
.iter()
.any(|permission| permission == "observe")
})
.filter_map(|grant| {
let worker = api.runtime.worker(&grant.subject).ok()?;
if matches!(
worker.state.as_str(),
"stopped" | "failed" | "rejected" | "disconnected"
) && (worker.worker.runtime_id != source.runtime_id
|| worker.worker.worker_id != source.worker_id)
})
.take(100)
.map(|worker| WorkerObservationSubject {
subject: WorkerObservationSubjectRef::RuntimeWorker {
runtime_id: worker.worker.runtime_id,
worker_id: worker.worker.worker_id,
},
display_name: worker.display_name,
relation: "workspace_orchestrator_grant".to_string(),
status: worker.state,
) {
return None;
}
Some(WorkerObservationSubject {
subject: WorkerObservationSubjectRef::RuntimeWorker {
runtime_id: grant.subject.runtime_id,
worker_id: grant.subject.worker_id,
},
display_name: worker.display_name,
relation: grant.relation,
status: worker.state,
})
})
.collect::<Vec<_>>();
Ok(Json(serde_json::json!({ "sessions": sessions })))
@@ -5872,7 +6130,6 @@ async fn scoped_capture_worker_observation_session(
) -> ApiResult<Json<serde_json::Value>> {
validate_workspace_scope(&api, &path.workspace_id)?;
let source = authenticate_worker_mutation_source(&api, &path.workspace_id, &headers)?;
authorize_workspace_orchestrator_observation(&api, &source)?;
let WorkerObservationSubjectRef::RuntimeWorker {
runtime_id,
worker_id,
@@ -5883,17 +6140,16 @@ async fn scoped_capture_worker_observation_session(
}));
};
let target = RuntimeWorkerRef::new(runtime_id, worker_id);
let granted = workers_response(api.clone())?
.items
.into_iter()
.any(|worker| {
worker.worker == target
&& !matches!(
worker.state.as_str(),
"stopped" | "failed" | "rejected" | "disconnected"
)
});
if !granted {
let controller = RuntimeWorkerRef::new(&source.runtime_id, &source.worker_id);
authorize_known_worker_permission(&api, &path.workspace_id, &controller, &target, "observe")?;
let target_summary = api
.runtime
.worker(&target)
.map_err(|error| error.into_error())?;
if matches!(
target_summary.state.as_str(),
"stopped" | "failed" | "rejected" | "disconnected"
) {
return Err(ApiError::from(Error::UnknownWorker { worker: target }));
}
@@ -5927,25 +6183,6 @@ async fn scoped_capture_worker_observation_session(
})))
}
fn authorize_workspace_orchestrator_observation(
api: &WorkspaceApi,
source: &WorkerMutationSource,
) -> ApiResult<()> {
let Some(orchestrator) = find_workspace_orchestrator(api) else {
return Err(ApiError::from(Error::UnknownWorker {
worker: RuntimeWorkerRef::new(source.runtime_id.clone(), source.worker_id.clone()),
}));
};
if orchestrator.worker.runtime_id != source.runtime_id
|| orchestrator.worker.worker_id != source.worker_id
{
return Err(ApiError::from(Error::UnknownWorker {
worker: RuntimeWorkerRef::new(source.runtime_id.clone(), source.worker_id.clone()),
}));
}
Ok(())
}
async fn scoped_start_workspace_orchestrator(
State(api): State<WorkspaceApi>,
AxumPath(path): AxumPath<ScopedWorkspacePath>,
@@ -6028,6 +6265,14 @@ async fn scoped_start_workspace_orchestrator(
result.diagnostics,
));
}
let worker = result.worker.as_ref().expect("accepted Worker was checked");
record_worker_summary(
&api,
worker,
&worker.display_name,
Some("builtin:orchestrator".to_string()),
WorkerRegistryDisplayNamePolicy::UseProvided,
)?;
*api.orchestrator_attention_fingerprint
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
@@ -8446,6 +8691,7 @@ async fn create_workspace_worker(
ticket_assignment,
initial_submit,
working_directory,
control_operation_id: _,
} = request;
let config_state = api
.config_store
@@ -12273,6 +12519,7 @@ mod tests {
selector: "builtin:coder-review".to_string(),
}],
working_directory: None,
control_operation_id: None,
}),
)
.await
@@ -12312,6 +12559,7 @@ mod tests {
ticket_assignment: None,
initial_submit: Vec::new(),
working_directory: None,
control_operation_id: None,
}),
)
.await
@@ -12346,6 +12594,7 @@ mod tests {
ticket_assignment: None,
initial_submit: Vec::new(),
working_directory: None,
control_operation_id: None,
}),
)
.await
@@ -12447,6 +12696,7 @@ mod tests {
selector: "builtin:coder-review".to_string(),
}],
working_directory: None,
control_operation_id: None,
}),
)
.await
@@ -12745,6 +12995,7 @@ mod tests {
ticket_assignment: None,
initial_submit: Vec::new(),
working_directory: None,
control_operation_id: None,
}),
)
.await
@@ -12761,6 +13012,7 @@ mod tests {
ticket_assignment: None,
initial_submit: Vec::new(),
working_directory: None,
control_operation_id: None,
}),
)
.await
@@ -12783,6 +13035,21 @@ mod tests {
);
assert_ne!(dedicated.worker.worker_id, generic.worker_ref.worker_id);
api.store
.create_worker_control_grant(&WorkerControlGrantRecord {
workspace_id: workspace_id.clone(),
grant_id: "orchestrator-controls-generic".to_string(),
controller: dedicated.worker.clone(),
subject: generic.worker_ref.clone(),
relation: "spawned".to_string(),
origin: "test".to_string(),
permissions: vec!["observe".to_string()],
operation_id: "observe-generic".to_string(),
created_at: "2026-07-27T00:00:00Z".to_string(),
revoked_at: None,
})
.unwrap();
let mut observation_headers = HeaderMap::new();
observation_headers.insert(
"x-yoi-runtime-id",
@@ -12792,6 +13059,19 @@ mod tests {
"x-yoi-worker-id",
axum::http::HeaderValue::from_str(&dedicated.worker.worker_id).unwrap(),
);
let Json(known) = list_known_workers(
State(api.clone()),
AxumPath(ScopedWorkspacePath {
workspace_id: workspace_id.clone(),
}),
observation_headers.clone(),
)
.await
.unwrap();
assert_eq!(known.items.len(), 1);
assert_eq!(known.items[0].subject, generic.worker_ref);
assert_eq!(known.items[0].permissions, ["observe"]);
let Json(sessions) = scoped_list_worker_observation_sessions(
State(api.clone()),
AxumPath(ScopedWorkspacePath {
@@ -12836,7 +13116,7 @@ mod tests {
"x-yoi-worker-id",
axum::http::HeaderValue::from_str(&generic.worker_ref.worker_id).unwrap(),
);
let error = scoped_list_worker_observation_sessions(
let Json(unauthorized) = scoped_list_worker_observation_sessions(
State(api.clone()),
AxumPath(ScopedWorkspacePath {
workspace_id: workspace_id.clone(),
@@ -12844,8 +13124,8 @@ mod tests {
unauthorized_headers,
)
.await
.unwrap_err();
assert_eq!(error.into_response().status(), StatusCode::NOT_FOUND);
.unwrap();
assert!(unauthorized["sessions"].as_array().unwrap().is_empty());
let Json(existing) = scoped_start_workspace_orchestrator(
State(api.clone()),
@@ -14883,6 +15163,9 @@ mod tests {
)
.unwrap();
let target = spawned.worker.unwrap().worker;
let target_summary = api.runtime.worker(&target).unwrap();
sync_worker_observation(&api, &target_summary).unwrap();
seed_worker_control_grant(&api, &source, &target, "caller-guard-target");
let running_response = executor
.execute_async(
verified_source(),
@@ -14992,6 +15275,7 @@ mod tests {
.unwrap();
let summary = api.runtime.worker(&target).unwrap();
let record = sync_worker_observation(&api, &summary).unwrap();
seed_worker_control_grant(&api, &source, &target, "embedded-valid-proof");
let response = WorkspaceWorkerRemoveExecutor::new(&api)
.execute_async(
@@ -15208,12 +15492,12 @@ mod tests {
)
.await
.unwrap();
assert_eq!(route_response.status(), StatusCode::FORBIDDEN);
assert_eq!(route_response.status(), StatusCode::NOT_FOUND);
let route_body = axum::body::to_bytes(route_response.into_body(), usize::MAX)
.await
.unwrap();
let route_body = String::from_utf8(route_body.to_vec()).unwrap();
assert!(route_body.contains("orchestrator_required"));
assert!(route_body.contains("unknown_worker"));
assert!(!route_body.contains("source"));
assert!(!route_body.contains("proof"));
@@ -15262,6 +15546,28 @@ mod tests {
.unwrap();
}
fn seed_worker_control_grant(
api: &WorkspaceApi,
controller: &RuntimeWorkerRef,
subject: &RuntimeWorkerRef,
operation_id: &str,
) {
api.store
.create_worker_control_grant(&WorkerControlGrantRecord {
workspace_id: api.config.workspace_id.clone(),
grant_id: format!("grant-{operation_id}"),
controller: controller.clone(),
subject: subject.clone(),
relation: "spawned".to_string(),
origin: "test".to_string(),
permissions: vec!["remove".to_string()],
operation_id: operation_id.to_string(),
created_at: now_registry_timestamp(),
revoked_at: None,
})
.unwrap();
}
fn seed_cleanup_worker(
api: &WorkspaceApi,
runtime_worker_id: u64,
+414 -9
View File
@@ -181,6 +181,11 @@ const MIGRATIONS: &[Migration] = &[
name: "persist Workspace config schema contribution bundles",
apply: persist_workspace_config_schema_bundles,
},
Migration {
version: 33,
name: "create durable Runtime Worker control grants",
apply: create_worker_control_grant_authority,
},
];
struct Migration {
@@ -325,6 +330,23 @@ pub struct WorkerRegistryRecord {
pub updated_at: String,
}
/// Durable authority describing which Runtime Worker another Runtime Worker may
/// discover and control. Revoked grants remain as audit evidence but are never
/// returned by active-grant queries.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkerControlGrantRecord {
pub workspace_id: String,
pub grant_id: String,
pub controller: RuntimeWorkerRef,
pub subject: RuntimeWorkerRef,
pub relation: String,
pub origin: String,
pub permissions: Vec<String>,
pub operation_id: String,
pub created_at: String,
pub revoked_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TicketWorkerAssignmentRecord {
pub workspace_id: String,
@@ -732,6 +754,35 @@ pub trait ControlPlaneStore: Send + Sync {
fn delete_worker_registry(&self, workspace_id: &str, worker: &RuntimeWorkerRef)
-> Result<bool>;
fn create_worker_control_grant(
&self,
record: &WorkerControlGrantRecord,
) -> Result<WorkerControlGrantRecord>;
fn get_worker_control_grant_by_operation(
&self,
workspace_id: &str,
controller: &RuntimeWorkerRef,
operation_id: &str,
) -> Result<Option<WorkerControlGrantRecord>>;
fn get_active_worker_control_grant(
&self,
workspace_id: &str,
controller: &RuntimeWorkerRef,
subject: &RuntimeWorkerRef,
) -> Result<Option<WorkerControlGrantRecord>>;
fn list_active_worker_control_grants(
&self,
workspace_id: &str,
controller: &RuntimeWorkerRef,
limit: usize,
) -> Result<Vec<WorkerControlGrantRecord>>;
fn revoke_worker_control_grant(
&self,
workspace_id: &str,
grant_id: &str,
revoked_at: &str,
) -> Result<bool>;
fn get_ticket_assignment_operation(
&self,
workspace_id: &str,
@@ -2321,6 +2372,157 @@ impl ControlPlaneStore for SqliteWorkspaceStore {
})
}
fn create_worker_control_grant(
&self,
record: &WorkerControlGrantRecord,
) -> Result<WorkerControlGrantRecord> {
self.with_conn(|conn| {
let permissions_json = serde_json::to_string(&record.permissions)
.map_err(|error| Error::Store(error.to_string()))?;
conn.execute(
r#"INSERT INTO worker_control_grants (
workspace_id, grant_id,
controller_runtime_id, controller_worker_id,
subject_runtime_id, subject_worker_id,
relation, origin, permissions_json, operation_id, created_at, revoked_at
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
ON CONFLICT (
workspace_id,
controller_runtime_id,
controller_worker_id,
operation_id
) DO NOTHING"#,
params![
record.workspace_id,
record.grant_id,
record.controller.runtime_id,
record.controller.worker_id,
record.subject.runtime_id,
record.subject.worker_id,
record.relation,
record.origin,
permissions_json,
record.operation_id,
record.created_at,
record.revoked_at,
],
)?;
let persisted = read_worker_control_grant_by_operation(
conn,
record.workspace_id.as_str(),
&record.controller,
record.operation_id.as_str(),
)?
.ok_or_else(|| Error::Store("worker control grant was not persisted".to_string()))?;
if persisted.subject != record.subject
|| persisted.relation != record.relation
|| persisted.origin != record.origin
|| persisted.permissions != record.permissions
{
return Err(Error::InvalidInput(format!(
"worker control operation `{}` was already used with different input",
record.operation_id
)));
}
Ok(persisted)
})
}
fn get_worker_control_grant_by_operation(
&self,
workspace_id: &str,
controller: &RuntimeWorkerRef,
operation_id: &str,
) -> Result<Option<WorkerControlGrantRecord>> {
self.with_conn(|conn| {
read_worker_control_grant_by_operation(conn, workspace_id, controller, operation_id)
})
}
fn get_active_worker_control_grant(
&self,
workspace_id: &str,
controller: &RuntimeWorkerRef,
subject: &RuntimeWorkerRef,
) -> Result<Option<WorkerControlGrantRecord>> {
self.with_conn(|conn| {
conn.query_row(
r#"SELECT workspace_id, grant_id,
controller_runtime_id, controller_worker_id,
subject_runtime_id, subject_worker_id,
relation, origin, permissions_json, operation_id, created_at, revoked_at
FROM worker_control_grants
WHERE workspace_id = ?1
AND controller_runtime_id = ?2 AND controller_worker_id = ?3
AND subject_runtime_id = ?4 AND subject_worker_id = ?5
AND revoked_at IS NULL
ORDER BY created_at DESC
LIMIT 1"#,
params![
workspace_id,
controller.runtime_id,
controller.worker_id,
subject.runtime_id,
subject.worker_id,
],
read_worker_control_grant_record,
)
.optional()
.map_err(Error::from)
})
}
fn list_active_worker_control_grants(
&self,
workspace_id: &str,
controller: &RuntimeWorkerRef,
limit: usize,
) -> Result<Vec<WorkerControlGrantRecord>> {
self.with_conn(|conn| {
let mut stmt = conn.prepare(
r#"SELECT workspace_id, grant_id,
controller_runtime_id, controller_worker_id,
subject_runtime_id, subject_worker_id,
relation, origin, permissions_json, operation_id, created_at, revoked_at
FROM worker_control_grants
WHERE workspace_id = ?1
AND controller_runtime_id = ?2 AND controller_worker_id = ?3
AND revoked_at IS NULL
ORDER BY created_at ASC, grant_id ASC
LIMIT ?4"#,
)?;
let rows = stmt.query_map(
params![
workspace_id,
controller.runtime_id,
controller.worker_id,
limit as i64,
],
read_worker_control_grant_record,
)?;
rows.collect::<std::result::Result<Vec<_>, _>>()
.map_err(Error::from)
})
}
fn revoke_worker_control_grant(
&self,
workspace_id: &str,
grant_id: &str,
revoked_at: &str,
) -> Result<bool> {
self.with_conn(|conn| {
let changed = conn.execute(
r#"UPDATE worker_control_grants
SET revoked_at = ?3
WHERE workspace_id = ?1 AND grant_id = ?2 AND revoked_at IS NULL"#,
params![workspace_id, grant_id, revoked_at],
)?;
Ok(changed > 0)
})
}
fn get_ticket_assignment_operation(
&self,
workspace_id: &str,
@@ -3627,6 +3829,57 @@ fn read_worker_registry_record(row: &rusqlite::Row<'_>) -> rusqlite::Result<Work
})
}
fn read_worker_control_grant_record(
row: &rusqlite::Row<'_>,
) -> rusqlite::Result<WorkerControlGrantRecord> {
let permissions_json: String = row.get(8)?;
let permissions = serde_json::from_str(&permissions_json).map_err(|error| {
rusqlite::Error::FromSqlConversionFailure(8, rusqlite::types::Type::Text, Box::new(error))
})?;
Ok(WorkerControlGrantRecord {
workspace_id: row.get(0)?,
grant_id: row.get(1)?,
controller: RuntimeWorkerRef::new(
row.get::<_, String>(2)?,
row.get::<_, u64>(3)?.to_string(),
),
subject: RuntimeWorkerRef::new(row.get::<_, String>(4)?, row.get::<_, u64>(5)?.to_string()),
relation: row.get(6)?,
origin: row.get(7)?,
permissions,
operation_id: row.get(9)?,
created_at: row.get(10)?,
revoked_at: row.get(11)?,
})
}
fn read_worker_control_grant_by_operation(
conn: &Connection,
workspace_id: &str,
controller: &RuntimeWorkerRef,
operation_id: &str,
) -> Result<Option<WorkerControlGrantRecord>> {
conn.query_row(
r#"SELECT workspace_id, grant_id,
controller_runtime_id, controller_worker_id,
subject_runtime_id, subject_worker_id,
relation, origin, permissions_json, operation_id, created_at, revoked_at
FROM worker_control_grants
WHERE workspace_id = ?1
AND controller_runtime_id = ?2 AND controller_worker_id = ?3
AND operation_id = ?4"#,
params![
workspace_id,
controller.runtime_id,
controller.worker_id,
operation_id,
],
read_worker_control_grant_record,
)
.optional()
.map_err(Error::from)
}
fn current_ticket_worker_assignment_select_sql() -> String {
"SELECT a.workspace_id, a.ticket_id, a.assignment_id, a.runtime_id, a.worker_id, \
a.assigned_by, a.assigned_at \
@@ -4639,6 +4892,58 @@ pub(crate) fn persist_workspace_config_schema_bundles(conn: &Connection) -> Resu
Ok(())
}
fn create_worker_control_grant_authority(conn: &Connection) -> Result<()> {
conn.execute_batch(
r#"
CREATE TABLE worker_control_grants (
workspace_id TEXT NOT NULL,
grant_id TEXT NOT NULL,
controller_runtime_id TEXT NOT NULL,
controller_worker_id INTEGER NOT NULL,
subject_runtime_id TEXT NOT NULL,
subject_worker_id INTEGER NOT NULL,
relation TEXT NOT NULL,
origin TEXT NOT NULL,
permissions_json TEXT NOT NULL,
operation_id TEXT NOT NULL,
created_at TEXT NOT NULL,
revoked_at TEXT,
PRIMARY KEY (workspace_id, grant_id),
UNIQUE (
workspace_id,
controller_runtime_id,
controller_worker_id,
operation_id
),
FOREIGN KEY (workspace_id, controller_runtime_id, controller_worker_id)
REFERENCES worker_registry (workspace_id, runtime_id, runtime_worker_id)
ON DELETE CASCADE,
FOREIGN KEY (workspace_id, subject_runtime_id, subject_worker_id)
REFERENCES worker_registry (workspace_id, runtime_id, runtime_worker_id)
ON DELETE CASCADE
);
CREATE INDEX idx_worker_control_grants_controller_active
ON worker_control_grants (
workspace_id,
controller_runtime_id,
controller_worker_id,
revoked_at,
created_at
);
CREATE INDEX idx_worker_control_grants_subject_active
ON worker_control_grants (
workspace_id,
subject_runtime_id,
subject_worker_id,
revoked_at
);
"#,
)?;
Ok(())
}
fn create_worker_mutation_source_proof_replay_guard(conn: &Connection) -> Result<()> {
conn.execute_batch(
r#"
@@ -5312,7 +5617,7 @@ CREATE TABLE ticket_worker_links (ticket_id TEXT, worker_ref_key TEXT);
apply_migrations(&conn).unwrap();
assert_eq!(current_schema_version(&conn).unwrap(), 32);
assert_eq!(current_schema_version(&conn).unwrap(), 33);
assert!(table_exists(&conn, "worker_workdir_attachment_reservations").unwrap());
}
@@ -5345,7 +5650,7 @@ CREATE TABLE flow_events (event_id TEXT PRIMARY KEY);
apply_migrations(&conn).unwrap();
assert_eq!(current_schema_version(&conn).unwrap(), 32);
assert_eq!(current_schema_version(&conn).unwrap(), 33);
assert!(table_exists(&conn, "flow_sources").unwrap());
assert!(table_exists(&conn, "flow_source_revisions").unwrap());
assert!(!table_exists(&conn, "flow_instances").unwrap());
@@ -5412,7 +5717,7 @@ INSERT INTO worker_workdir_attachment_reservations (
apply_migrations(&conn).unwrap();
assert_eq!(current_schema_version(&conn).unwrap(), 32);
assert_eq!(current_schema_version(&conn).unwrap(), 33);
let repositories_sql: String = conn
.query_row(
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'repositories'",
@@ -5592,7 +5897,7 @@ INSERT INTO workdir_registry (
let db = dir.path().join("control-plane.sqlite");
let store = SqliteWorkspaceStore::open(&db).unwrap();
assert_eq!(store.schema_version().await.unwrap(), 32);
assert_eq!(store.schema_version().await.unwrap(), 33);
assert!(
!store
.with_conn(|conn| table_exists(conn, "worker_workspace_credentials"))
@@ -5609,7 +5914,7 @@ INSERT INTO workdir_registry (
store.upsert_workspace(&record).await.unwrap();
let reopened = SqliteWorkspaceStore::open(&db).unwrap();
assert_eq!(reopened.schema_version().await.unwrap(), 32);
assert_eq!(reopened.schema_version().await.unwrap(), 33);
assert_eq!(
reopened.get_workspace("local-dev").await.unwrap(),
Some(record)
@@ -6156,7 +6461,7 @@ INSERT INTO workdir_registry (
.unwrap();
let store = SqliteWorkspaceStore::from_connection(conn).unwrap();
assert_eq!(store.schema_version().await.unwrap(), 32);
assert_eq!(store.schema_version().await.unwrap(), 33);
store
.with_conn(|conn| {
@@ -6345,7 +6650,7 @@ CREATE TABLE ticket_assignment_operations (
#[tokio::test]
async fn repository_records_round_trip() {
let store = SqliteWorkspaceStore::in_memory().unwrap();
assert_eq!(store.schema_version().await.unwrap(), 32);
assert_eq!(store.schema_version().await.unwrap(), 33);
let workspace = WorkspaceRecord {
workspace_id: "local-dev".to_string(),
owner_account_id: None,
@@ -6411,7 +6716,7 @@ CREATE TABLE ticket_assignment_operations (
#[tokio::test]
async fn memory_authority_records_round_trip_and_close_staging() {
let store = SqliteWorkspaceStore::in_memory().unwrap();
assert_eq!(store.schema_version().await.unwrap(), 32);
assert_eq!(store.schema_version().await.unwrap(), 33);
let workspace = WorkspaceRecord {
workspace_id: "local-dev".to_string(),
owner_account_id: None,
@@ -6671,10 +6976,110 @@ CREATE TABLE ticket_assignment_operations (
);
}
#[tokio::test]
async fn worker_control_grants_are_idempotent_scoped_and_revocable() {
let store = SqliteWorkspaceStore::in_memory().unwrap();
store
.upsert_workspace(&WorkspaceRecord {
workspace_id: "workspace-control".to_string(),
owner_account_id: None,
display_name: "Control grants".to_string(),
state: "active".to_string(),
created_at: "2026-07-27T00:00:00Z".to_string(),
updated_at: "2026-07-27T00:00:00Z".to_string(),
})
.await
.unwrap();
let worker_record = |worker_id: &str, display_name: &str| WorkerRegistryRecord {
workspace_id: "workspace-control".to_string(),
worker: RuntimeWorkerRef::new("runtime-a", worker_id),
display_name: display_name.to_string(),
profile: None,
retention_state: "normal".to_string(),
transcript_ref: None,
session_ref: None,
summary_ref: None,
diagnostics_ref: None,
created_at: "2026-07-27T00:00:00Z".to_string(),
updated_at: "2026-07-27T00:00:00Z".to_string(),
};
let controller_record = worker_record("1", "Controller");
let subject_record = worker_record("2", "Subject");
store.upsert_worker_registry(&controller_record).unwrap();
store.upsert_worker_registry(&subject_record).unwrap();
let grant = WorkerControlGrantRecord {
workspace_id: "workspace-control".to_string(),
grant_id: "grant-1".to_string(),
controller: controller_record.worker.clone(),
subject: subject_record.worker.clone(),
relation: "spawned".to_string(),
origin: "worker_spawn".to_string(),
permissions: vec![
"observe".to_string(),
"send_input".to_string(),
"stop".to_string(),
],
operation_id: "spawn-op-1".to_string(),
created_at: "2026-07-27T00:00:01Z".to_string(),
revoked_at: None,
};
assert_eq!(store.create_worker_control_grant(&grant).unwrap(), grant);
assert_eq!(store.create_worker_control_grant(&grant).unwrap(), grant);
assert_eq!(
store
.list_active_worker_control_grants(
"workspace-control",
&controller_record.worker,
10,
)
.unwrap(),
vec![grant.clone()]
);
assert_eq!(
store
.get_active_worker_control_grant(
"workspace-control",
&controller_record.worker,
&subject_record.worker,
)
.unwrap(),
Some(grant.clone())
);
let conflicting_replay = WorkerControlGrantRecord {
subject: controller_record.worker.clone(),
..grant.clone()
};
assert!(matches!(
store.create_worker_control_grant(&conflicting_replay),
Err(Error::InvalidInput(_))
));
assert!(
store
.revoke_worker_control_grant(
"workspace-control",
&grant.grant_id,
"2026-07-27T00:00:02Z",
)
.unwrap()
);
assert!(
store
.list_active_worker_control_grants(
"workspace-control",
&controller_record.worker,
10,
)
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn account_and_login_records_round_trip() {
let store = SqliteWorkspaceStore::in_memory().unwrap();
assert_eq!(store.schema_version().await.unwrap(), 32);
assert_eq!(store.schema_version().await.unwrap(), 33);
let now = "2026-07-22T00:00:00Z".to_string();
let account = AccountRecord {
account_id: "acct-user-alice".to_string(),