keel-exec-core 0.0.8

Keel space lifecycle — Policy + Enforce + Record orchestration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use crate::error::{KeelError, KeelResult};
use chrono::Utc;
use keel_enforce::{EnforceBackend, SpawnRequest, SpawnedProcess};
use keel_policy::{Policy, SpaceId};
use keel_record::{
    default_space_sink, space_policy_path, EventKind, MemorySink, MultiSink, RecordEvent,
    RecordSink,
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, warn};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpaceState {
    Creating,
    Open,
    Destroying,
    Destroyed,
}

/// Options for opening a space.
#[derive(Debug, Clone)]
pub struct SpaceOptions {
    /// Persist events to `~/.keel/spaces/<id>/events.jsonl` (default true).
    pub persist_events: bool,
    /// Also keep an in-memory copy of events (default false; true when useful for tests/CLI --trace).
    pub memory_events: bool,
    /// Write `policy.json` next to events (default true when persist_events).
    pub persist_policy: bool,
    /// If true, missing credential sources fail spawn (default false).
    pub strict_credentials: bool,
    /// If true, emit `Violation` events when check_fs / check_egress denies (default true).
    pub record_violations: bool,
}

impl Default for SpaceOptions {
    fn default() -> Self {
        Self {
            persist_events: true,
            memory_events: false,
            persist_policy: true,
            strict_credentials: false,
            record_violations: true,
        }
    }
}

/// Live execution space: one policy, one backend, one record stream.
pub struct Space {
    id: SpaceId,
    policy: Policy,
    backend: Arc<dyn EnforceBackend>,
    sink: Arc<dyn RecordSink>,
    events_path: Option<PathBuf>,
    opts: SpaceOptions,
    state: RwLock<SpaceState>,
}

/// Public handle returned after create.
#[derive(Clone)]
pub struct SpaceHandle {
    inner: Arc<Space>,
}

impl SpaceHandle {
    pub fn id(&self) -> &SpaceId {
        &self.inner.id
    }

    pub fn policy(&self) -> &Policy {
        &self.inner.policy
    }

    /// Path to JSONL events when persistence is enabled.
    pub fn events_path(&self) -> Option<&Path> {
        self.inner.events_path.as_deref()
    }

    pub fn backend_info(&self) -> keel_enforce::BackendInfo {
        self.inner.backend.info()
    }

    pub async fn state(&self) -> SpaceState {
        *self.inner.state.read().await
    }

    pub async fn check_fs(&self, path: &Path, write: bool) -> KeelResult<bool> {
        self.inner.ensure_open().await?;
        if self.inner.policy.is_expired(Utc::now()) {
            return Err(keel_enforce::EnforceError::PolicyExpired.into());
        }
        let allowed = self
            .inner
            .backend
            .check_fs(&self.inner.policy, path, write)
            .await?;
        let op = if write { "write" } else { "read" };
        self.inner
            .emit(EventKind::FsAccess {
                path: path.to_path_buf(),
                operation: op.into(),
                allowed,
            })
            .await?;
        if !allowed && self.inner.opts.record_violations {
            self.inner
                .emit(EventKind::Violation {
                    operation: op.into(),
                    target: path.display().to_string(),
                    detail: Some("fs policy soft deny".into()),
                })
                .await?;
        }
        Ok(allowed)
    }

    /// Check whether dialing `host:port` is allowed by the space network policy.
    pub async fn check_egress(&self, host: &str, port: u16) -> KeelResult<bool> {
        self.inner.ensure_open().await?;
        if self.inner.policy.is_expired(Utc::now()) {
            return Err(keel_enforce::EnforceError::PolicyExpired.into());
        }
        let decision = keel_policy::check_egress(&self.inner.policy.network, host, port);
        let allowed = decision.is_allowed();
        self.inner
            .emit(EventKind::NetDial {
                host: host.to_string(),
                port: Some(port),
                allowed,
            })
            .await?;
        if !allowed && self.inner.opts.record_violations {
            let detail = match &decision {
                keel_policy::EgressDecision::Deny { reason } => Some(reason.clone()),
                keel_policy::EgressDecision::Allow => None,
            };
            self.inner
                .emit(EventKind::Violation {
                    operation: "connect".into(),
                    target: format!("{host}:{port}"),
                    detail,
                })
                .await?;
        }
        Ok(allowed)
    }

    pub async fn spawn(&self, mut req: SpawnRequest) -> KeelResult<SpawnedProcess> {
        self.inner.ensure_open().await?;
        if self.inner.policy.is_expired(Utc::now()) {
            return Err(keel_enforce::EnforceError::PolicyExpired.into());
        }

        // JIT credentials: resolve from parent env/files, inject into child env.
        let resolved = keel_enforce::resolve_credentials(
            &self.inner.policy,
            self.inner.opts.strict_credentials,
        )?;
        let issued = keel_enforce::inject_into_env(&mut req.env, &resolved);
        for name in &issued {
            self.inner
                .emit(EventKind::CredentialIssued {
                    name: name.clone(),
                })
                .await?;
        }
        // Drop secret material from this task asap (child already has env copy).
        keel_enforce::revoke_resolved(resolved);

        let child = self
            .inner
            .backend
            .spawn(
                &self.inner.id,
                &self.inner.policy,
                req,
                self.inner.sink.clone(),
            )
            .await?;
        Ok(child)
    }

    /// Open a **new** space for a subtask with a policy that can only shrink reach.
    ///
    /// This is the per-task rebind primitive: never mutates the parent space.
    pub async fn open_task(
        &self,
        spec: keel_policy::TaskSpec,
        backend: Arc<dyn EnforceBackend>,
        opts: SpaceOptions,
    ) -> KeelResult<SpaceHandle> {
        self.inner.ensure_open().await?;
        let child_policy = keel_policy::narrow_policy(&self.inner.policy, spec)?;
        Space::create_with(child_policy, backend, opts).await
    }

    /// Convenience: open a task in a git/directory worktree under the parent workspace.
    pub async fn open_task_in_worktree(
        &self,
        spec: keel_policy::TaskSpec,
        opts: SpaceOptions,
    ) -> KeelResult<SpaceHandle> {
        let backend = Arc::new(keel_enforce::WorktreeBackend::new());
        self.open_task(spec, backend, opts).await
    }

    pub async fn run_capture(
        &self,
        program: &str,
        args: &[&str],
    ) -> KeelResult<std::process::Output> {
        let req = SpawnRequest::new(program).args(args.iter().map(|s| s.to_string()));
        let spawned = self.spawn(req).await?;
        let output = spawned.child.wait_with_output().await?;
        Ok(output)
    }

    pub async fn destroy(self) -> KeelResult<()> {
        self.inner.destroy_inner().await
    }
}

impl Space {
    /// Create a space with default persistence (`~/.keel/spaces/<id>/events.jsonl`).
    pub async fn create(
        policy: Policy,
        backend: Arc<dyn EnforceBackend>,
    ) -> KeelResult<SpaceHandle> {
        Self::create_with(policy, backend, SpaceOptions::default()).await
    }

    /// Create with explicit options and optional pre-built sink override.
    pub async fn create_with(
        policy: Policy,
        backend: Arc<dyn EnforceBackend>,
        opts: SpaceOptions,
    ) -> KeelResult<SpaceHandle> {
        Self::create_with_sink(policy, backend, opts, None).await
    }

    /// Full constructor: optional sink override (e.g. tests inject `MemorySink` only).
    pub async fn create_with_sink(
        policy: Policy,
        backend: Arc<dyn EnforceBackend>,
        opts: SpaceOptions,
        sink_override: Option<Arc<dyn RecordSink>>,
    ) -> KeelResult<SpaceHandle> {
        policy.validate()?;
        if policy.is_expired(Utc::now()) {
            return Err(keel_enforce::EnforceError::PolicyExpired.into());
        }

        let id = SpaceId::new();
        let mut events_path = None;

        let sink: Arc<dyn RecordSink> = if let Some(s) = sink_override {
            s
        } else {
            let mut parts: Vec<Arc<dyn RecordSink>> = Vec::new();
            if opts.memory_events {
                parts.push(Arc::new(MemorySink::new()));
            }
            if opts.persist_events {
                let jsonl = default_space_sink(&id).await?;
                events_path = Some(jsonl.path().to_path_buf());
                parts.push(Arc::new(jsonl));
            }
            if parts.is_empty() {
                // Always have at least a memory sink so events are not dropped.
                parts.push(Arc::new(MemorySink::new()));
            }
            if parts.len() == 1 {
                parts.pop().unwrap()
            } else {
                Arc::new(MultiSink::new(parts))
            }
        };

        if opts.persist_policy && opts.persist_events {
            let path = space_policy_path(&id);
            if let Some(parent) = path.parent() {
                let _ = std::fs::create_dir_all(parent);
            }
            if let Ok(json) = policy.to_json() {
                let _ = std::fs::write(&path, json);
            }
        }

        let space = Arc::new(Space {
            id: id.clone(),
            policy: policy.clone(),
            backend: backend.clone(),
            sink: sink.clone(),
            events_path,
            opts: opts.clone(),
            state: RwLock::new(SpaceState::Creating),
        });

        space
            .emit(EventKind::SpaceCreated {
                backend: backend.info().name.to_string(),
                label: policy.label.clone(),
            })
            .await?;
        space
            .emit(EventKind::PolicyBound {
                label: policy.label.clone(),
            })
            .await?;

        backend.apply(&policy, sink.clone()).await?;

        *space.state.write().await = SpaceState::Open;
        info!(
            space_id = %id,
            policy_id = %policy.id,
            backend = backend.info().name,
            events = ?space.events_path,
            "keel space open"
        );

        Ok(SpaceHandle { inner: space })
    }

    async fn ensure_open(&self) -> KeelResult<()> {
        match *self.state.read().await {
            SpaceState::Open => Ok(()),
            SpaceState::Creating => Err(KeelError::NotOpen("creating")),
            SpaceState::Destroying => Err(KeelError::NotOpen("destroying")),
            SpaceState::Destroyed => Err(KeelError::NotOpen("destroyed")),
        }
    }

    async fn emit(&self, event: EventKind) -> KeelResult<()> {
        self.sink
            .emit(RecordEvent::new(
                self.id.clone(),
                self.policy.id.clone(),
                self.policy.task_id.clone(),
                event,
            ))
            .await?;
        Ok(())
    }

    async fn destroy_inner(self: &Arc<Self>) -> KeelResult<()> {
        {
            let mut st = self.state.write().await;
            if matches!(*st, SpaceState::Destroyed | SpaceState::Destroying) {
                return Ok(());
            }
            *st = SpaceState::Destroying;
        }

        for name in keel_enforce::grant_names(&self.policy) {
            let _ = self
                .emit(EventKind::CredentialRevoked { name })
                .await;
        }

        if let Err(e) = self.backend.destroy(&self.policy, self.sink.clone()).await {
            warn!(error = %e, "backend destroy failed");
        }

        self.emit(EventKind::SpaceDestroyed {
            reason: "explicit".into(),
        })
        .await?;
        let _ = self.sink.flush().await;

        *self.state.write().await = SpaceState::Destroyed;
        info!(space_id = %self.id, "keel space destroyed");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use keel_enforce::ProcessGuardBackend;
    use keel_policy::profile_workspace;
    use std::sync::Arc;

    #[tokio::test]
    async fn create_check_destroy_memory_only() {
        let policy = profile_workspace(Path::new("/tmp/keel-test-ws")).unwrap();
        let sink: Arc<dyn RecordSink> = Arc::new(MemorySink::new());
        let backend = Arc::new(ProcessGuardBackend::new());
        let space = Space::create_with_sink(
            policy,
            backend,
            SpaceOptions {
                persist_events: false,
                memory_events: true,
                persist_policy: false,
                ..Default::default()
            },
            Some(sink.clone()),
        )
        .await
        .unwrap();

        assert!(space
            .check_fs(Path::new("/tmp/keel-test-ws/foo.rs"), true)
            .await
            .unwrap());
        space.destroy().await.unwrap();
    }

    #[tokio::test]
    async fn create_persists_events() {
        let dir = tempfile::tempdir().unwrap();
        // Isolate home for this test.
        // SAFETY: test-only env mutation, single-threaded for this var.
        unsafe {
            std::env::set_var("KEEL_HOME", dir.path());
        }
        let policy = profile_workspace(Path::new("/tmp")).unwrap();
        let backend = Arc::new(ProcessGuardBackend::new());
        let space = Space::create(policy, backend).await.unwrap();
        let path = space.events_path().unwrap().to_path_buf();
        space
            .check_fs(Path::new("/tmp/x"), false)
            .await
            .unwrap();
        space.destroy().await.unwrap();
        assert!(path.is_file());
        let body = std::fs::read_to_string(&path).unwrap();
        assert!(body.contains("\"kind\""));
        unsafe {
            std::env::remove_var("KEEL_HOME");
        }
    }

    #[tokio::test]
    async fn spawn_echo() {
        let policy = profile_workspace(Path::new("/tmp")).unwrap();
        let sink: Arc<dyn RecordSink> = Arc::new(MemorySink::new());
        let backend = Arc::new(ProcessGuardBackend::new());
        let space = Space::create_with_sink(
            policy,
            backend,
            SpaceOptions {
                persist_events: false,
                memory_events: true,
                persist_policy: false,
                ..Default::default()
            },
            Some(sink),
        )
        .await
        .unwrap();

        let out = space.run_capture("echo", &["keel-ok"]).await.unwrap();
        assert!(out.status.success());
        assert!(String::from_utf8_lossy(&out.stdout).contains("keel-ok"));
        space.destroy().await.unwrap();
    }
}