Skip to main content

cpa_plugin/store/
auth.rs

1//! Store authentication (internal/pluginstore/auth.go): `plugins.store-auth` rules
2//! that add credentials to matching store requests, and the resolved credentials
3//! Home hands out for synced plugins.
4
5use super::registry::{INSTALL_TYPE_DIRECT, INSTALL_TYPE_GITHUB_RELEASE, Plugin, Source, github_repository_parts};
6use super::url;
7use super::{REQUEST_KIND_ARTIFACT, REQUEST_KIND_METADATA, REQUEST_KIND_REGISTRY};
8use crate::go_struct;
9use crate::gojson::{self, GoJson, Node};
10use cpa_core::gostr::GoStr;
11
12pub const AUTH_TYPE_NONE: &str = "none";
13pub const AUTH_TYPE_BEARER: &str = "bearer";
14pub const AUTH_TYPE_BASIC: &str = "basic";
15pub const AUTH_TYPE_HEADER: &str = "header";
16pub const AUTH_TYPE_GITHUB_TOKEN: &str = "github-token";
17
18/// One `plugins.store-auth` rule. Secrets are named by environment variable.
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct AuthConfig {
21    pub matches: String,
22    pub apply_to: Vec<String>,
23    pub auth_type: String,
24    pub token_env: String,
25    pub username_env: String,
26    pub password_env: String,
27    pub header_name: String,
28    pub header_value_env: String,
29    pub allow_insecure: bool,
30}
31
32/// Short-lived credential material, zeroed when dropped (Go `Secret.Clear`).
33#[derive(Clone, Default, PartialEq, Eq)]
34pub struct Secret(pub Vec<u8>);
35
36impl std::fmt::Debug for Secret {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.write_str(if self.0.is_empty() {
39            "Secret(empty)"
40        } else {
41            "Secret(..)"
42        })
43    }
44}
45
46impl Drop for Secret {
47    fn drop(&mut self) {
48        for b in &mut self.0 {
49            // SAFETY: `b` is a valid, aligned, exclusive reference; the volatile store
50            // keeps the zeroing from being optimised away.
51            unsafe { std::ptr::write_volatile(b, 0) };
52        }
53    }
54}
55
56/// `[]byte` in JSON: base64 (Go's encoding of `Secret`).
57impl GoJson for Secret {
58    const GO_TYPE: &'static str = "pluginstore.Secret";
59    fn encode(&self, out: &mut Vec<u8>) {
60        bytes::Bytes::copy_from_slice(&self.0).encode(out);
61    }
62    fn decode_value(v: &Node) -> Result<Self, gojson::DecodeError> {
63        let b = bytes::Bytes::decode_value(v)?;
64        Ok(Self(b.to_vec()))
65    }
66    fn is_empty(&self) -> bool {
67        self.0.is_empty()
68    }
69}
70
71go_struct! {
72    /// A resolved store credential (Home plugin sync).
73    pub struct ResolvedAuthConfig("pluginstore.ResolvedAuthConfig") {
74        "match" omitempty => matches: String,
75        "apply_to" omitempty => apply_to: Vec<String>,
76        "type" omitempty => auth_type: String,
77        "token" omitempty => token: Secret,
78        "username" omitempty => username: Secret,
79        "password" omitempty => password: Secret,
80        "header_name" omitempty => header_name: String,
81        "header_value" omitempty => header_value: Secret,
82    }
83}
84
85/// Go `ValidateResolvedAuthConfig`.
86pub fn validate_resolved_auth_config(item: &ResolvedAuthConfig) -> Result<(), String> {
87    let parsed = match url::parse(item.matches.trim()) {
88        Some(u) if !u.scheme.is_empty() && !u.host.is_empty() => u,
89        _ => return Err("plugin store resolved auth match is invalid".into()),
90    };
91    if !parsed.scheme.eq_ignore_ascii_case("https") {
92        return Err("plugin store resolved auth match must use https".into());
93    }
94    if parsed.has_user || !parsed.raw_query.is_empty() || !parsed.fragment.is_empty() {
95        return Err("plugin store resolved auth match must not contain credentials, query, or fragment".into());
96    }
97    for kind in &item.apply_to {
98        let k = kind.trim().go_lower();
99        if !matches!(
100            k.as_str(),
101            REQUEST_KIND_REGISTRY | REQUEST_KIND_METADATA | REQUEST_KIND_ARTIFACT
102        ) {
103            return Err(format!(
104                "plugin store resolved auth has unsupported apply_to {}",
105                cpa_common::gostr::quote(kind)
106            ));
107        }
108    }
109    match item.auth_type.trim().go_lower().as_str() {
110        "" | AUTH_TYPE_NONE => Ok(()),
111        AUTH_TYPE_BEARER | AUTH_TYPE_GITHUB_TOKEN if item.token.0.is_empty() => {
112            Err("plugin store resolved auth token is empty".into())
113        }
114        AUTH_TYPE_BEARER | AUTH_TYPE_GITHUB_TOKEN => Ok(()),
115        AUTH_TYPE_BASIC if item.username.0.is_empty() || item.password.0.is_empty() => {
116            Err("plugin store resolved basic auth is incomplete".into())
117        }
118        AUTH_TYPE_BASIC => Ok(()),
119        AUTH_TYPE_HEADER => {
120            if item.header_name.trim().is_empty() || item.header_name.contains(['\r', '\n', ':']) {
121                return Err("plugin store resolved auth header name is invalid".into());
122            }
123            if item.header_value.0.is_empty() || item.header_value.0.iter().any(|b| matches!(b, b'\r' | b'\n')) {
124                return Err("plugin store resolved auth header value is invalid".into());
125            }
126            Ok(())
127        }
128        _ => Err(format!(
129            "unsupported plugin store resolved auth type {}",
130            cpa_common::gostr::quote(&item.auth_type)
131        )),
132    }
133}
134
135/// Go `NormalizeAuthConfigs`: trimmed, `none` by default, rules without a match
136/// dropped, `apply-to` lower-cased and deduplicated.
137pub fn normalize_auth_configs(auth: &[AuthConfig]) -> Vec<AuthConfig> {
138    auth.iter()
139        .filter_map(|item| {
140            let mut item = item.clone();
141            item.matches = item.matches.trim().into();
142            item.auth_type = item.auth_type.trim().go_lower();
143            for field in [
144                &mut item.token_env,
145                &mut item.username_env,
146                &mut item.password_env,
147                &mut item.header_name,
148                &mut item.header_value_env,
149            ] {
150                *field = field.trim().into();
151            }
152            if item.auth_type.is_empty() {
153                item.auth_type = AUTH_TYPE_NONE.into();
154            }
155            if item.matches.is_empty() {
156                return None;
157            }
158            let mut apply_to: Vec<String> = Vec::new();
159            for value in &item.apply_to {
160                let value = value.trim().go_lower();
161                if !value.is_empty() && !apply_to.contains(&value) {
162                    apply_to.push(value);
163                }
164            }
165            item.apply_to = apply_to;
166            Some(item)
167        })
168        .collect()
169}
170
171fn env(name: &str) -> String {
172    std::env::var(name).unwrap_or_default().trim().to_owned()
173}
174
175/// Go `AuthConfigured`: a matching rule whose credentials are present.
176pub fn auth_configured(auth: &[AuthConfig], request_url: &str, kind: &str) -> bool {
177    let Some(item) = matching_auth_config(auth, request_url, kind) else {
178        return false;
179    };
180    match item.auth_type.trim().go_lower().as_str() {
181        AUTH_TYPE_BEARER | AUTH_TYPE_GITHUB_TOKEN => !env(&item.token_env).is_empty(),
182        AUTH_TYPE_BASIC => !env(&item.username_env).is_empty() && !env(&item.password_env).is_empty(),
183        AUTH_TYPE_HEADER => !item.header_name.is_empty() && !env(&item.header_value_env).is_empty(),
184        _ => false,
185    }
186}
187
188/// Go `PluginAuthConfigured`: a credential applies to the plugin's registry, its
189/// artifacts, or its GitHub release metadata.
190pub fn plugin_auth_configured(source: &Source, plugin: &Plugin, auth: &[AuthConfig]) -> bool {
191    if auth_configured(auth, &source.url, REQUEST_KIND_REGISTRY) {
192        return true;
193    }
194    match super::registry::plugin_install_type(plugin).as_str() {
195        INSTALL_TYPE_DIRECT => super::registry::plugin_artifacts(plugin)
196            .iter()
197            .any(|a| auth_configured(auth, &a.url, REQUEST_KIND_ARTIFACT)),
198        INSTALL_TYPE_GITHUB_RELEASE => {
199            let Ok((owner, repo)) = github_repository_parts(&plugin.repository) else {
200                return false;
201            };
202            let releases = format!(
203                "https://api.github.com/repos/{}/{}/releases/",
204                url::path_escape(&owner),
205                url::path_escape(&repo)
206            );
207            auth_configured(auth, &format!("{releases}latest"), REQUEST_KIND_METADATA)
208                || auth_configured(auth, &format!("{releases}tags/"), REQUEST_KIND_METADATA)
209        }
210        _ => false,
211    }
212}
213
214/// Request headers in Go `http.Header` form (canonical keys).
215pub type Headers = std::collections::BTreeMap<String, Vec<String>>;
216
217fn set_header(headers: &mut Headers, name: &str, value: String) {
218    headers.insert(cpa_exec::proxy::canonical_header(name), vec![value]);
219}
220
221/// Go `applyPluginStoreAuthForClient`: a matching resolved credential, else a
222/// matching rule; whether credentials were added.
223pub(super) fn apply_auth(
224    headers: &mut Headers,
225    resolved: &[ResolvedAuthConfig],
226    auth: &[AuthConfig],
227    request_url: &str,
228    kind: &str,
229) -> Result<bool, String> {
230    if let Some(item) = matching_resolved_auth_config(resolved, request_url, kind) {
231        return apply_resolved(headers, item);
232    }
233    let Some(item) = matching_auth_config(auth, request_url, kind) else {
234        return Ok(false);
235    };
236    match item.auth_type.trim().go_lower().as_str() {
237        "" | AUTH_TYPE_NONE => return Ok(false),
238        AUTH_TYPE_BEARER | AUTH_TYPE_GITHUB_TOKEN => {
239            let token = env_value_required(&item.token_env, "token-env")?;
240            set_header(headers, "Authorization", format!("Bearer {token}"));
241        }
242        AUTH_TYPE_BASIC => {
243            let username = env_value_required(&item.username_env, "username-env")?;
244            let password = env_value_required(&item.password_env, "password-env")?;
245            use base64::Engine as _;
246            let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"));
247            set_header(headers, "Authorization", format!("Basic {encoded}"));
248        }
249        AUTH_TYPE_HEADER => {
250            if item.header_name.trim().is_empty() {
251                return Err("plugin store auth missing header-name".into());
252            }
253            let value = env_value_required(&item.header_value_env, "header-value-env")?;
254            set_header(headers, &item.header_name, value);
255        }
256        _ => {
257            return Err(format!(
258                "unsupported plugin store auth type {}",
259                cpa_common::gostr::quote(&item.auth_type)
260            ));
261        }
262    }
263    Ok(true)
264}
265
266fn apply_resolved(headers: &mut Headers, item: &ResolvedAuthConfig) -> Result<bool, String> {
267    match item.auth_type.trim().go_lower().as_str() {
268        "" | AUTH_TYPE_NONE => return Ok(false),
269        AUTH_TYPE_BEARER | AUTH_TYPE_GITHUB_TOKEN => {
270            if item.token.0.is_empty() {
271                return Err("plugin store resolved auth token is empty".into());
272            }
273            set_header(
274                headers,
275                "Authorization",
276                format!("Bearer {}", String::from_utf8_lossy(&item.token.0)),
277            );
278        }
279        AUTH_TYPE_BASIC => {
280            if item.username.0.is_empty() || item.password.0.is_empty() {
281                return Err("plugin store resolved basic auth is incomplete".into());
282            }
283            let mut credential = Secret(Vec::with_capacity(item.username.0.len() + 1 + item.password.0.len()));
284            credential.0.extend_from_slice(&item.username.0);
285            credential.0.push(b':');
286            credential.0.extend_from_slice(&item.password.0);
287            use base64::Engine as _;
288            let encoded = base64::engine::general_purpose::STANDARD.encode(&credential.0);
289            set_header(headers, "Authorization", format!("Basic {encoded}"));
290        }
291        AUTH_TYPE_HEADER => {
292            if item.header_name.trim().is_empty() {
293                return Err("plugin store resolved auth missing header-name".into());
294            }
295            if item.header_value.0.is_empty() {
296                return Err("plugin store resolved auth header value is empty".into());
297            }
298            set_header(
299                headers,
300                &item.header_name,
301                String::from_utf8_lossy(&item.header_value.0).into_owned(),
302            );
303        }
304        _ => {
305            return Err(format!(
306                "unsupported plugin store resolved auth type {}",
307                cpa_common::gostr::quote(&item.auth_type)
308            ));
309        }
310    }
311    Ok(true)
312}
313
314/// Go `validatePluginStoreRequestURL`.
315pub(super) fn validate_request_url(auth: &[AuthConfig], request_url: &str, kind: &str) -> Result<(), String> {
316    let parsed = match url::parse(request_url.trim()) {
317        Some(u) if !u.scheme.is_empty() && !u.host.is_empty() => u,
318        _ => return Err("invalid plugin store url".into()),
319    };
320    if parsed.has_user {
321        return Err("plugin store url must not contain credentials".into());
322    }
323    if url::has_sensitive_query_parameter(&parsed) {
324        return Err("plugin store url contains sensitive query parameter".into());
325    }
326    if parsed.scheme.eq_ignore_ascii_case("http")
327        && !matching_auth_config(auth, request_url, kind).is_some_and(|item| item.allow_insecure)
328    {
329        return Err("insecure plugin store url requires matching allow-insecure auth rule".into());
330    }
331    Ok(())
332}
333
334/// Go `validateResolvedAuthExpiry`.
335pub(super) fn validate_resolved_auth_expiry(
336    auth: &[ResolvedAuthConfig],
337    expires_at: Option<std::time::SystemTime>,
338    now: std::time::SystemTime,
339    request_url: &str,
340    kind: &str,
341) -> Result<(), String> {
342    let Some(expires_at) = expires_at else {
343        return Ok(());
344    };
345    if matching_resolved_auth_config(auth, request_url, kind).is_none() {
346        return Ok(());
347    }
348    if now >= expires_at {
349        return Err("plugin store resolved auth expired".into());
350    }
351    Ok(())
352}
353
354/// Go `matchingAuthConfig`: the first normalised rule matching the URL and kind.
355pub(super) fn matching_auth_config(auth: &[AuthConfig], request_url: &str, kind: &str) -> Option<AuthConfig> {
356    let kind = kind.trim().go_lower();
357    normalize_auth_configs(auth)
358        .into_iter()
359        .find(|item| url_matches_rule(request_url.trim(), &item.matches) && applies_to(&item.apply_to, &kind))
360}
361
362/// Go `matchingResolvedAuthConfig`.
363pub(super) fn matching_resolved_auth_config<'a>(
364    auth: &'a [ResolvedAuthConfig],
365    request_url: &str,
366    kind: &str,
367) -> Option<&'a ResolvedAuthConfig> {
368    let kind = kind.trim().go_lower();
369    auth.iter()
370        .find(|item| url_matches_rule(request_url.trim(), item.matches.trim()) && applies_to(&item.apply_to, &kind))
371}
372
373fn applies_to(apply_to: &[String], kind: &str) -> bool {
374    apply_to.is_empty() || apply_to.iter().any(|v| v.trim().eq_ignore_ascii_case(kind))
375}
376
377/// Go `resolvedAuthConfigured`.
378pub(super) fn resolved_auth_configured(item: &ResolvedAuthConfig) -> bool {
379    match item.auth_type.trim().go_lower().as_str() {
380        AUTH_TYPE_BEARER | AUTH_TYPE_GITHUB_TOKEN => !item.token.0.is_empty(),
381        AUTH_TYPE_BASIC => !item.username.0.is_empty() && !item.password.0.is_empty(),
382        AUTH_TYPE_HEADER => !item.header_name.trim().is_empty() && !item.header_value.0.is_empty(),
383        _ => false,
384    }
385}
386
387/// Go `pluginStoreURLMatchesAuthRule`: same scheme and host (any case), and the
388/// rule's path as a segment prefix.
389fn url_matches_rule(request_url: &str, match_url: &str) -> bool {
390    let (Some(request), Some(rule)) = (url::parse(request_url.trim()), url::parse(match_url.trim())) else {
391        return false;
392    };
393    if request.scheme.is_empty() || request.host.is_empty() || rule.scheme.is_empty() || rule.host.is_empty() {
394        return false;
395    }
396    if !request.scheme.eq_ignore_ascii_case(&rule.scheme) || !request.host.eq_ignore_ascii_case(&rule.host) {
397        return false;
398    }
399    path_matches_rule(&url::path(&request), &url::path(&rule))
400}
401
402fn path_matches_rule(request_path: &str, rule_path: &str) -> bool {
403    if rule_path.is_empty() || rule_path == "/" {
404        return true;
405    }
406    let request_path = if request_path.is_empty() { "/" } else { request_path };
407    if request_path == rule_path {
408        return true;
409    }
410    if rule_path.ends_with('/') {
411        return request_path.starts_with(rule_path);
412    }
413    request_path.starts_with(&format!("{rule_path}/"))
414}
415
416/// Go `envValueRequired`.
417fn env_value_required(name: &str, field: &str) -> Result<String, String> {
418    let name = name.trim();
419    if name.is_empty() {
420        return Err(format!("plugin store auth missing {field}"));
421    }
422    let value = env(name);
423    if value.is_empty() {
424        return Err(format!("plugin store auth env {name} is empty"));
425    }
426    Ok(value)
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432
433    #[test]
434    fn rule_paths_match_by_segment() {
435        assert!(url_matches_rule("https://H.example/a/b", "https://h.example/a"));
436        assert!(!url_matches_rule("https://h.example/ab", "https://h.example/a"));
437        assert!(!url_matches_rule("https://h.example/ab", "https://h.example/a/"));
438        assert!(url_matches_rule("https://h.example/a/b", "https://h.example/a/"));
439        assert!(!url_matches_rule("https://h.example/a", "http://h.example/a"));
440        assert!(url_matches_rule("https://h.example", "https://h.example/"));
441    }
442}