#![forbid(unsafe_code)]
use std::sync::Arc;
use serde_json::Value;
mod ast;
mod builtins;
mod dispatch;
mod interp;
mod lexer;
pub mod limits;
mod parser;
pub mod value;
pub use limits::{
DEFAULT_MAX_CAPABILITY_CALLS, DEFAULT_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_LINES,
DEFAULT_MAX_RECURSION_DEPTH, DEFAULT_MAX_STEPS, DEFAULT_MAX_VALUE_BYTES, DEFAULT_TIMEOUT,
Limits,
};
use dekopon_core::SecretUseProposal;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CapabilityDescription {
pub capability: String,
pub description: String,
pub input_schema: Value,
}
#[derive(Clone, Debug, PartialEq)]
pub enum CapabilityCallResult {
Succeeded(Value),
Denied {
reason: String,
},
Failed {
error: String,
},
NotFound,
}
#[derive(Clone, Debug, PartialEq)]
pub enum CommandRun {
Proposed {
capability: String,
input: Value,
},
Rendered {
stdout: String,
stderr: String,
status: u8,
},
Failed {
message: String,
},
Errored {
message: String,
},
Denied {
reason: String,
},
}
pub trait CapabilityInvoker {
fn granted(&self) -> Vec<String>;
fn is_granted(&self, capability: &str) -> bool {
self.granted().iter().any(|granted| granted == capability)
}
fn grants_namespace(&self, namespace: &str) -> bool {
self.granted().iter().any(|granted| {
granted
.split('.')
.next()
.is_some_and(|candidate| candidate == namespace)
})
}
fn command_words(&self) -> Vec<String> {
Vec::new()
}
fn has_command_word(&self, word: &str) -> bool {
self.command_words()
.iter()
.any(|candidate| candidate == word)
}
fn run_command(&self, word: &str, argv: &[String], stdin: Option<&str>) -> Option<CommandRun> {
let _ = (word, argv, stdin);
None
}
fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
let _ = capability;
None
}
fn invoke(
&self,
capability: &str,
input: Value,
secret_use: Option<SecretUseProposal>,
) -> CapabilityCallResult;
}
#[must_use]
pub fn secret_use_unsupported() -> CapabilityCallResult {
CapabilityCallResult::Denied {
reason: "secret references require a broker-backed capability".to_owned(),
}
}
impl<T: CapabilityInvoker + ?Sized> CapabilityInvoker for Arc<T> {
fn granted(&self) -> Vec<String> {
self.as_ref().granted()
}
fn is_granted(&self, capability: &str) -> bool {
self.as_ref().is_granted(capability)
}
fn grants_namespace(&self, namespace: &str) -> bool {
self.as_ref().grants_namespace(namespace)
}
fn command_words(&self) -> Vec<String> {
self.as_ref().command_words()
}
fn has_command_word(&self, word: &str) -> bool {
self.as_ref().has_command_word(word)
}
fn run_command(&self, word: &str, argv: &[String], stdin: Option<&str>) -> Option<CommandRun> {
self.as_ref().run_command(word, argv, stdin)
}
fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
self.as_ref().describe(capability)
}
fn invoke(
&self,
capability: &str,
input: Value,
secret_use: Option<SecretUseProposal>,
) -> CapabilityCallResult {
self.as_ref().invoke(capability, input, secret_use)
}
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExitCode(u8);
impl ExitCode {
pub const SUCCESS: Self = Self(0);
pub const FAILURE: Self = Self(1);
pub const SYNTAX: Self = Self(2);
pub const TIMEOUT: Self = Self(124);
pub const DENIED: Self = Self(126);
pub const NOT_FOUND: Self = Self(127);
#[must_use]
pub fn from_script_exit(status: i64) -> Self {
Self(u8::try_from(status.rem_euclid(256)).unwrap_or(0))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
#[must_use]
pub const fn from_capability_result(result: &CapabilityCallResult) -> Self {
match result {
CapabilityCallResult::Succeeded(_) => Self::SUCCESS,
CapabilityCallResult::Failed { .. } => Self::FAILURE,
CapabilityCallResult::Denied { .. } => Self::DENIED,
CapabilityCallResult::NotFound => Self::NOT_FOUND,
}
}
}
impl From<ExitCode> for u8 {
fn from(code: ExitCode) -> Self {
code.0
}
}
impl From<u8> for ExitCode {
fn from(code: u8) -> Self {
Self(code)
}
}
impl std::fmt::Display for ExitCode {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}", self.0)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScriptOutcome {
pub output: String,
pub exit_code: ExitCode,
pub truncated: bool,
pub capability_calls: u32,
pub steps: u64,
}
#[derive(Clone, Debug, Default)]
pub struct Interpreter {
limits: Limits,
curl_capability: Option<String>,
}
impl Interpreter {
#[must_use]
pub fn new(limits: Limits) -> Self {
Self {
limits,
curl_capability: None,
}
}
#[must_use]
pub fn with_curl_capability(mut self, capability: Option<String>) -> Self {
self.curl_capability = capability;
self
}
#[must_use]
pub fn limits(&self) -> Limits {
self.limits
}
pub fn run(&self, script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
interp::run(
script,
invoker,
self.limits,
self.curl_capability.as_deref(),
)
}
}
pub fn run(script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
Interpreter::new(Limits::default()).run(script, invoker)
}
#[must_use]
pub fn abandoned_filter_workers() -> usize {
builtins::jq::abandoned_workers()
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use dekopon_core::{SecretDrn, SecretUseProposal};
use serde_json::{Value, json};
use super::{
CapabilityCallResult, CapabilityDescription, CapabilityInvoker, CommandRun, ExitCode,
};
#[derive(Default)]
struct RecordingInvoker {
secret_uses: Mutex<Vec<Option<SecretUseProposal>>>,
}
impl CapabilityInvoker for RecordingInvoker {
fn granted(&self) -> Vec<String> {
vec!["echo.echo".to_owned()]
}
fn is_granted(&self, capability: &str) -> bool {
capability == "gh.pr-view"
}
fn grants_namespace(&self, namespace: &str) -> bool {
namespace == "gh"
}
fn command_words(&self) -> Vec<String> {
vec!["gh".to_owned()]
}
fn has_command_word(&self, word: &str) -> bool {
word == "gh-extra"
}
fn run_command(
&self,
word: &str,
argv: &[String],
stdin: Option<&str>,
) -> Option<CommandRun> {
Some(CommandRun::Proposed {
capability: word.to_owned(),
input: json!({ "argv": argv, "stdin": stdin }),
})
}
fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
Some(CapabilityDescription {
capability: capability.to_owned(),
description: "recorded".to_owned(),
input_schema: json!({"type": "object"}),
})
}
fn invoke(
&self,
_capability: &str,
input: Value,
secret_use: Option<SecretUseProposal>,
) -> CapabilityCallResult {
self.secret_uses
.lock()
.expect("recorded secret uses")
.push(secret_use);
CapabilityCallResult::Succeeded(input)
}
}
fn proposal() -> SecretUseProposal {
SecretUseProposal::HttpBearer {
secret: "drn:com.xrl:secret:prod:api/token"
.parse::<SecretDrn>()
.expect("canonical DRN"),
}
}
#[test]
fn an_arc_hands_a_secret_use_proposal_to_the_invoker_behind_it_unchanged() {
let inner = Arc::new(RecordingInvoker::default());
let shared: Arc<dyn CapabilityInvoker> = Arc::clone(&inner) as Arc<dyn CapabilityInvoker>;
assert_eq!(
shared.invoke("http-probe.fetch", json!({"url": "https://x"}), None),
CapabilityCallResult::Succeeded(json!({"url": "https://x"}))
);
assert_eq!(
shared.invoke("http-probe.fetch", json!({}), Some(proposal())),
CapabilityCallResult::Succeeded(json!({}))
);
assert_eq!(
*inner.secret_uses.lock().expect("recorded secret uses"),
vec![None, Some(proposal())],
"the pointer altered a proposal on its way to the invoker behind it"
);
}
#[test]
fn an_arc_forwards_the_defaulted_methods_instead_of_inheriting_their_defaults() {
let shared: Arc<dyn CapabilityInvoker> = Arc::new(RecordingInvoker::default());
assert_eq!(shared.granted(), vec!["echo.echo".to_owned()]);
assert!(shared.is_granted("gh.pr-view"));
assert!(shared.grants_namespace("gh"));
assert_eq!(shared.command_words(), vec!["gh".to_owned()]);
assert!(shared.has_command_word("gh-extra"));
assert_eq!(
shared.run_command("gh", &["pr".to_owned()], Some("piped")),
Some(CommandRun::Proposed {
capability: "gh".to_owned(),
input: json!({"argv": ["pr"], "stdin": "piped"}),
})
);
assert_eq!(
shared.describe("gh.pr-view").map(|it| it.description),
Some("recorded".to_owned())
);
}
#[test]
fn exit_codes_follow_the_documented_mapping() {
assert_eq!(ExitCode::SUCCESS.get(), 0);
assert_eq!(ExitCode::FAILURE.get(), 1);
assert_eq!(ExitCode::SYNTAX.get(), 2);
assert_eq!(ExitCode::TIMEOUT.get(), 124);
assert_eq!(ExitCode::DENIED.get(), 126);
assert_eq!(ExitCode::NOT_FOUND.get(), 127);
}
#[test]
fn capability_results_map_onto_distinct_codes() {
assert_eq!(
ExitCode::from_capability_result(&CapabilityCallResult::Succeeded(
serde_json::Value::Null
)),
ExitCode::SUCCESS
);
assert_eq!(
ExitCode::from_capability_result(&CapabilityCallResult::Failed {
error: "boom".to_owned()
}),
ExitCode::FAILURE
);
assert_eq!(
ExitCode::from_capability_result(&CapabilityCallResult::Denied {
reason: "policy".to_owned()
}),
ExitCode::DENIED
);
assert_eq!(
ExitCode::from_capability_result(&CapabilityCallResult::NotFound),
ExitCode::NOT_FOUND
);
}
#[test]
fn script_exit_wraps_like_bash() {
assert_eq!(ExitCode::from_script_exit(0).get(), 0);
assert_eq!(ExitCode::from_script_exit(7).get(), 7);
assert_eq!(ExitCode::from_script_exit(256).get(), 0);
assert_eq!(ExitCode::from_script_exit(257).get(), 1);
assert_eq!(ExitCode::from_script_exit(-1).get(), 255);
}
}