1use cpa_core::gostr::GoStr;
9use std::collections::BTreeMap;
10
11use bytes::Bytes;
12use serde_json::Value;
13
14use crate::abi::method;
15use crate::api::{
16 AuthData, AuthLoginPollRequest, AuthLoginPollResponse, AuthLoginStartRequest, AuthLoginStartResponse,
17 AuthParseRequest, AuthParseResponse, AuthRefreshRequest, AuthRefreshResponse, FrontendAuthRequest,
18 FrontendAuthResponse, HostConfigSummary, ModelAlias,
19};
20use crate::callbacks::RequestScope;
21use crate::gojson::{GoTime, Metadata, StringMap};
22use crate::host::{Host, Record, normalize_provider};
23use crate::rpc::CallError;
24
25pub const ATTRIBUTE_PATH: &str = "path";
26pub const ATTRIBUTE_SOURCE: &str = "source";
27pub const ATTRIBUTE_SOURCE_BACKEND: &str = "source_backend";
28pub const ATTRIBUTE_FILE_PRIORITY: &str = "file_priority";
29pub const AUTH_SOURCE_FILE: &str = "file";
30
31#[derive(Debug, Clone, Default, PartialEq)]
33pub struct PluginAuth {
34 pub provider: String,
35 pub id: String,
36 pub file_name: String,
37 pub label: String,
38 pub prefix: String,
39 pub proxy_url: String,
40 pub disabled: bool,
41 pub storage_json: Bytes,
43 pub metadata: Metadata,
45 pub attributes: StringMap,
46 pub next_refresh_after: GoTime,
47}
48
49pub fn canonical_metadata_key(key: &str) -> &str {
51 match key {
52 "api-key" => "api_key",
53 "base-url" => "base_url",
54 "disable-cooling" => "disable_cooling",
55 "excluded-models" => "excluded_models",
56 "fingerprint-profile" => "fingerprint_profile",
57 "model-aliases" => "model_aliases",
58 "openapi-location" => "openapi_location",
59 "openapi-models" => "openapi_models",
60 "proxy-url" => "proxy_url",
61 "request-retry" => "request_retry",
62 "request-scoped-errors" => "request_scoped_errors",
63 "tool-prefix-disabled" => "tool_prefix_disabled",
64 other => other,
65 }
66}
67
68pub fn normalize_credential_metadata(metadata: &mut serde_json::Map<String, Value>) {
71 let legacy: Vec<String> = metadata
72 .keys()
73 .filter(|k| canonical_metadata_key(k) != k.as_str())
74 .cloned()
75 .collect();
76 for key in legacy {
77 let value = metadata.remove(&key).expect("listed above");
78 metadata.entry(canonical_metadata_key(&key).to_owned()).or_insert(value);
79 }
80}
81
82pub fn auth_id_for_path(path: &str, auth_dir: &str) -> String {
84 let path = path.trim();
85 if path.is_empty() {
86 return String::new();
87 }
88 let auth_dir = auth_dir.trim();
89 let id = match crate::platform::rel(auth_dir, path) {
90 Some(rel) if !auth_dir.is_empty() && !rel.is_empty() && !rel.starts_with("..") => rel,
91 _ => path.to_owned(),
92 };
93 let id = crate::platform::clean(std::path::Path::new(&id))
94 .to_string_lossy()
95 .into_owned();
96 if cfg!(windows) {
98 id.replace('\\', "/").go_lower()
99 } else {
100 id
101 }
102}
103
104fn first_non_empty(values: &[&str]) -> String {
105 values
106 .iter()
107 .map(|v| v.trim())
108 .find(|v| !v.is_empty())
109 .unwrap_or_default()
110 .to_owned()
111}
112
113impl PluginAuth {
114 pub fn from_auth_data(data: AuthData, path: &str, file_name: &str, auth_dir: &str) -> Option<Self> {
116 let provider = normalize_provider(&data.provider);
117 if provider.is_empty() {
118 return None;
119 }
120 let mut metadata = data.metadata;
121 metadata.insert("type".into(), provider.clone().into());
122 let mut attributes = data.attributes;
123 let path = path.trim();
124 if !path.is_empty() {
125 for (key, value) in [
126 (ATTRIBUTE_PATH, path),
127 (ATTRIBUTE_SOURCE, path),
128 (ATTRIBUTE_SOURCE_BACKEND, AUTH_SOURCE_FILE),
129 ] {
130 if attributes.get(key).is_none_or(|v| v.is_empty()) {
131 attributes.insert(key.into(), value.into());
132 }
133 }
134 }
135 let file_name = first_non_empty(&[&data.file_name, file_name]);
136 if !file_name.is_empty() && attributes.get(ATTRIBUTE_SOURCE).is_none_or(|v| v.is_empty()) {
137 attributes.insert(ATTRIBUTE_SOURCE.into(), file_name.clone());
138 }
139 let mut id = data.id.trim().to_owned();
140 if id.is_empty() {
141 id = auth_id_for_path(&first_non_empty(&[path, &file_name]), auth_dir);
142 }
143 Some(Self {
144 provider,
145 id,
146 file_name,
147 label: data.label.trim().to_owned(),
148 prefix: data.prefix.trim().to_owned(),
149 proxy_url: data.proxy_url.trim().to_owned(),
150 disabled: data.disabled,
151 storage_json: data.storage_json,
152 metadata,
153 attributes,
154 next_refresh_after: data.next_refresh_after,
155 })
156 }
157
158 pub fn storage_payload(&self) -> Result<Bytes, String> {
162 let mut out = serde_json::Map::new();
163 if !self.storage_json.trim_ascii().is_empty() {
164 match crate::gojson::parse(&self.storage_json).and_then(|n| n.to_value()) {
165 Ok(Value::Object(map)) => out = map,
166 Ok(Value::Null) => {}
167 Ok(_) => return Err("decode plugin token storage: json: cannot unmarshal into map".into()),
168 Err(e) => return Err(format!("decode plugin token storage: {e}")),
169 }
170 }
171 for (key, value) in &self.metadata {
172 out.insert(key.clone(), value.clone());
173 }
174 let provider = normalize_provider(&self.provider);
175 if !provider.is_empty() {
176 out.insert("type".into(), provider.into());
177 }
178 normalize_credential_metadata(&mut out);
179 if out.is_empty() {
180 return Err("plugin token storage payload is empty".into());
181 }
182 let mut payload = Vec::new();
183 crate::gojson::encode_any(&Value::Object(out), &mut payload);
184 Ok(Bytes::from(payload))
185 }
186}
187
188impl PluginAuth {
189 pub fn merge_existing(&mut self, existing: &serde_json::Map<String, Value>) {
193 if existing.is_empty() {
194 return;
195 }
196 if !self.metadata.contains_key("disabled")
197 && let Some(Value::Bool(disabled)) = existing.get("disabled")
198 {
199 self.disabled = *disabled;
200 }
201 let meta = self.provider.trim().eq_ignore_ascii_case("meta");
202 for (key, value) in existing {
203 if is_auth_token_payload_key(key) {
204 continue;
205 }
206 if meta
207 && matches!(
208 canonical_metadata_key(key),
209 "api_key" | "dca_token" | "dca_expired" | "dca_expires_at"
210 )
211 {
212 continue;
213 }
214 self.metadata.entry(key.clone()).or_insert_with(|| value.clone());
215 }
216 }
217
218 pub fn file_path(&self, base_dir: &str) -> Result<String, String> {
220 use std::path::Path;
221 let base_dir = base_dir.trim();
222 Ok(match self.attributes.get(ATTRIBUTE_PATH).map(|p| p.trim()) {
223 Some(p) if !p.is_empty() => p.to_owned(),
224 _ => match self.file_name.trim() {
225 "" if self.id.is_empty() => return Err("auth filestore: missing id".into()),
226 "" if Path::new(&self.id).is_absolute() => self.id.clone(),
227 "" if base_dir.is_empty() => return Err("auth filestore: directory not configured".into()),
228 "" => Path::new(base_dir).join(&self.id).to_string_lossy().into_owned(),
229 name if Path::new(name).is_absolute() || base_dir.is_empty() => name.to_owned(),
230 name => Path::new(base_dir).join(name).to_string_lossy().into_owned(),
231 },
232 })
233 }
234
235 pub fn save_file(mut self, base_dir: &str, create: bool) -> Result<String, String> {
241 use std::path::Path;
242 let mut metadata: serde_json::Map<String, Value> = std::mem::take(&mut self.metadata).into_iter().collect();
243 normalize_credential_metadata(&mut metadata);
244 if let Some(raw) = self.attributes.get("weight") {
246 let weight = Value::String(raw.clone());
247 cpa_core::config::credentials::parse_weight(&weight).map_err(|e| {
248 format!(
249 "auth filestore: invalid attributes weight: {}",
250 crate::hostauth::go_weight_error(&weight, e)
251 )
252 })?;
253 }
254 if let Some(weight) = metadata.get("weight") {
255 cpa_core::config::credentials::parse_weight(weight).map_err(|e| {
256 format!(
257 "auth filestore: invalid metadata weight: {}",
258 crate::hostauth::go_weight_error(weight, e)
259 )
260 })?;
261 }
262 let path = self.file_path(base_dir)?;
263 let path_ref = Path::new(&path);
264 if self.disabled
267 && !create
268 && std::fs::metadata(path_ref).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
269 {
270 return Ok(String::new());
271 }
272 if let Some(dir) = path_ref.parent().filter(|d| !d.as_os_str().is_empty()) {
273 create_private_dir(dir).map_err(|e| {
274 format!(
275 "auth filestore: create dir failed: {}",
276 crate::hostauth::path_error("mkdir", dir, &e)
277 )
278 })?;
279 }
280 metadata.insert("disabled".into(), self.disabled.into());
281 self.metadata = metadata.into_iter().collect();
282 let payload = self.storage_payload()?;
284 if let Ok(current) = std::fs::read(path_ref)
285 && json_payload_equal(¤t, &payload)
286 {
287 return Ok(path);
288 }
289 atomic_write(path_ref, &payload)?;
290 Ok(path)
291 }
292}
293
294fn is_auth_token_payload_key(key: &str) -> bool {
296 matches!(
297 key.trim().go_lower().as_str(),
298 "access_token"
299 | "refresh_token"
300 | "id_token"
301 | "session_id"
302 | "expired"
303 | "last_refresh"
304 | "expires_in"
305 | "timestamp"
306 | "token_type"
307 | "user_code"
308 | "verification_uri"
309 | "verification_uri_complete"
310 )
311}
312
313fn create_private_dir(dir: &std::path::Path) -> std::io::Result<()> {
315 let mut builder = std::fs::DirBuilder::new();
316 builder.recursive(true);
317 #[cfg(unix)]
318 std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
319 builder.create(dir)
320}
321
322fn json_payload_equal(a: &[u8], b: &[u8]) -> bool {
325 fn same(a: &Value, b: &Value) -> bool {
326 match (a, b) {
327 (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(),
328 (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| same(x, y)),
329 (Value::Object(x), Value::Object(y)) => {
330 x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same(v, w)))
331 }
332 _ => a == b,
333 }
334 }
335 let decode = |raw: &[u8]| crate::gojson::parse(raw).and_then(|n| n.to_value());
336 matches!((decode(a), decode(b)), (Ok(a), Ok(b)) if same(&a, &b))
337}
338
339pub fn atomic_write(path: &std::path::Path, data: &[u8]) -> Result<(), String> {
341 use std::io::Write as _;
342 let dir = match path.parent() {
343 Some(d) if !d.as_os_str().is_empty() => d,
344 _ => std::path::Path::new("."),
345 };
346 create_private_dir(dir).map_err(|e| {
347 format!(
348 "create auth directory: {}",
349 crate::hostauth::path_error("mkdir", dir, &e)
350 )
351 })?;
352 let mut options = std::fs::OpenOptions::new();
353 options.write(true).create_new(true);
354 #[cfg(unix)]
355 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
356 let mut attempt = 0u32;
358 let (tmp_path, mut tmp) = loop {
359 let nanos = std::time::SystemTime::now()
360 .duration_since(std::time::UNIX_EPOCH)
361 .map_or(0, |d| d.subsec_nanos());
362 let candidate = dir.join(format!(".plugin-auth-{}{nanos}{attempt}.tmp", std::process::id()));
363 match options.open(&candidate) {
364 Ok(file) => break (candidate, file),
365 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt < 10_000 => attempt += 1,
366 Err(e) => {
367 return Err(format!(
368 "create temp auth file: {}",
369 crate::hostauth::path_error("open", &candidate, &e)
370 ));
371 }
372 }
373 };
374 let result = tmp
375 .write_all(data)
376 .map_err(|e| {
377 format!(
378 "write temp auth file: {}",
379 crate::hostauth::path_error("write", &tmp_path, &e)
380 )
381 })
382 .and_then(|()| {
383 drop(tmp);
384 std::fs::rename(&tmp_path, path).map_err(|e| format!("rename temp auth file: {e}"))
385 });
386 let _ = std::fs::remove_file(&tmp_path);
387 result
388}
389
390impl PluginAuth {
391 pub fn view(&self) -> AuthView {
394 AuthView {
395 id: self.id.clone(),
396 provider: self.provider.clone(),
397 file_name: self.file_name.clone(),
398 label: self.label.clone(),
399 prefix: self.prefix.clone(),
400 proxy_url: self.proxy_url.clone(),
401 storage_json: self.storage_payload().unwrap_or_default(),
402 metadata: self.metadata.clone(),
403 attributes: self.attributes.clone(),
404 next_refresh_after: self.next_refresh_after,
405 }
406 }
407}
408
409#[derive(Debug, Clone, Default)]
411pub struct AuthView {
412 pub id: String,
413 pub provider: String,
414 pub file_name: String,
415 pub label: String,
416 pub prefix: String,
417 pub proxy_url: String,
418 pub storage_json: Bytes,
420 pub metadata: Metadata,
421 pub attributes: StringMap,
422 pub next_refresh_after: GoTime,
423}
424
425fn preserve_file_auth_priority(data: &mut AuthData, auth: &AuthView) {
427 if auth.attributes.get(ATTRIBUTE_SOURCE_BACKEND).map(String::as_str) != Some(AUTH_SOURCE_FILE) {
428 return;
429 }
430 for key in [
431 ATTRIBUTE_PATH,
432 ATTRIBUTE_SOURCE,
433 ATTRIBUTE_SOURCE_BACKEND,
434 ATTRIBUTE_FILE_PRIORITY,
435 ] {
436 if let Some(value) = auth.attributes.get(key) {
437 data.attributes.insert(key.into(), value.clone());
438 }
439 }
440 if auth.attributes.get(ATTRIBUTE_FILE_PRIORITY).map(String::as_str) != Some("true") {
441 data.attributes.remove(ATTRIBUTE_FILE_PRIORITY);
442 return;
443 }
444 match auth.attributes.get("priority") {
445 Some(p) => data.attributes.insert("priority".into(), p.clone()),
446 None => data.attributes.remove("priority"),
447 };
448 match auth.metadata.get("priority") {
449 Some(p) => data.metadata.insert("priority".into(), p.clone()),
450 None => data.metadata.remove("priority"),
451 };
452}
453
454pub fn refreshed_auth_data(resp: AuthRefreshResponse, auth: &AuthView) -> AuthData {
456 let mut data = resp.auth;
457 let fill = |v: &mut String, from: &str| {
458 if v.trim().is_empty() {
459 *v = from.to_owned();
460 }
461 };
462 fill(&mut data.provider, &auth.provider);
463 fill(&mut data.id, &auth.id);
464 fill(&mut data.file_name, &auth.file_name);
465 fill(&mut data.label, &auth.label);
466 fill(&mut data.prefix, &auth.prefix);
467 fill(&mut data.proxy_url, &auth.proxy_url);
468 if data.metadata.is_empty() {
469 data.metadata = auth.metadata.clone();
470 }
471 if data.attributes.is_empty() {
472 data.attributes = auth.attributes.clone();
473 } else {
474 for (k, v) in &auth.attributes {
475 data.attributes.entry(k.clone()).or_insert_with(|| v.clone());
476 }
477 }
478 preserve_file_auth_priority(&mut data, auth);
479 if data.storage_json.is_empty() {
480 data.storage_json = auth.storage_json.clone();
481 }
482 data.next_refresh_after = if resp.next_refresh_after.is_zero() {
483 auth.next_refresh_after
484 } else {
485 resp.next_refresh_after
486 };
487 data
488}
489
490fn plugin_oauth_aliases(cfg: &cpa_core::config::Config) -> BTreeMap<String, Vec<ModelAlias>> {
492 let mut out: BTreeMap<String, Vec<ModelAlias>> = BTreeMap::new();
493 for (provider, aliases) in cpa_core::registry::dynamic::global_aliases(cfg) {
494 let key = normalize_provider(&provider);
495 if key.is_empty() {
496 continue;
497 }
498 for alias in aliases {
499 let (name, value) = (alias.name.trim(), alias.alias.trim());
500 if !name.is_empty() && !value.is_empty() {
501 out.entry(key.clone()).or_default().push(ModelAlias {
502 name: name.into(),
503 alias: value.into(),
504 });
505 }
506 }
507 }
508 out
509}
510
511pub(crate) fn host_config_summary_of(cfg: &cpa_core::config::Config) -> HostConfigSummary {
513 let proxy_url = cfg
514 .document
515 .get("requests")
516 .and_then(|r| r.get("proxy-url"))
517 .map(crate::config::yaml_string)
518 .unwrap_or_default();
519 HostConfigSummary {
520 auth_dir: cfg.auth_dir.to_string_lossy().trim().to_owned(),
521 proxy_url: proxy_url.trim().to_owned(),
522 force_model_prefix: cfg.routing.force_model_prefix,
523 oauth_model_alias: plugin_oauth_aliases(cfg),
524 excluded_models: cpa_core::config::credentials::oauth_excluded(cfg)
525 .into_iter()
526 .filter_map(|(k, v)| {
527 let k = normalize_provider(&k);
528 (!k.is_empty()).then_some((k, v))
529 })
530 .collect(),
531 }
532}
533
534impl Host {
535 pub fn host_config_summary(&self) -> HostConfigSummary {
537 self.config()
538 .map(|cfg| host_config_summary_of(&cfg))
539 .unwrap_or_default()
540 }
541
542 pub fn auth_provider_identifiers(&self) -> Vec<String> {
544 self.active_records()
545 .into_iter()
546 .filter(|r| r.plugin.caps.auth_provider && !self.is_fused(&r.id))
547 .map(|r| normalize_provider(&r.plugin.auth_identifier))
548 .filter(|id| !id.is_empty())
549 .collect()
550 }
551
552 pub fn auth_provider_record(&self, provider: &str) -> Option<Record> {
554 let provider = normalize_provider(provider);
555 if provider.is_empty() {
556 return None;
557 }
558 self.active_records().into_iter().find(|r| {
559 r.plugin.caps.auth_provider
560 && !self.is_fused(&r.id)
561 && normalize_provider(&r.plugin.auth_identifier) == provider
562 })
563 }
564
565 pub fn has_auth_provider(&self, provider: &str) -> bool {
567 self.auth_provider_record(provider).is_some()
568 }
569
570 pub fn parse_auths(&self, req: AuthParseRequest) -> ParseAuthsResult {
574 self.parse_auths_for(req, false)
575 }
576
577 pub(crate) fn parse_auths_for(&self, req: AuthParseRequest, save: bool) -> ParseAuthsResult {
579 if !req.provider.trim().is_empty() {
580 let Some(record) = self.auth_provider_record(&req.provider) else {
581 return ParseAuthsResult::default();
582 };
583 return self.call_parse_auths(&record, req, save);
584 }
585 for record in self.active_records() {
586 if !record.plugin.caps.auth_provider || self.is_fused(&record.id) {
587 continue;
588 }
589 let result = self.call_parse_auths(&record, req.clone(), save);
590 if result.error.is_some() || result.handled {
591 return result;
592 }
593 }
594 ParseAuthsResult::default()
595 }
596
597 fn call_parse_auths(&self, record: &Record, mut req: AuthParseRequest, save: bool) -> ParseAuthsResult {
600 if self.is_fused(&record.id) || !self.record_current(record) {
601 return ParseAuthsResult::default();
602 }
603 if req.host.auth_dir.is_empty() {
604 req.host = self.host_config_summary();
605 }
606 req.provider = normalize_provider(&req.provider);
607 let identifier = normalize_provider(&record.plugin.auth_identifier);
608 if req.provider.is_empty() {
609 req.provider = identifier.clone();
610 }
611 let parsing = Parsing::new(self, record, &req.path, save);
612 let (instance, path) = (parsing.instance.clone(), parsing.path.clone());
615 let resp = record
616 .client
617 .call_blocking_in(method::AUTH_PARSE, &crate::gojson::to_vec(&req), move || {
618 ParsingHere::enter(instance, path)
619 })
620 .map_err(CallError::from)
621 .and_then(|raw| crate::rpc::decode_response(method::AUTH_PARSE, &raw));
622 let resp = self.fuse_on_panic(&record.id, method::AUTH_PARSE, resp);
623 drop(parsing);
624 let resp: AuthParseResponse = match resp {
625 Ok(resp) => resp,
626 Err(e) => return ParseAuthsResult::failed(false, e),
627 };
628 if !resp.handled {
629 return ParseAuthsResult::default();
630 }
631 let datas = if resp.auths.is_empty() {
632 vec![resp.auth]
633 } else {
634 resp.auths
635 };
636 let auth_dir = self.host_config_summary().auth_dir;
637 let mut auths = Vec::with_capacity(datas.len());
638 for mut data in datas {
639 if data.provider.trim().is_empty() {
640 data.provider = req.provider.clone();
641 }
642 if data.provider.trim().is_empty() {
643 data.provider = identifier.clone();
644 }
645 if normalize_provider(&data.provider).is_empty() {
646 let message = format!("auth provider {} returned auth without provider", record.id);
647 return ParseAuthsResult::failed(true, CallError::Other(message));
648 }
649 match PluginAuth::from_auth_data(data, &req.path, &req.file_name, &auth_dir) {
650 Some(parsed) => auths.push(parsed),
651 None => {
652 let message = format!("auth provider {} returned invalid auth data", record.id);
653 return ParseAuthsResult::failed(true, CallError::Other(message));
654 }
655 }
656 }
657 ParseAuthsResult {
658 auths,
659 handled: true,
660 error: None,
661 }
662 }
663
664 pub async fn start_login(
666 &self,
667 provider: &str,
668 base_url: &str,
669 metadata: Metadata,
670 scope: &RequestScope,
671 ) -> Result<Option<AuthLoginStartResponse>, CallError> {
672 let Some(record) = self.auth_provider_record(provider) else {
673 return Ok(None);
674 };
675 if !self.record_current(&record) {
676 return Ok(None);
677 }
678 let req = AuthLoginStartRequest {
679 provider: normalize_provider(provider),
680 base_url: base_url.trim().to_owned(),
681 host: self.host_config_summary(),
682 metadata,
683 };
684 self.call_with_callback(&record, method::AUTH_LOGIN_START, &req, scope)
685 .await
686 .map(Some)
687 }
688
689 pub async fn poll_login(
691 &self,
692 provider: &str,
693 state: &str,
694 metadata: Metadata,
695 scope: &RequestScope,
696 ) -> Result<Option<AuthLoginPollResponse>, CallError> {
697 let Some(record) = self.auth_provider_record(provider) else {
698 return Ok(None);
699 };
700 if !self.record_current(&record) {
701 return Ok(None);
702 }
703 let req = AuthLoginPollRequest {
704 provider: normalize_provider(provider),
705 state: state.trim().to_owned(),
706 host: self.host_config_summary(),
707 metadata,
708 };
709 self.call_with_callback(&record, method::AUTH_LOGIN_POLL, &req, scope)
710 .await
711 .map(Some)
712 }
713
714 pub async fn refresh_auth(&self, auth: &AuthView, scope: &RequestScope) -> Result<Option<PluginAuth>, CallError> {
716 let Some(record) = self.auth_provider_record(&auth.provider) else {
717 return Ok(None);
718 };
719 if !self.record_current(&record) {
720 return Ok(None);
721 }
722 let req = AuthRefreshRequest {
723 auth_id: auth.id.clone(),
724 auth_provider: auth.provider.clone(),
725 storage_json: auth.storage_json.clone(),
726 metadata: auth.metadata.clone(),
727 attributes: auth.attributes.clone(),
728 host: self.host_config_summary(),
729 };
730 let resp: AuthRefreshResponse = self
731 .call_with_callback(&record, method::AUTH_REFRESH, &req, scope)
732 .await?;
733 let data = refreshed_auth_data(resp, auth);
734 let path = auth.attributes.get(ATTRIBUTE_PATH).cloned().unwrap_or_default();
735 let file_name = data.file_name.clone();
736 PluginAuth::from_auth_data(data, &path, &file_name, &self.host_config_summary().auth_dir)
737 .map(Some)
738 .ok_or_else(|| CallError::Other("auth provider refresh returned invalid auth data".into()))
739 }
740
741 pub async fn frontend_auth_providers(&self) -> (Vec<(String, String)>, Option<String>) {
746 let mut providers = Vec::new();
747 let mut exclusive: Option<(String, String, i64)> = None;
748 for record in self.active_records() {
749 if !record.plugin.caps.frontend_auth_provider || self.is_fused(&record.id) {
750 continue;
751 }
752 let Some(key) = self.frontend_auth_key(&record).await else {
753 continue;
754 };
755 if record.plugin.caps.frontend_auth_provider_exclusive {
756 let better = match &exclusive {
757 None => true,
758 Some((_, id, priority)) => {
759 record.priority > *priority || (record.priority == *priority && record.id < *id)
760 }
761 };
762 if better {
763 exclusive = Some((key.clone(), record.id.clone(), record.priority));
764 }
765 }
766 providers.push((key, record.id.clone()));
767 }
768 (providers, exclusive.map(|(key, _, _)| key))
769 }
770
771 pub async fn frontend_auth_identifier(&self, plugin_id: &str) -> Option<String> {
774 let record = self.record(plugin_id)?;
775 if !record.plugin.caps.frontend_auth_provider {
776 return None;
777 }
778 self.frontend_auth_key(&record).await
779 }
780
781 async fn frontend_auth_key(&self, record: &Record) -> Option<String> {
783 let identifier = crate::rpc::identifier(&record.client, method::FRONTEND_AUTH_IDENTIFIER).await;
784 let id = record.id.trim();
785 (!id.is_empty() && !identifier.is_empty()).then(|| format!("plugin:{id}:{identifier}"))
786 }
787
788 pub async fn frontend_authenticate(
791 &self,
792 plugin_id: &str,
793 req: &FrontendAuthRequest,
794 ) -> Option<FrontendAuthOutcome> {
795 let record = self.record(plugin_id)?;
796 if !self.live(&record) {
797 return None;
798 }
799 let resp: FrontendAuthResponse = self.call(&record, method::FRONTEND_AUTH_AUTHENTICATE, req).await.ok()?;
800 if !resp.authenticated {
801 return None;
802 }
803 let provider = self.frontend_auth_key(&record).await?;
804 Some(FrontendAuthOutcome {
805 provider,
806 principal: resp.principal,
807 metadata: resp.metadata,
808 })
809 }
810}
811
812#[derive(Debug, Default)]
814pub struct ParseAuthsResult {
815 pub auths: Vec<PluginAuth>,
816 pub handled: bool,
817 pub error: Option<CallError>,
818}
819
820std::thread_local! {
821 static PARSING_HERE: std::cell::RefCell<Vec<(std::sync::Arc<crate::client::CallbackInstance>, std::path::PathBuf)>> =
826 const { std::cell::RefCell::new(Vec::new()) };
827}
828
829struct Parsing<'a> {
832 host: &'a Host,
833 instance: std::sync::Arc<crate::client::CallbackInstance>,
834 path: std::path::PathBuf,
835 save: bool,
836}
837
838impl<'a> Parsing<'a> {
839 fn new(host: &'a Host, record: &Record, path: &str, save: bool) -> Self {
840 let instance = record.client.instance().clone();
841 let path = cpa_core::config::credentials::absolute_clean_path(std::path::Path::new(path));
842 crate::host::lock(&host.inner.auth_parses).push((instance.clone(), path.clone(), save));
843 Self {
844 host,
845 instance,
846 path,
847 save,
848 }
849 }
850
851 fn is(&self, instance: &std::sync::Arc<crate::client::CallbackInstance>, path: &std::path::Path) -> bool {
852 std::sync::Arc::ptr_eq(instance, &self.instance) && path == self.path
853 }
854}
855
856struct ParsingHere {
859 instance: std::sync::Arc<crate::client::CallbackInstance>,
860 path: std::path::PathBuf,
861}
862
863impl ParsingHere {
864 fn enter(instance: std::sync::Arc<crate::client::CallbackInstance>, path: std::path::PathBuf) -> Self {
865 PARSING_HERE.with_borrow_mut(|here| here.push((instance.clone(), path.clone())));
866 Self { instance, path }
867 }
868}
869
870impl Drop for ParsingHere {
871 fn drop(&mut self) {
872 PARSING_HERE.with_borrow_mut(|here| {
873 if let Some(at) = here
874 .iter()
875 .rposition(|(i, p)| std::sync::Arc::ptr_eq(i, &self.instance) && *p == self.path)
876 {
877 here.remove(at);
878 }
879 });
880 }
881}
882
883impl Drop for Parsing<'_> {
884 fn drop(&mut self) {
885 let mut parses = crate::host::lock(&self.host.inner.auth_parses);
886 if let Some(at) = parses
887 .iter()
888 .position(|(i, p, save)| self.is(i, p) && *save == self.save)
889 {
890 parses.swap_remove(at);
891 }
892 }
893}
894
895#[derive(Debug, Clone, Copy, PartialEq, Eq)]
897pub(crate) enum SaveParse {
898 Parse,
900 Nested,
904 Refused,
908}
909
910impl Host {
911 pub(crate) fn save_parse(
913 &self,
914 instance: &std::sync::Arc<crate::client::CallbackInstance>,
915 path: &std::path::Path,
916 ) -> SaveParse {
917 let path = cpa_core::config::credentials::absolute_clean_path(path);
918 let same = |i: &std::sync::Arc<crate::client::CallbackInstance>, p: &std::path::PathBuf| {
919 std::sync::Arc::ptr_eq(i, instance) && *p == path
920 };
921 if PARSING_HERE.with_borrow(|here| here.iter().any(|(i, p)| same(i, p))) {
922 return SaveParse::Nested;
923 }
924 if crate::host::lock(&self.inner.auth_parses)
925 .iter()
926 .any(|(i, p, save)| *save && same(i, p))
927 {
928 return SaveParse::Refused;
929 }
930 SaveParse::Parse
931 }
932}
933
934impl ParseAuthsResult {
935 fn failed(handled: bool, error: CallError) -> Self {
936 Self {
937 auths: Vec::new(),
938 handled,
939 error: Some(error),
940 }
941 }
942}
943
944impl Host {
945 pub fn auth_parser(&self) -> std::sync::Arc<dyn cpa_core::config::credentials::PluginAuthParser> {
950 self.inner
951 .auth_parser_installed
952 .store(true, std::sync::atomic::Ordering::Release);
953 let state = self.state();
954 self.publish_hook_activity(&state, &self.snapshot().records);
955 drop(state);
956 self.inner
958 .auth_parser
959 .get_or_init(|| std::sync::Arc::new(AuthParser(std::sync::Arc::downgrade(&self.inner))))
960 .clone()
961 }
962}
963
964struct AuthParser(std::sync::Weak<crate::host::Inner>);
965
966impl cpa_core::config::credentials::PluginAuthParser for AuthParser {
967 fn parse_auths(
968 &self,
969 req: &cpa_core::config::credentials::ParseRequest<'_>,
970 ) -> cpa_core::config::credentials::Parsed {
971 use cpa_core::config::credentials::Parsed;
972 let Some(inner) = self.0.upgrade() else {
973 return Parsed::NotHandled;
974 };
975 let result = Host::from_inner(inner).parse_auths(AuthParseRequest {
976 provider: req.provider.to_owned(),
977 path: req.path.display().to_string(),
978 file_name: req.file_name.to_owned(),
979 raw_json: Bytes::copy_from_slice(req.raw_json),
980 ..Default::default()
981 });
982 if result.error.is_some() || !result.handled {
984 return Parsed::NotHandled;
985 }
986 Parsed::Handled(result.auths.into_iter().map(PluginAuth::into_parsed).collect())
987 }
988}
989
990impl PluginAuth {
991 pub(crate) fn into_parsed(self) -> cpa_core::config::credentials::ParsedAuth {
995 let metadata = self
996 .storage_payload()
997 .ok()
998 .and_then(|payload| serde_json::from_slice(&payload).ok())
999 .unwrap_or_else(|| self.metadata.clone().into_iter().collect());
1000 cpa_core::config::credentials::ParsedAuth {
1001 provider: self.provider,
1002 id: self.id,
1003 file_name: self.file_name,
1004 label: self.label,
1005 prefix: self.prefix,
1006 proxy_url: self.proxy_url,
1007 disabled: self.disabled,
1008 metadata,
1009 attributes: self.attributes,
1010 next_refresh_after: self.next_refresh_after.0.map(std::time::SystemTime::from),
1011 }
1012 }
1013}
1014
1015#[derive(Debug, Clone, PartialEq, Eq)]
1017pub struct FrontendAuthOutcome {
1018 pub provider: String,
1019 pub principal: String,
1020 pub metadata: StringMap,
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025 #[cfg(unix)]
1027 #[test]
1028 fn save_file_follows_go_filestore() {
1029 use std::os::unix::fs::PermissionsExt as _;
1030 let dir = std::env::temp_dir().join(format!("cpa-plugin-save-file-{}", std::process::id()));
1031 let _ = std::fs::remove_dir_all(&dir);
1032 std::fs::create_dir_all(&dir).unwrap();
1033 let base = dir.to_string_lossy().into_owned();
1034 let auth = |file: &str, disabled: bool| {
1035 let data = AuthData {
1036 provider: "Rec".into(),
1037 file_name: file.into(),
1038 disabled,
1039 storage_json: Bytes::from_static(br#"{"k":1,"base-url":"u"}"#),
1040 ..Default::default()
1041 };
1042 PluginAuth::from_auth_data(data, "", "", &base).unwrap()
1043 };
1044 assert_eq!(auth("gone.json", true).save_file(&base, false).unwrap(), "");
1046 assert!(!dir.join("gone.json").exists());
1047 let path = auth("new.json", false).save_file(&base, false).unwrap();
1049 assert_eq!(path, dir.join("new.json").to_string_lossy());
1050 assert_eq!(
1051 std::fs::read_to_string(&path).unwrap(),
1052 r#"{"base_url":"u","disabled":false,"k":1,"type":"rec"}"#
1053 );
1054 assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1055 std::fs::write(
1057 &path,
1058 r#"{ "k": 1.0, "type": "rec", "disabled": false, "base_url": "u" }"#,
1059 )
1060 .unwrap();
1061 auth("new.json", false).save_file(&base, false).unwrap();
1062 assert!(std::fs::read_to_string(&path).unwrap().starts_with("{ "));
1063 if unsafe { libc::geteuid() } != 0 {
1066 let locked = dir.join("locked");
1067 std::fs::create_dir_all(&locked).unwrap();
1068 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
1069 let e = auth("locked/x.json", true).save_file(&base, false).unwrap_err();
1070 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).unwrap();
1071 assert!(e.starts_with("create temp auth file: open "), "{e}");
1072 assert!(e.ends_with(": permission denied"), "{e}");
1073 }
1074 let _ = std::fs::remove_dir_all(&dir);
1075 }
1076
1077 use super::*;
1078
1079 #[test]
1081 fn auth_data_conversion_and_storage_follow_go() {
1082 let data = AuthData {
1083 provider: " Plugin-X ".into(),
1084 storage_json: Bytes::from_static(br#"{"token":"t","priority":1,"base-url":"old"}"#),
1085 metadata: [
1086 ("base-url".to_owned(), Value::from("u")),
1087 ("email".to_owned(), Value::from("e")),
1088 ]
1089 .into(),
1090 ..Default::default()
1091 };
1092 let auth = PluginAuth::from_auth_data(data, "/auth/sub/a.json", "", "/auth").unwrap();
1093 assert_eq!(auth.provider, "plugin-x");
1094 assert_eq!(auth.id, "sub/a.json");
1095 assert_eq!(auth.attributes["source_backend"], "file");
1096 assert_eq!(auth.attributes["source"], "/auth/sub/a.json");
1097 assert_eq!(auth.metadata["type"], "plugin-x");
1098 let payload = auth.storage_payload().unwrap();
1099 assert_eq!(
1100 &payload[..],
1101 br#"{"base_url":"u","email":"e","priority":1,"token":"t","type":"plugin-x"}"#
1102 );
1103 assert!(PluginAuth::from_auth_data(AuthData::default(), "", "", "").is_none());
1104 for (path, dir, want) in [
1106 ("/auth/sub/a.json", "/auth", "sub/a.json"),
1107 ("/auth/../other/t.json", "/auth", "/other/t.json"),
1108 ("/elsewhere/x.json", "/auth", "/elsewhere/x.json"),
1109 ("/auth", "/auth", "."),
1110 ("/auth/", "/auth/", "."),
1111 ("rel/a.json", "rel", "a.json"),
1112 ("rel/a.json", "/auth", "rel/a.json"),
1113 ("/auth/..x/a.json", "/auth", "/auth/..x/a.json"),
1114 ("/auth/a\\b.json", "/auth", "a\\b.json"),
1115 ("/auth//x/./y.json", "/auth/", "x/y.json"),
1116 ("a.json", "", "a.json"),
1117 ("/a/b/c", "/a/x/y", "/a/b/c"),
1118 ("x/y", ".", "x/y"),
1119 ("../q", ".", "../q"),
1120 ] {
1121 assert_eq!(auth_id_for_path(path, dir), want, "{path} in {dir}");
1122 }
1123 for (targ, base, want) in [
1124 ("/a/b/c", "/a/x/y", Some("../../b/c")),
1125 ("rel/a.json", "/auth", None),
1126 ("/auth/../other/t.json", "/auth", Some("../other/t.json")),
1127 ("x/y", ".", Some("x/y")),
1128 (".", "a", Some("..")),
1129 (".", "a/b", Some("../..")),
1130 ("a/c", "a/b", Some("../c")),
1131 ] {
1132 assert_eq!(crate::platform::rel(base, targ).as_deref(), want, "{targ} from {base}");
1133 }
1134 }
1135}