cpa_plugin/store/
home_sync.rs1use std::collections::BTreeMap;
4
5use super::auth::{ResolvedAuthConfig, validate_resolved_auth_config};
6use super::manifest::Manifest;
7use super::registry::normalize_install_plan;
8use super::url;
9use crate::go_struct;
10use crate::gojson::GoTime;
11
12pub const PLUGIN_SYNC_SCHEMA_VERSION: isize = 1;
13
14go_struct! {
15 pub struct PluginSyncRequest("pluginstore.PluginSyncRequest") {
16 "schema_version" => schema_version: isize,
17 "goos" => goos: String,
18 "goarch" => goarch: String,
19 "installed_versions" omitempty => installed_versions: BTreeMap<String, String>,
20 }
21}
22
23go_struct! {
24 pub struct PluginSyncItem("pluginstore.PluginSyncItem") {
25 "manifest" => manifest: Manifest,
26 "auth" omitempty => auth: Vec<ResolvedAuthConfig>,
27 }
28}
29
30go_struct! {
31 pub struct PluginSyncResponse("pluginstore.PluginSyncResponse") {
32 "schema_version" => schema_version: isize,
33 "expires_at" => expires_at: GoTime,
34 "items" => items: Vec<PluginSyncItem>,
35 }
36}
37
38impl PluginSyncResponse {
39 pub fn validate(&self, now: chrono::DateTime<chrono::FixedOffset>) -> Result<(), String> {
41 if self.schema_version != PLUGIN_SYNC_SCHEMA_VERSION {
42 return Err(format!(
43 "unsupported plugin sync schema_version {}",
44 self.schema_version
45 ));
46 }
47 let Some(expires_at) = self.expires_at.0 else {
48 return Err("plugin sync response missing expires_at".into());
49 };
50 if now >= expires_at {
51 return Err("plugin sync response expired".into());
52 }
53 let mut seen: Vec<&str> = Vec::new();
54 for (index, item) in self.items.iter().enumerate() {
55 item.manifest
56 .validate()
57 .map_err(|e| format!("plugin sync item {index}: {e}"))?;
58 validate_manifest_urls(&item.manifest).map_err(|e| format!("plugin sync item {index}: {e}"))?;
59 let id = item.manifest.id.trim();
60 if seen.contains(&id) {
61 return Err(format!(
62 "plugin sync response contains duplicate plugin {}",
63 cpa_common::gostr::quote(id)
64 ));
65 }
66 seen.push(id);
67 for (auth_index, auth) in item.auth.iter().enumerate() {
68 validate_resolved_auth_config(auth)
69 .map_err(|e| format!("plugin sync item {index} auth {auth_index}: {e}"))?;
70 }
71 }
72 Ok(())
73 }
74}
75
76fn validate_manifest_urls(manifest: &Manifest) -> Result<(), String> {
79 if manifest.install_type() != super::registry::INSTALL_TYPE_DIRECT {
80 return Ok(());
81 }
82 let plan = normalize_install_plan(&manifest.install);
83 if plan.artifacts.is_empty() {
84 return Err("direct plugin sync manifest requires pinned artifacts".into());
85 }
86 for (index, artifact) in plan.artifacts.iter().enumerate() {
87 if !url::parse(artifact.url.trim()).is_some_and(|u| u.scheme.eq_ignore_ascii_case("https")) {
88 return Err(format!("direct plugin sync artifact {index} must use https"));
89 }
90 }
91 Ok(())
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
100 use crate::gojson;
101 use crate::store::{Artifact, InstallPlan, Secret};
102
103 const SHA: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
104
105 fn now() -> chrono::DateTime<chrono::FixedOffset> {
106 chrono::Utc::now().fixed_offset()
107 }
108
109 fn response(url: &str, auth: Vec<ResolvedAuthConfig>) -> PluginSyncResponse {
110 PluginSyncResponse {
111 schema_version: PLUGIN_SYNC_SCHEMA_VERSION,
112 expires_at: GoTime(Some(now() + chrono::Duration::minutes(1))),
113 items: vec![PluginSyncItem {
114 manifest: Manifest {
115 schema_version: 2,
116 id: "sample".into(),
117 version: "1.0.0".into(),
118 install: InstallPlan {
119 install_type: "direct".into(),
120 artifacts: vec![Artifact {
121 goos: "linux".into(),
122 goarch: "amd64".into(),
123 url: url.into(),
124 sha256: SHA.into(),
125 size: 0,
126 }],
127 },
128 ..Default::default()
129 },
130 auth,
131 }],
132 }
133 }
134
135 fn bearer(matches: &str, apply_to: &[&str]) -> Vec<ResolvedAuthConfig> {
136 vec![ResolvedAuthConfig {
137 matches: matches.into(),
138 apply_to: apply_to.iter().map(|s| s.to_string()).collect(),
139 auth_type: "bearer".into(),
140 token: Secret(b"temporary-token".to_vec()),
141 ..Default::default()
142 }]
143 }
144
145 #[test]
146 fn plugin_sync_response_validates_and_clears_resolved_auth() {
147 let response = response(
148 "https://downloads.example/sample.zip",
149 bearer("https://downloads.example/", &[]),
150 );
151 response.validate(now()).unwrap();
152 }
153
154 #[test]
155 fn plugin_sync_response_json_keeps_secrets_out_of_plain_text() {
156 let response = PluginSyncResponse {
157 schema_version: PLUGIN_SYNC_SCHEMA_VERSION,
158 expires_at: GoTime(Some(now() + chrono::Duration::minutes(1))),
159 items: vec![PluginSyncItem {
160 auth: vec![ResolvedAuthConfig {
161 token: Secret(b"temporary-token".to_vec()),
162 ..Default::default()
163 }],
164 ..Default::default()
165 }],
166 };
167 let raw = gojson::to_vec(&response);
168 assert!(!String::from_utf8_lossy(&raw).contains("temporary-token"));
169 let decoded: PluginSyncResponse = gojson::from_slice(&raw).unwrap();
170 assert_eq!(decoded.items[0].auth[0].token.0, b"temporary-token");
171 }
172
173 #[test]
174 fn plugin_sync_response_rejects_expired_plan() {
175 let response = PluginSyncResponse {
176 schema_version: PLUGIN_SYNC_SCHEMA_VERSION,
177 expires_at: GoTime(Some(now() - chrono::Duration::seconds(1))),
178 items: Vec::new(),
179 };
180 assert!(response.validate(now()).is_err());
181 }
182
183 #[test]
184 fn plugin_sync_response_rejects_insecure_resolved_auth_match() {
185 let response = response(
186 "https://downloads.example/sample.zip",
187 bearer("http://downloads.example/", &[]),
188 );
189 assert!(response.validate(now()).is_err());
190 }
191
192 #[test]
193 fn plugin_sync_response_rejects_http_artifact() {
194 let response = response("http://downloads.example/sample.zip", Vec::new());
195 assert!(response.validate(now()).is_err());
196 }
197
198 #[test]
199 fn plugin_sync_response_rejects_http_artifact_with_resolved_auth() {
200 let response = response(
201 "http://downloads.example/sample.zip",
202 bearer("https://downloads.example/", &[crate::store::REQUEST_KIND_ARTIFACT]),
203 );
204 assert!(response.validate(now()).is_err());
205 }
206
207 #[test]
208 fn plugin_sync_response_rejects_artifact_url_credentials() {
209 let response = response("https://user:password@downloads.example/sample.zip", Vec::new());
210 let error = response.validate(now()).unwrap_err();
211 assert!(!error.contains("password"), "{error}");
212 }
213}