Skip to main content

dekopon_provider_sdk/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(test, allow(clippy::unwrap_used))]
3#![cfg_attr(
4    test,
5    allow(
6        clippy::disallowed_methods,
7        clippy::disallowed_types,
8        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
9    )
10)]
11pub use dekopon_capability::EffectKind;
12pub use dekopon_core::{
13    CapabilityId, IdentifierError, ProviderId, RiskLevel, SecretDrn, SecretUseProposal,
14};
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17
18pub use clap;
19pub use schemars;
20
21pub mod asset;
22#[cfg(target_arch = "wasm32")]
23mod clock;
24mod http;
25pub mod provider;
26mod random;
27pub mod signed_download;
28mod spawn;
29mod storage;
30
31pub use provider::{
32    Capability, Code, Failure, Needs, Proposal, Provider, SdkFailure, Stdin, Stdout, Usage,
33    command, manifest, stdin,
34};
35
36#[doc(hidden)]
37pub mod export_bindings {
38    wit_bindgen::generate!({
39        path: "wit",
40        world: "provider-cli",
41        pub_export_macro: true,
42        generate_all,
43    });
44}
45
46#[macro_export]
47macro_rules! export {
48    ($provider:ty) => {
49        struct __DekoponTypedProviderComponent;
50
51        impl $crate::export_bindings::Guest for __DekoponTypedProviderComponent {
52            fn describe() -> ::std::string::String {
53                $crate::__typed_describe::<$provider>()
54            }
55
56            fn invoke(capability: ::std::string::String, input_json: ::std::string::String) -> ::std::result::Result<(), u8> {
57                $crate::__typed_invoke::<$provider>(&capability, &input_json)
58            }
59
60            fn run_command(argv: ::std::vec::Vec<::std::string::String>, stdin_piped: bool) -> ::std::string::String {
61                $crate::__typed_run_command::<$provider>(&argv, stdin_piped)
62            }
63        }
64
65        $crate::export_bindings::export!(__DekoponTypedProviderComponent with_types_in $crate::export_bindings);
66    };
67}
68
69#[doc(hidden)]
70pub fn __typed_describe<P: provider::Provider>() -> String {
71    match provider::manifest::<P>() {
72        Ok(manifest) => {
73            serde_json::to_string(&manifest).unwrap_or_else(|error| describe_fallback(&error))
74        }
75        Err(error) => serde_json::json!({
76            "apiVersion": "dekopon.dev/provider/v1alpha1",
77            "id": "invalid",
78            "description": format!("manifest derivation failed: {error}"),
79            "capabilities": []
80        })
81        .to_string(),
82    }
83}
84
85#[doc(hidden)]
86#[cfg(target_arch = "wasm32")]
87pub fn __typed_invoke<P: provider::Provider>(capability: &str, input: &str) -> Result<(), u8> {
88    provider::invoke::<P>(capability, input).map_err(std::num::NonZeroU8::get)
89}
90
91#[doc(hidden)]
92#[cfg(not(target_arch = "wasm32"))]
93pub fn __typed_invoke<P: provider::Provider>(capability: &str, input: &str) -> Result<(), u8> {
94    let stdio = provider::NativeStdio {
95        stdin: None,
96        stdout: Box::new(std::io::stdout()),
97    };
98    match provider::invoke_native::<P>(capability, input, stdio) {
99        provider::NativeExit { status: 0, .. } => Ok(()),
100        provider::NativeExit { status, .. } => Err(status),
101    }
102}
103
104#[doc(hidden)]
105pub fn __typed_run_command<P: provider::Provider>(argv: &[String], stdin_piped: bool) -> String {
106    serde_json::to_string(&provider::command::<P>(argv, stdin_piped))
107        .unwrap_or_else(|_| RUN_SERIALIZATION_FALLBACK.to_owned())
108}
109
110pub const PROVIDER_WIT: &str = include_str!("../wit/provider.wit");
111
112pub const ASSET_WIT: &str = include_str!("../wit/deps/asset.wit");
113
114#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
115pub enum ProviderApiVersion {
116    #[serde(rename = "dekopon.dev/provider/v1alpha1")]
117    V1Alpha1,
118}
119
120#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
121#[serde(deny_unknown_fields, rename_all = "camelCase")]
122pub struct ProviderManifest {
123    pub api_version: ProviderApiVersion,
124    pub id: ProviderId,
125    pub description: String,
126    pub capabilities: Vec<ProviderCapability>,
127    #[serde(default)]
128    pub command_words: Vec<String>,
129}
130
131#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
132#[serde(deny_unknown_fields, rename_all = "camelCase")]
133pub struct ProviderCapability {
134    pub id: CapabilityId,
135    pub description: String,
136    pub effect: EffectKind,
137    pub risk: RiskLevel,
138    pub input_schema: Value,
139}
140
141#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
142#[serde(deny_unknown_fields, rename_all = "camelCase")]
143pub struct ComponentFailure {
144    pub code: String,
145    pub message: String,
146}
147
148#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
149#[serde(tag = "outcome", rename_all = "camelCase", deny_unknown_fields)]
150pub enum CommandRunOutcome {
151    Proposed {
152        capability: CapabilityId,
153        input: Value,
154        #[serde(rename = "secretUse", default, skip_serializing_if = "Option::is_none")]
155        secret_use: Option<SecretUseProposal>,
156    },
157    Rendered {
158        stdout: String,
159        stderr: String,
160        status: u8,
161    },
162    Failed {
163        error: ComponentFailure,
164    },
165}
166
167const RUN_SERIALIZATION_FALLBACK: &str = r#"{"outcome":"failed","error":{"code":"serialization-failed","message":"command run could not be serialized"}}"#;
168
169fn describe_fallback(error: &serde_json::Error) -> String {
170    serde_json::json!({
171        "apiVersion": "dekopon.dev/provider/v1alpha1",
172        "id": "invalid",
173        "description": format!("manifest serialization failed: {error}"),
174        "capabilities": [],
175    })
176    .to_string()
177}
178
179#[macro_export]
180macro_rules! skills {
181    ($($path:literal),* $(,)?) => {
182        $(
183            #[cfg(target_family = "wasm")]
184            const _: () = {
185                #[used]
186                #[unsafe(link_section = concat!("dekopon:skill/", $path))]
187                static FILE: [u8; include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/skills/", $path)).len()] =
188                    *include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/skills/", $path));
189            };
190        )*
191    };
192}
193
194#[cfg(test)]
195mod tests {
196    use super::{
197        CommandRunOutcome, ComponentFailure, ProviderCapability, ProviderManifest,
198        RUN_SERIALIZATION_FALLBACK, SecretUseProposal, describe_fallback,
199    };
200    use serde_json::json;
201    const UPPER: &str = "cli-probe.upper";
202    const DRN: &str = "drn:secret:api/token";
203    fn upper() -> super::CapabilityId {
204        UPPER.parse().expect("valid capability fixture")
205    }
206    #[test]
207    fn a_manifest_carrying_any_other_unknown_field_is_still_refused() {
208        for unknown in ["idempotency", "retries", "idempotencyKey"] {
209            let error = serde_json::from_value::<ProviderCapability>(json!({
210                "id": UPPER,
211                "description": "Upper-cases text",
212                "effect": "read-only",
213                "risk": "Low",
214                unknown: "whatever",
215                "inputSchema": {"type": "object"},
216            }))
217            .expect_err("an unknown manifest field must be refused");
218
219            assert!(
220                error.to_string().contains(unknown),
221                "the refusal must name {unknown}, got {error}"
222            );
223        }
224    }
225
226    #[test]
227    fn a_proposal_carries_its_secret_use_under_secret_use_and_omits_it_when_absent() {
228        let with = CommandRunOutcome::Proposed {
229            capability: upper(),
230            input: json!({"text": "hello"}),
231            secret_use: Some(SecretUseProposal::HttpBasic {
232                secret: DRN.parse().expect("canonical DRN fixture"),
233                username: "user-a".to_owned(),
234            }),
235        };
236        let encoded = serde_json::to_string(&with).expect("a proposal serializes");
237        assert_eq!(
238            encoded,
239            r#"{"outcome":"proposed","capability":"cli-probe.upper","input":{"text":"hello"},"secretUse":{"kind":"httpBasic","secret":"drn:secret:api/token","username":"user-a"}}"#
240        );
241        assert_eq!(
242            serde_json::from_str::<CommandRunOutcome>(&encoded).expect("the proposal decodes"),
243            with
244        );
245
246        let without = CommandRunOutcome::Proposed {
247            capability: upper(),
248            input: json!({"text": "hello"}),
249            secret_use: None,
250        };
251        let encoded = serde_json::to_string(&without).expect("a proposal serializes");
252        assert_eq!(
253            encoded,
254            r#"{"outcome":"proposed","capability":"cli-probe.upper","input":{"text":"hello"}}"#
255        );
256        assert_eq!(
257            serde_json::from_str::<CommandRunOutcome>(&encoded).expect("the proposal decodes"),
258            without
259        );
260    }
261
262    #[test]
263    fn a_run_outcome_decodes_only_its_own_wire_shape() {
264        let outcome = serde_json::from_str::<CommandRunOutcome>(
265            r#"{"outcome":"rendered","stdout":"Usage: fixture\n","stderr":"","status":0}"#,
266        )
267        .expect("a rendered page parses");
268        assert_eq!(
269            outcome,
270            CommandRunOutcome::Rendered {
271                stdout: "Usage: fixture\n".to_owned(),
272                stderr: String::new(),
273                status: 0,
274            }
275        );
276
277        let error = serde_json::from_str::<CommandRunOutcome>(
278            r#"{"outcome":"resolved","capability":"fixture.run","input":{}}"#,
279        )
280        .expect_err("the retired resolution tag is not a run outcome");
281        assert!(error.to_string().contains("resolved"), "{error}");
282
283        let error = serde_json::from_str::<CommandRunOutcome>(
284            r#"{"outcome":"rendered","stdout":"","stderr":"","status":0,"extra":1}"#,
285        )
286        .expect_err("unknown fields are refused");
287        assert!(error.to_string().contains("extra"), "{error}");
288
289        let error = serde_json::from_str::<CommandRunOutcome>(&format!(
290            r#"{{"outcome":"proposed","capability":"fixture.run","input":{{}},"secretUse":{{"kind":"httpBasic","secret":"{DRN}","username":"user:password"}}}}"#
291        ))
292        .expect_err("a Basic username carrying a colon is refused");
293        assert!(error.to_string().contains("colon-free"), "{error}");
294    }
295
296    #[test]
297    fn describe_fallback_reports_the_serialization_error() {
298        let error = serde_json::from_str::<ProviderManifest>("{").expect_err("malformed manifest");
299        let encoded = describe_fallback(&error);
300
301        let manifest =
302            serde_json::from_str::<ProviderManifest>(&encoded).expect("fallback manifest decodes");
303        assert_eq!(manifest.id.as_str(), "invalid");
304        assert!(
305            manifest
306                .description
307                .starts_with("manifest serialization failed: "),
308            "{}",
309            manifest.description
310        );
311        assert!(manifest.description.contains(&error.to_string()));
312        assert!(manifest.capabilities.is_empty());
313    }
314
315    #[test]
316    fn fallback_literals_decode_into_their_wire_types() {
317        let error = serde_json::from_str::<ProviderManifest>("{").expect_err("malformed manifest");
318        serde_json::from_str::<ProviderManifest>(&describe_fallback(&error))
319            .expect("describe fallback decodes as a manifest");
320
321        let run = serde_json::from_str::<CommandRunOutcome>(RUN_SERIALIZATION_FALLBACK)
322            .expect("run fallback decodes as a command run outcome");
323        assert_eq!(
324            run,
325            CommandRunOutcome::Failed {
326                error: ComponentFailure {
327                    code: "serialization-failed".to_owned(),
328                    message: "command run could not be serialized".to_owned(),
329                },
330            }
331        );
332    }
333}