Skip to main content

cpa_plugin/
hostauth.rs

1//! `host.auth.*` and `host.affinity.lookup` callbacks (internal/pluginhost/
2//! auth_callbacks.go, affinity_callbacks.go): plugins read and save credentials and
3//! observe session affinity through the host's auth manager.
4//!
5//! The server provides the manager ([`AuthManager`], Go's `coreauth.Manager` as the
6//! plugin host uses it); without one, listing reads the auth directory and lookups
7//! report the manager unavailable, as Go's host does before `SetAuthManager`.
8
9use cpa_core::gostr::GoStr;
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14use bytes::Bytes;
15use serde_json::{Map, Value};
16
17use crate::abi;
18use crate::api::{
19    AFFINITY_BOUND, AFFINITY_UNSUPPORTED, HostAffinityLookupRequest, HostAffinityLookupResponse, HostAuthFileEntry,
20    HostAuthGetRuntimeResponse, HostAuthSaveRequest, HostAuthSaveResponse, HostRecentRequestEntry,
21};
22use crate::client::CallbackError;
23use crate::go_struct;
24use crate::gojson::{self, GoTime, Metadata, NonNil, RawJson};
25use crate::host::Host;
26
27/// A credential as the manager holds it (the Go `coreauth.Auth` fields the plugin
28/// host reads).
29#[derive(Debug, Clone, Default, PartialEq)]
30pub struct HostAuth {
31    pub id: String,
32    /// Go `Auth.Index` (`EnsureIndex`).
33    pub index: String,
34    pub provider: String,
35    pub file_name: String,
36    pub label: String,
37    /// Go `Auth.Status`: `active`, `disabled`, `error`, ...
38    pub status: String,
39    pub status_message: String,
40    pub disabled: bool,
41    pub unavailable: bool,
42    pub attributes: BTreeMap<String, String>,
43    pub metadata: Map<String, Value>,
44    pub success: i64,
45    pub failed: i64,
46    /// Go `RecentRequestsSnapshot`: bucket label, successes, failures, oldest first.
47    pub recent_requests: Vec<(String, i64, i64)>,
48    pub created_at: GoTime,
49    pub updated_at: GoTime,
50    pub last_refreshed_at: GoTime,
51    pub next_retry_after: GoTime,
52    /// Go `Auth.AccountInfo()`.
53    pub account_type: String,
54    pub account: String,
55}
56
57/// What `host.auth.save` registers for the file it writes (Go `buildAuthsFromFileData`).
58#[derive(Clone)]
59pub enum SavedAuths {
60    /// No plugin auth provider took the file: its built-in credential.
61    BuiltIn(Box<HostAuth>),
62    /// The credentials the plugin auth provider for the file's type parsed, the file's
63    /// settings applied. Possibly none: the file then has no credential. `persist`: the
64    /// one credential's metadata replaces the file (Go `Manager.persist` with its token
65    /// storage); otherwise the file keeps the saved bytes.
66    Plugin {
67        path: PathBuf,
68        credentials: Vec<cpa_core::credential::Credential>,
69        persist: bool,
70        refresh: Vec<SavedRefresh>,
71    },
72    /// Nothing yet: the saving plugin is parsing this file, and the file's credentials
73    /// come from that parse. `data` is what the save writes.
74    Written { path: PathBuf, data: Vec<u8> },
75}
76
77/// Where a saved plugin auth's refresh deadlines come from (Go `preserveExistingAuthState`
78/// in `buildAuthsFromFileData`): the registered auth it replaces (`donor`, Go
79/// `findExistingAuthForSave`), whose `LastRefreshedAt` and `NextRefreshAfter` it takes,
80/// unset ones included; without one, the `NextRefreshAfter` its plugin parsed (the
81/// credential's own). The manager applies them only once it registers the auth.
82#[derive(Clone, Debug)]
83pub struct SavedRefresh {
84    pub id: String,
85    pub donor: Option<String>,
86}
87
88/// The server's credential manager as the plugin host uses it.
89pub trait AuthManager: Send + Sync {
90    /// Go `Manager.List`.
91    fn list(&self) -> Vec<HostAuth>;
92    /// Go `Manager.GetByID`.
93    fn get_by_id(&self, id: &str) -> Option<HostAuth>;
94    /// Go `saveAuthFile` from the write on: `write` puts the file (its error is the
95    /// callback's), then the manager registers or updates `auths` and removes the
96    /// file's other credentials (`upsertAuthRecordsForPath`), persisting them as its
97    /// store does. The manager serialises this with its own credential changes.
98    fn save(&self, auths: SavedAuths, write: &mut dyn FnMut() -> Result<(), String>) -> Result<(), String>;
99    /// Go `Manager.LookupSessionAffinity`: the status (`bound`, `unbound`, `ambiguous`,
100    /// `unsupported`) and, when bound, the credential.
101    fn lookup_session_affinity(&self, provider: &str, model: &str, session_id: &str) -> (String, Option<HostAuth>);
102}
103
104go_struct! {
105    pub struct RpcHostAuthGetRequest("pluginhost.rpcHostAuthGetRequest") {
106        "auth_index" => auth_index: String,
107    }
108}
109
110go_struct! {
111    pub struct RpcHostAuthListResponse("pluginhost.rpcHostAuthListResponse") {
112        "files" => files: NonNil<Vec<HostAuthFileEntry>>,
113    }
114}
115
116go_struct! {
117    pub struct RpcHostAuthGetResponse("pluginhost.rpcHostAuthGetResponse") {
118        "auth_index" => auth_index: String,
119        "name" omitempty => name: String,
120        "path" omitempty => path: String,
121        "json" => json: RawJson,
122    }
123}
124
125fn err(message: impl Into<String>) -> CallbackError {
126    CallbackError::new(message)
127}
128
129impl Host {
130    /// Go `SetAuthManager`.
131    pub fn set_auth_manager(&self, manager: Option<Arc<dyn AuthManager>>) {
132        let previous = std::mem::replace(
133            &mut *self
134                .inner
135                .callbacks
136                .auth
137                .write()
138                .unwrap_or_else(std::sync::PoisonError::into_inner),
139            manager,
140        );
141        // Dropped after the lock is released: a manager's drop may call back in.
142        drop(previous);
143    }
144
145    fn auth_manager(&self) -> Option<Arc<dyn AuthManager>> {
146        self.inner
147            .callbacks
148            .auth
149            .read()
150            .unwrap_or_else(std::sync::PoisonError::into_inner)
151            .clone()
152    }
153
154    /// Go `resolvedAuthDir`: the configured auth dir, cleaned and absolute.
155    fn resolved_auth_dir(&self) -> Option<PathBuf> {
156        let cfg = self.config()?;
157        let dir = cfg.auth_dir.to_string_lossy().trim().to_owned();
158        if dir.is_empty() {
159            return None;
160        }
161        Some(absolute(&crate::platform::clean(Path::new(&dir))))
162    }
163
164    /// `host.auth.list`.
165    pub(crate) fn host_auth_list(&self, raw: &[u8]) -> Result<Bytes, CallbackError> {
166        if !trim_space(raw).is_empty() {
167            gojson::from_slice::<Metadata>(raw).map_err(|e| err(format!("decode host auth list request: {e}")))?;
168        }
169        let files = match self.auth_manager() {
170            Some(manager) => {
171                let mut entries: Vec<HostAuthFileEntry> = manager.list().iter().filter_map(build_entry).collect();
172                entries.sort_by_key(|e| e.name.go_lower());
173                entries
174            }
175            None => self.list_auth_files_from_disk()?,
176        };
177        Ok(abi::ok_envelope(&RpcHostAuthListResponse { files: NonNil(files) }))
178    }
179
180    /// Go `listAuthFilesFromDisk`.
181    fn list_auth_files_from_disk(&self) -> Result<Vec<HostAuthFileEntry>, CallbackError> {
182        let dir = self
183            .resolved_auth_dir()
184            .ok_or_else(|| err("auth directory is unavailable"))?;
185        let read = std::fs::read_dir(&dir)
186            .map_err(|e| err(format!("failed to read auth dir: {}", path_error("open", &dir, &e))))?;
187        // os.ReadDir sorts by name.
188        let mut dirents: Vec<std::fs::DirEntry> = read.filter_map(Result::ok).collect();
189        dirents.sort_by_key(std::fs::DirEntry::file_name);
190        let mut files = Vec::new();
191        for dirent in dirents {
192            if dirent.file_type().is_ok_and(|t| t.is_dir()) {
193                continue;
194            }
195            let name = dirent.file_name().to_string_lossy().into_owned();
196            if !name.go_lower().ends_with(".json") {
197                continue;
198            }
199            let full = dir.join(&name);
200            let mut entry = HostAuthFileEntry {
201                name,
202                source: "file".into(),
203                path: full.to_string_lossy().into_owned(),
204                ..Default::default()
205            };
206            if let Ok(info) = dirent.metadata() {
207                entry.size = info.len() as i64;
208                entry.mod_time = mod_time(&info);
209            }
210            if let Ok(data) = std::fs::read(&full)
211                && let Ok(metadata) = gojson::from_slice::<Metadata>(&data)
212            {
213                if let Some(Value::String(provider)) = metadata.get("type") {
214                    entry.auth_type = provider.trim().to_owned();
215                    entry.provider = entry.auth_type.clone();
216                }
217                if let Some(Value::String(email)) = metadata.get("email") {
218                    entry.email = email.trim().to_owned();
219                }
220                if let Some(Value::String(project)) = metadata.get("project_id") {
221                    entry.project_id = project.trim().to_owned();
222                }
223                if let Some(priority) = metadata.get("priority").and_then(parse_priority) {
224                    entry.priority = priority;
225                }
226                if let Some(Value::String(note)) = metadata.get("note") {
227                    entry.note = note.trim().to_owned();
228                }
229                if let Some(Value::String(base_url)) = metadata.get("base_url") {
230                    entry.base_url = base_url.trim().to_owned();
231                }
232                if let Some(websockets) = metadata.get("websockets").and_then(parse_bool_value) {
233                    entry.websockets = websockets;
234                }
235                if metadata.get("disabled").and_then(parse_bool_value) == Some(true) {
236                    entry.disabled = true;
237                    entry.status = "disabled".into();
238                } else {
239                    entry.status = "active".into();
240                }
241            }
242            files.push(entry);
243        }
244        files.sort_by_key(|e| e.name.go_lower());
245        Ok(files)
246    }
247
248    /// Go `authByIndex`.
249    fn auth_by_index(&self, index: &str) -> Result<HostAuth, CallbackError> {
250        let index = index.trim();
251        if index.is_empty() {
252            return Err(err("auth_index is required"));
253        }
254        let manager = self
255            .auth_manager()
256            .ok_or_else(|| err("core auth manager unavailable"))?;
257        manager
258            .list()
259            .into_iter()
260            .find(|auth| auth.index == index)
261            .ok_or_else(|| err(format!("auth not found for auth_index {index}")))
262    }
263
264    /// `host.auth.get`: the credential file's JSON.
265    pub(crate) fn host_auth_get(&self, raw: &[u8]) -> Result<Bytes, CallbackError> {
266        let req: RpcHostAuthGetRequest =
267            gojson::from_slice(raw).map_err(|e| err(format!("decode host auth get request: {e}")))?;
268        let index = req.auth_index.trim();
269        if index.is_empty() {
270            return Err(err("auth_index is required"));
271        }
272        let auth = self.auth_by_index(index)?;
273        let path = attribute(&auth, "path").trim().to_owned();
274        if path.is_empty() {
275            return Err(err(format!("auth file path not found for auth_index {index}")));
276        }
277        let data = std::fs::read(&path).map_err(|e| {
278            if e.kind() == std::io::ErrorKind::NotFound {
279                err(format!("auth file not found for auth_index {index}"))
280            } else {
281                err(format!(
282                    "failed to read auth file: {}",
283                    read_error(Path::new(&path), &e)
284                ))
285            }
286        })?;
287        if trim_space(&data).is_empty() {
288            return Err(err(format!("auth file is empty for auth_index {index}")));
289        }
290        gojson::from_slice::<Metadata>(&data)
291            .map_err(|e| err(format!("invalid auth file for auth_index {index}: {e}")))?;
292        let name = match auth.file_name.trim() {
293            "" => auth.id.trim().to_owned(),
294            name => name.to_owned(),
295        };
296        Ok(abi::ok_envelope(&RpcHostAuthGetResponse {
297            auth_index: index.to_owned(),
298            name,
299            path,
300            json: RawJson(Bytes::from(data)),
301        }))
302    }
303
304    /// `host.auth.get_runtime`: the credential's runtime entry.
305    pub(crate) fn host_auth_get_runtime(&self, raw: &[u8]) -> Result<Bytes, CallbackError> {
306        let req: RpcHostAuthGetRequest =
307            gojson::from_slice(raw).map_err(|e| err(format!("decode host auth get runtime request: {e}")))?;
308        let index = req.auth_index.trim();
309        if index.is_empty() {
310            return Err(err("auth_index is required"));
311        }
312        let auth = self.auth_by_index(index)?;
313        let entry =
314            build_entry(&auth).ok_or_else(|| err(format!("auth runtime info not found for auth_index {index}")))?;
315        Ok(abi::ok_envelope(&HostAuthGetRuntimeResponse { auth: entry }))
316    }
317
318    /// `host.auth.save`: writes the credential file and registers it.
319    pub(crate) fn host_auth_save(&self, caller: &crate::callbacks::Caller, raw: &[u8]) -> Result<Bytes, CallbackError> {
320        let req: HostAuthSaveRequest =
321            gojson::from_slice(raw).map_err(|e| err(format!("decode host auth save request: {e}")))?;
322        // validateHostAuthSaveRequest.
323        let name = req.name.trim();
324        if name.is_empty() || name.contains(['/', '\\']) || (cfg!(windows) && has_volume_name(name)) {
325            return Err(err("invalid auth file name"));
326        }
327        if !name.go_lower().ends_with(".json") {
328            return Err(err("auth file name must end with .json"));
329        }
330        let data = trim_space(&req.json.0).to_vec();
331        if data.is_empty() {
332            return Err(err("json is required"));
333        }
334        gojson::from_slice::<Metadata>(&data).map_err(|e| err(format!("invalid auth json: {e}")))?;
335        // saveAuthFile.
336        let dir = self
337            .resolved_auth_dir()
338            .ok_or_else(|| err("auth directory is unavailable"))?;
339        let dst = absolute(&dir.join(name));
340        // Go parses the saved data first, which recurses through a plugin saving the file
341        // it is parsing (`auth::SaveParse`).
342        let auths = match self.save_parse(&caller.instance, &dst) {
343            crate::auth::SaveParse::Parse => self.build_auths_from_file_data(&dst, &data)?,
344            // The file is written as is; the parse's answer is published and the watcher
345            // parses the saved bytes next (`credentials::note_plugin_auth_write`).
346            crate::auth::SaveParse::Nested => SavedAuths::Written {
347                path: dst.clone(),
348                data: data.clone(),
349            },
350            crate::auth::SaveParse::Refused => {
351                return Err(err(format!(
352                    "auth file {name} is being parsed for another save by this plugin"
353                )));
354            }
355        };
356        let mut write = || write_auth_file(&dst, &data).map_err(|e| format!("failed to write auth file: {e}"));
357        match self.auth_manager() {
358            Some(manager) => manager.save(auths, &mut write).map_err(err)?,
359            None => write().map_err(err)?,
360        }
361        Ok(abi::ok_envelope(&HostAuthSaveResponse {
362            name: name.to_owned(),
363            path: dst.to_string_lossy().into_owned(),
364        }))
365    }
366
367    /// Go `buildAuthsFromFileData` for a file about to be written: the plugin auth
368    /// provider for the file's type is asked first (a failed parse fails the save), then
369    /// the built-in credential. Called holding no lock, so the plugin may call back.
370    fn build_auths_from_file_data(&self, path: &Path, data: &[u8]) -> Result<SavedAuths, CallbackError> {
371        let mut metadata: Map<String, Value> = match gojson::from_slice::<Metadata>(data) {
372            Ok(m) => m.into_iter().collect(),
373            Err(e) => return Err(err(format!("invalid auth file: {e}"))),
374        };
375        crate::auth::normalize_credential_metadata(&mut metadata);
376        // ValidateAuthWeight on the file's metadata.
377        if let Some(weight) = metadata.get("weight") {
378            cpa_core::config::credentials::parse_weight(weight).map_err(|e| {
379                err(format!(
380                    "invalid auth weight: invalid metadata weight: {}",
381                    go_weight_error(weight, e)
382                ))
383            })?;
384        }
385        let path_text = path.to_string_lossy().into_owned();
386        let default_id = match self.auth_id_for_path(&path_text) {
387            id if id.is_empty() => path_text.clone(),
388            id => id,
389        };
390        let parsed = self.parse_auths_for(
391            crate::api::AuthParseRequest {
392                provider: match metadata.get("type") {
393                    Some(Value::String(p)) => p.trim().to_owned(),
394                    _ => String::new(),
395                },
396                path: path_text.clone(),
397                file_name: default_id.clone(),
398                raw_json: Bytes::copy_from_slice(data),
399                ..Default::default()
400            },
401            true,
402        );
403        if let Some(e) = parsed.error {
404            return Err(err(format!("invalid auth file: {e}")));
405        }
406        if !parsed.handled {
407            // The file's credential keeps its ID.
408            let id = self
409                .existing_auth_for_save(&default_id, &path_text, &default_id)
410                .map(|existing| existing.id.trim().to_owned())
411                .filter(|id| !id.is_empty())
412                .unwrap_or(default_id);
413            return self
414                .built_in_auth(path, metadata, id)
415                .map(|auth| SavedAuths::BuiltIn(Box::new(auth)));
416        }
417        let single = parsed.auths.len() == 1;
418        let file_disabled = metadata.get("disabled").and_then(parse_bool_value) == Some(true);
419        let base = path
420            .file_name()
421            .map(|n| n.to_string_lossy().into_owned())
422            .unwrap_or_default();
423        let mut persist = single;
424        let mut auths = Vec::with_capacity(parsed.auths.len());
425        let mut refresh = Vec::with_capacity(parsed.auths.len());
426        for mut auth in parsed.auths {
427            validate_parsed_weight(&auth)?;
428            // Normalized before the one auth inherits the file's other fields, so the
429            // plugin's own fields win in either spelling.
430            let mut own: Map<String, Value> = std::mem::take(&mut auth.metadata).into_iter().collect();
431            crate::auth::normalize_credential_metadata(&mut own);
432            auth.metadata = own.into_iter().collect();
433            if single {
434                // The one auth inherits the file's other fields and, without storage of
435                // its own, the file itself.
436                for (key, value) in &metadata {
437                    auth.metadata.entry(key.clone()).or_insert_with(|| value.clone());
438                }
439                if auth.storage_json.trim_ascii().is_empty() {
440                    auth.storage_json = Bytes::copy_from_slice(data);
441                }
442            }
443            if auth.file_name.trim().is_empty() {
444                auth.file_name = base.clone();
445            }
446            // ponytail: a credential lists under its file's name (see
447            // DIFFERENCES-FROM-GO.md); a save whose auth names another file is refused
448            // before the write. Upgrade: keep the parsed file name on the credential.
449            if auth.file_name.trim() != base {
450                return Err(err(format!(
451                    "auth provider returned file name {} for auth file {base}, which is not supported",
452                    auth.file_name.trim()
453                )));
454            }
455            // One auth under the file's own ID takes over the credential the file has.
456            if single
457                && (auth.id.trim().is_empty() || auth.id == default_id)
458                && let Some(existing) = self.existing_auth_for_save(&auth.id, &path_text, &default_id)
459                && !existing.id.trim().is_empty()
460            {
461                auth.id = existing.id.trim().to_owned();
462            }
463            if auth.id.trim().is_empty() {
464                auth.id = default_id.clone();
465            }
466            // Go `findExistingAuthForSave(auth.ID, path, len(out) == 1)`.
467            let donor = if single {
468                self.existing_auth_for_save(&auth.id, &path_text, &default_id)
469            } else {
470                self.auth_manager().and_then(|m| m.get_by_id(auth.id.trim()))
471            };
472            refresh.push(SavedRefresh {
473                id: auth.id.clone(),
474                donor: donor.map(|d| d.id),
475            });
476            if file_disabled {
477                auth.disabled = true;
478                auth.metadata.insert("disabled".into(), true.into());
479            }
480            if single {
481                // Go `Manager.persist` skips runtime-only and plugin-virtual auths, and a
482                // token storage that cannot build its document fails, leaving the file
483                // with the saved bytes; the auth is registered either way.
484                let marked = |key: &str| auth.attributes.get(key).is_some_and(|v| v.trim().go_eq_fold("true"));
485                persist = !marked("runtime_only") && !marked("plugin_virtual");
486                if persist {
487                    // Go `FileTokenStore.Save` records the disabled state before the
488                    // storage serializes, so it stays even when serializing fails.
489                    auth.metadata.insert("disabled".into(), auth.disabled.into());
490                    if let Err(error) = auth.storage_payload() {
491                        tracing::warn!(id = %auth.id, provider = %auth.provider, %error, "failed to persist registered auth");
492                        persist = false;
493                    }
494                }
495            }
496            auths.push(auth.into_parsed());
497        }
498        // The saved file's settings Go applies when saving (priority, weight, prefix,
499        // proxy URL, ...), from its decoded metadata.
500        let credentials =
501            cpa_core::config::credentials::plugin_save_credentials(path, &metadata, auths).map_err(err)?;
502        Ok(SavedAuths::Plugin {
503            path: path.to_owned(),
504            credentials,
505            persist,
506            refresh,
507        })
508    }
509
510    /// Go `findExistingAuthForSave(authID, path, true)`: the credential with `id` unless
511    /// that is the file's default ID, else a non-virtual credential of the file at
512    /// `path` (preferring one not under the default ID), else the one with `id`.
513    fn existing_auth_for_save(&self, id: &str, path: &str, default_id: &str) -> Option<HostAuth> {
514        let manager = self.auth_manager()?;
515        let id = id.trim();
516        if !id.is_empty()
517            && id != default_id
518            && let Some(existing) = manager.get_by_id(id)
519        {
520            return Some(existing);
521        }
522        let path = absolute(&crate::platform::clean(Path::new(path)));
523        let same_file = |auth: &HostAuth| {
524            ["path", "source", "virtual_source"].iter().any(|key| {
525                let other = attribute(auth, key).trim();
526                !other.is_empty() && absolute(&crate::platform::clean(Path::new(other))) == path
527            })
528        };
529        let mut matched: Option<HostAuth> = None;
530        for candidate in manager.list() {
531            let marked = |key| attribute(&candidate, key).trim().go_eq_fold("true");
532            if marked("runtime_only") || marked("plugin_virtual") || !same_file(&candidate) {
533                continue;
534            }
535            if matched
536                .as_ref()
537                .is_none_or(|m| m.id == default_id && candidate.id != default_id)
538            {
539                matched = Some(candidate);
540            }
541        }
542        matched.or_else(|| (!id.is_empty()).then(|| manager.get_by_id(id)).flatten())
543    }
544
545    /// The built-in branch of Go `buildAuthsFromFileData`.
546    fn built_in_auth(&self, path: &Path, metadata: Map<String, Value>, id: String) -> Result<HostAuth, CallbackError> {
547        let provider = match metadata.get("type") {
548            Some(Value::String(p)) if !p.trim().is_empty() => p.clone(),
549            _ => "unknown".to_owned(),
550        };
551        let label = match metadata.get("email") {
552            Some(Value::String(email)) if !email.trim().is_empty() => email.trim().to_owned(),
553            _ => provider.clone(),
554        };
555        let path_text = path.to_string_lossy().into_owned();
556        let disabled = metadata.get("disabled").and_then(parse_bool_value) == Some(true);
557        let now = GoTime::now_utc();
558        let mut auth = HostAuth {
559            id,
560            provider,
561            file_name: path
562                .file_name()
563                .map(|n| n.to_string_lossy().into_owned())
564                .unwrap_or_default(),
565            label,
566            status: if disabled { "disabled" } else { "active" }.into(),
567            disabled,
568            attributes: BTreeMap::from([("path".to_owned(), path_text.clone()), ("source".to_owned(), path_text)]),
569            metadata,
570            created_at: now,
571            updated_at: now,
572            ..Default::default()
573        };
574        if let Some(existing) = self.auth_manager().and_then(|m| m.get_by_id(&auth.id)) {
575            auth.created_at = existing.created_at;
576            auth.last_refreshed_at = existing.last_refreshed_at;
577            auth.next_retry_after = existing.next_retry_after;
578        }
579        // ponytail: ApplyCustomHeadersFromMetadata is left to the manager, which loads
580        // the saved file the way every auth file is loaded.
581        Ok(auth)
582    }
583
584    /// Go `authIDForPath` (auth_callbacks.go): relative to the auth dir when `Rel`
585    /// succeeds, otherwise the cleaned absolute path.
586    fn auth_id_for_path(&self, path: &str) -> String {
587        let path = path.trim();
588        if path.is_empty() {
589            return String::new();
590        }
591        let path = absolute(&crate::platform::clean(Path::new(path)))
592            .to_string_lossy()
593            .into_owned();
594        let mut id = path.clone();
595        if let Some(dir) = self.resolved_auth_dir()
596            && let Some(rel) = crate::platform::rel(&dir.to_string_lossy(), &path)
597            && !rel.is_empty()
598        {
599            id = rel;
600        }
601        if cfg!(windows) { id.go_lower() } else { id }
602    }
603
604    /// `host.affinity.lookup`.
605    pub(crate) fn host_affinity_lookup(&self, raw: &[u8]) -> Result<Bytes, CallbackError> {
606        let req: HostAffinityLookupRequest =
607            gojson::from_slice(raw).map_err(|e| err(format!("decode host affinity lookup request: {e}")))?;
608        let (provider, model, session) = (req.provider.trim(), req.model.trim(), req.session_id.trim());
609        if provider.is_empty() {
610            return Err(err("provider is required"));
611        }
612        if model.is_empty() {
613            return Err(err("model is required"));
614        }
615        if session.is_empty() {
616            return Err(err("session_id is required"));
617        }
618        let observed_at = GoTime::now_utc();
619        let Some(manager) = self.auth_manager() else {
620            return Ok(abi::ok_envelope(&HostAffinityLookupResponse {
621                status: AFFINITY_UNSUPPORTED.into(),
622                observed_at,
623                ..Default::default()
624            }));
625        };
626        let resp = match manager.lookup_session_affinity(provider, model, session) {
627            (status, Some(auth)) if status == AFFINITY_BOUND => HostAffinityLookupResponse {
628                status,
629                auth_index: auth.index.clone(),
630                observed_at,
631                disabled: auth.disabled || auth.status == "disabled",
632                unavailable: auth.unavailable || auth.status == "error",
633            },
634            (status, _) => HostAffinityLookupResponse {
635                status,
636                observed_at,
637                ..Default::default()
638            },
639        };
640        Ok(abi::ok_envelope(&resp))
641    }
642}
643
644/// Go `buildHostAuthFileEntry`. `None` hides the credential: a disabled runtime-only
645/// one, one without a file that is not runtime-only, or a disabled or removed one
646/// whose file is gone.
647pub fn build_entry(auth: &HostAuth) -> Option<HostAuthFileEntry> {
648    let runtime_only = attribute(auth, "runtime_only").trim().eq_ignore_ascii_case("true");
649    let disabled = auth.disabled || auth.status == "disabled";
650    if runtime_only && disabled {
651        return None;
652    }
653    let path = attribute(auth, "path").trim().to_owned();
654    if path.is_empty() && !runtime_only {
655        return None;
656    }
657    let name = match auth.file_name.trim() {
658        "" => auth.id.clone(),
659        name => name.to_owned(),
660    };
661    let mut entry = HostAuthFileEntry {
662        id: auth.id.clone(),
663        auth_index: auth.index.clone(),
664        name,
665        auth_type: auth.provider.trim().to_owned(),
666        provider: auth.provider.trim().to_owned(),
667        label: auth.label.clone(),
668        status: auth.status.clone(),
669        status_message: auth.status_message.clone(),
670        disabled: auth.disabled,
671        unavailable: auth.unavailable,
672        runtime_only,
673        source: "memory".into(),
674        success: auth.success,
675        failed: auth.failed,
676        recent_requests: auth
677            .recent_requests
678            .iter()
679            .map(|(time, success, failed)| HostRecentRequestEntry {
680                time: time.clone(),
681                success: *success,
682                failed: *failed,
683            })
684            .collect(),
685        email: auth_email(auth),
686        project_id: auth_project_id(auth),
687        account_type: auth.account_type.clone(),
688        account: auth.account.clone(),
689        ..Default::default()
690    };
691    if !auth.created_at.is_zero() {
692        entry.created_at = auth.created_at;
693    }
694    if !auth.updated_at.is_zero() {
695        entry.mod_time = auth.updated_at;
696        entry.updated_at = auth.updated_at;
697    }
698    if !auth.last_refreshed_at.is_zero() {
699        entry.last_refresh = auth.last_refreshed_at;
700    }
701    if !auth.next_retry_after.is_zero() {
702        entry.next_retry_after = auth.next_retry_after;
703    }
704    if !path.is_empty() {
705        entry.path = path.clone();
706        entry.source = "file".into();
707        match std::fs::metadata(&path) {
708            Ok(info) => {
709                entry.size = info.len() as i64;
710                entry.mod_time = mod_time(&info);
711            }
712            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
713                let removed = auth
714                    .status_message
715                    .trim()
716                    .eq_ignore_ascii_case("removed via management api");
717                if !runtime_only && (disabled || removed) {
718                    return None;
719                }
720                entry.source = "memory".into();
721            }
722            Err(_) => {}
723        }
724    }
725    match attribute(auth, "priority").trim() {
726        "" => {
727            if let Some(priority) = auth.metadata.get("priority").and_then(parse_priority) {
728                entry.priority = priority;
729            }
730        }
731        p => {
732            if let Ok(parsed) = parse_go_int(p) {
733                entry.priority = parsed;
734            }
735        }
736    }
737    match attribute(auth, "note").trim() {
738        "" => {
739            if let Some(Value::String(note)) = auth.metadata.get("note") {
740                entry.note = note.trim().to_owned();
741            }
742        }
743        note => entry.note = note.to_owned(),
744    }
745    match attribute(auth, "base_url").trim() {
746        "" => {
747            if let Some(Value::String(base_url)) = auth.metadata.get("base_url") {
748                entry.base_url = base_url.trim().to_owned();
749            }
750        }
751        base_url => entry.base_url = base_url.to_owned(),
752    }
753    if let Some(websockets) = auth_websockets(auth) {
754        entry.websockets = websockets;
755    }
756    Some(entry)
757}
758
759fn attribute<'a>(auth: &'a HostAuth, key: &str) -> &'a str {
760    auth.attributes.get(key).map_or("", String::as_str)
761}
762
763/// Go `authEmail`: metadata, then the `email` and `account_email` attributes.
764fn auth_email(auth: &HostAuth) -> String {
765    if let Some(Value::String(email)) = auth.metadata.get("email") {
766        return email.trim().to_owned();
767    }
768    for key in ["email", "account_email"] {
769        let v = attribute(auth, key).trim();
770        if !v.is_empty() {
771            return v.to_owned();
772        }
773    }
774    String::new()
775}
776
777/// Go `authProjectID`.
778fn auth_project_id(auth: &HostAuth) -> String {
779    if let Some(Value::String(project)) = auth.metadata.get("project_id")
780        && !project.trim().is_empty()
781    {
782        return project.trim().to_owned();
783    }
784    attribute(auth, "project_id").trim().to_owned()
785}
786
787/// Go `authWebsocketsValue`.
788fn auth_websockets(auth: &HostAuth) -> Option<bool> {
789    let raw = attribute(auth, "websockets").trim();
790    if !raw.is_empty()
791        && let Some(parsed) = parse_go_bool(raw)
792    {
793        return Some(parsed);
794    }
795    auth.metadata.get("websockets").and_then(parse_bool_value)
796}
797
798/// Go `parsePriorityValue` on decoded JSON: numbers truncate, strings `Atoi`.
799fn parse_priority(raw: &Value) -> Option<i64> {
800    match raw {
801        Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)),
802        Value::String(s) => parse_go_int(s.trim()).ok(),
803        _ => None,
804    }
805}
806
807/// Go `parseBoolValue`.
808fn parse_bool_value(raw: &Value) -> Option<bool> {
809    match raw {
810        Value::Bool(b) => Some(*b),
811        Value::String(s) => parse_go_bool(s.trim()),
812        _ => None,
813    }
814}
815
816/// `strconv.ParseBool`.
817fn parse_go_bool(s: &str) -> Option<bool> {
818    match s {
819        "1" | "t" | "T" | "TRUE" | "true" | "True" => Some(true),
820        "0" | "f" | "F" | "FALSE" | "false" | "False" => Some(false),
821        _ => None,
822    }
823}
824
825/// `strconv.Atoi`: optional sign and decimal digits, in range.
826fn parse_go_int(s: &str) -> Result<i64, ()> {
827    let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
828    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
829        return Err(());
830    }
831    s.parse().map_err(|_| ())
832}
833
834/// Go `strings.TrimSpace` on bytes.
835fn trim_space(raw: &[u8]) -> &[u8] {
836    match std::str::from_utf8(raw) {
837        Ok(s) => s.trim().as_bytes(),
838        Err(_) => raw.trim_ascii(),
839    }
840}
841
842/// `filepath.Abs` without touching the file system.
843fn absolute(path: &Path) -> PathBuf {
844    if path.is_absolute() {
845        return path.to_owned();
846    }
847    std::env::current_dir()
848        .map(|cwd| crate::platform::clean(&cwd.join(path)))
849        .unwrap_or_else(|_| path.to_owned())
850}
851
852/// Go `ValidateAuthWeight` on an auth a plugin parsed.
853fn validate_parsed_weight(auth: &crate::auth::PluginAuth) -> Result<(), CallbackError> {
854    let invalid = |kind: &str, weight: &Value, e: String| {
855        err(format!(
856            "invalid auth weight: invalid {kind} weight: {}",
857            go_weight_error(weight, e)
858        ))
859    };
860    if let Some(weight) = auth.attributes.get("weight") {
861        let weight = Value::String(weight.clone());
862        cpa_core::config::credentials::parse_weight(&weight).map_err(|e| invalid("attributes", &weight, e))?;
863    }
864    if let Some(weight) = auth.metadata.get("weight") {
865        cpa_core::config::credentials::parse_weight(weight).map_err(|e| invalid("metadata", weight, e))?;
866    }
867    Ok(())
868}
869
870/// Windows `filepath.VolumeName` is non-empty: a drive letter or a UNC prefix.
871fn has_volume_name(name: &str) -> bool {
872    let b = name.as_bytes();
873    (b.len() >= 2 && b[1] == b':' && b[0].is_ascii_alphabetic()) || name.starts_with("\\\\")
874}
875
876/// `info.ModTime()` in local time.
877fn mod_time(info: &std::fs::Metadata) -> GoTime {
878    GoTime(
879        info.modified()
880            .ok()
881            .map(|t| chrono::DateTime::<chrono::Local>::from(t).fixed_offset()),
882    )
883}
884
885/// `os.WriteFile(path, data, 0o600)`: the error is Go's `*PathError` text for the
886/// step that failed (open, write, then close).
887pub fn write_auth_file(path: &Path, data: &[u8]) -> Result<(), String> {
888    use std::io::Write as _;
889    let mut options = std::fs::OpenOptions::new();
890    options.write(true).create(true).truncate(true);
891    #[cfg(unix)]
892    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
893    let mut file = options.open(path).map_err(|e| path_error("open", path, &e))?;
894    let written = file.write_all(data).map_err(|e| path_error("write", path, &e));
895    let closed = close(file).map_err(|e| path_error("close", path, &e));
896    written.and(closed)
897}
898
899/// Closes `file`, reporting the error `close(2)` returns (Go's `File.Close`).
900fn close(file: std::fs::File) -> std::io::Result<()> {
901    #[cfg(unix)]
902    {
903        use std::os::fd::IntoRawFd as _;
904        // SAFETY: the descriptor is owned here and closed exactly once.
905        if unsafe { libc::close(file.into_raw_fd()) } != 0 {
906            return Err(std::io::Error::last_os_error());
907        }
908        Ok(())
909    }
910    #[cfg(not(unix))]
911    {
912        drop(file);
913        Ok(())
914    }
915}
916
917/// `credentialweight.ParseString`'s error for a string weight `strconv.ParseInt`
918/// rejects; any other weight error as reported.
919// ponytail: cpa-core's parse_weight words string failures with Rust's parse error.
920pub(crate) fn go_weight_error(weight: &Value, error: String) -> String {
921    let Value::String(raw) = weight else {
922        return error;
923    };
924    let raw = raw.trim();
925    match raw.parse::<i64>() {
926        Ok(_) => error,
927        Err(e) => {
928            let why = match e.kind() {
929                std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow => "value out of range",
930                _ => "invalid syntax",
931            };
932            format!(
933                "weight must be an integer: strconv.ParseInt: parsing {}: {why}",
934                cpa_common::gostr::quote(raw)
935            )
936        }
937    }
938}
939
940/// Go's `*PathError` text: `op path: errno`.
941pub(crate) fn path_error(op: &str, path: &Path, e: &std::io::Error) -> String {
942    format!("{op} {}: {}", path.display(), errno_text(e))
943}
944
945/// The error `os.ReadFile` reports: opening fails as `open`, reading a directory as
946/// `read`.
947fn read_error(path: &Path, e: &std::io::Error) -> String {
948    #[cfg(unix)]
949    if e.raw_os_error() == Some(libc::EISDIR) {
950        return path_error("read", path, e);
951    }
952    path_error("open", path, e)
953}
954
955/// Go's `syscall.Errno` text: strerror in lower case, without Rust's suffix.
956fn errno_text(e: &std::io::Error) -> String {
957    let text = e.to_string();
958    let text = text.split(" (os error").next().unwrap_or_default();
959    let mut chars = text.chars();
960    chars
961        .next()
962        .map_or_else(String::new, |c| c.to_lowercase().chain(chars).collect())
963}
964
965#[cfg(test)]
966mod tests {
967    use super::*;
968
969    #[test]
970    fn go_number_and_bool_parsing() {
971        assert_eq!(parse_go_int("+7"), Ok(7));
972        assert_eq!(parse_go_int("-3"), Ok(-3));
973        assert_eq!(parse_go_int("7.0"), Err(()));
974        assert_eq!(parse_go_int(""), Err(()));
975        assert_eq!(parse_priority(&serde_json::json!(4.9)), Some(4));
976        assert_eq!(parse_priority(&serde_json::json!(" 5 ")), Some(5));
977        assert_eq!(parse_priority(&serde_json::json!(true)), None);
978        assert_eq!(parse_bool_value(&serde_json::json!(" T ")), Some(true));
979        assert_eq!(parse_bool_value(&serde_json::json!("yes")), None);
980    }
981
982    /// credentialweight.ParseString: strconv.ParseInt's syntax and range errors.
983    #[test]
984    fn string_weight_errors_follow_go() {
985        let text = |w: Value| {
986            let e = cpa_core::config::credentials::parse_weight(&w).unwrap_err();
987            go_weight_error(&w, e)
988        };
989        assert_eq!(
990            text(serde_json::json!(" abc ")),
991            "weight must be an integer: strconv.ParseInt: parsing \"abc\": invalid syntax"
992        );
993        assert_eq!(
994            text(serde_json::json!("99999999999999999999")),
995            "weight must be an integer: strconv.ParseInt: parsing \"99999999999999999999\": value out of range"
996        );
997        assert_eq!(text(serde_json::json!("2000000")), "weight must not exceed 1000000");
998        assert_eq!(text(serde_json::json!(1.5)), "weight must be an integer");
999    }
1000}