1use std::collections::HashMap;
2
3use async_trait::async_trait;
4use pipedash_plugin_api::*;
5use tracing::{
6 debug,
7 info,
8 warn,
9};
10
11use crate::client::PodLogRequest;
12use crate::log_dialect::ArgocdLogDialect;
13use crate::{
14 client,
15 config,
16 logs,
17 mapper,
18 metadata,
19 sign_in,
20};
21
22const DEFAULT_PAGE_SIZE: usize = 1000;
23
24pub struct ArgocdPlugin {
25 metadata: PluginMetadata,
26 client: Option<client::ArgocdClient>,
27 provider_id: Option<i64>,
28 config: HashMap<String, String>,
29 server_url: Option<String>,
30 status_source: Option<StatusSource>,
31 organizations_filter: Option<Vec<String>>,
32}
33
34impl Default for ArgocdPlugin {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40impl ArgocdPlugin {
41 pub fn new() -> Self {
42 Self {
43 metadata: metadata::create_metadata(),
44 client: None,
45 provider_id: None,
46 config: HashMap::new(),
47 server_url: None,
48 status_source: None,
49 organizations_filter: None,
50 }
51 }
52
53 fn client(&self) -> PluginResult<&client::ArgocdClient> {
54 self.client
55 .as_ref()
56 .ok_or_else(|| PluginError::Internal("Plugin not initialized".to_string()))
57 }
58
59 fn get_server_url(&self) -> PluginResult<&str> {
60 self.server_url
61 .as_deref()
62 .ok_or_else(|| PluginError::Internal("Server URL not set".to_string()))
63 }
64
65 async fn read_pod_log(
66 &self, app_name: &str, namespace: &str, pod_name: &str, sink: &mut LogSink,
67 ) -> PluginResult<()> {
68 let client = self.client()?;
69 let pod = client.pod(app_name, namespace, pod_name).await?;
70 let events = client
71 .pod_events(app_name, namespace, pod_name, &pod.metadata.uid)
72 .await?;
73 let mut out = Vec::new();
74 logs::write_pod_summary(&pod, namespace, pod_name, events, &mut out);
75 sink.write(out.into()).await?;
76
77 for container in logs::container_logs(&pod) {
78 let mut header = Vec::new();
79 container.write_header(&mut header);
80 sink.write(header.into()).await?;
81 let request = PodLogRequest {
82 namespace,
83 pod: pod_name,
84 container: container.name,
85 previous: container.previous,
86 };
87 if client.stream_pod_log(app_name, request, sink).await? == 0 {
88 let mut empty = Vec::new();
89 logs::write_no_output(&mut empty);
90 sink.write(empty.into()).await?;
91 }
92 }
93 Ok(())
94 }
95}
96
97#[async_trait]
98impl Plugin for ArgocdPlugin {
99 fn metadata(&self) -> &PluginMetadata {
100 &self.metadata
101 }
102
103 fn provider_type(&self) -> &str {
104 "argocd"
105 }
106
107 fn client_options(&self, config: &HashMap<String, String>) -> ClientOptions {
108 ClientOptions {
109 origin: config::get_server_url(config)
110 .ok()
111 .and_then(|url| reqwest::Url::parse(&url).ok()),
112 accept_invalid_certs: config::is_insecure(config),
113 }
114 }
115
116 fn status_source(&self) -> Option<&StatusSource> {
117 self.status_source.as_ref()
118 }
119
120 fn initialize(
121 &mut self, provider_id: i64, config: HashMap<String, String>,
122 http_client: Option<std::sync::Arc<reqwest::Client>>,
123 ) -> PluginResult<()> {
124 info!(provider_id, "Initializing ArgoCD plugin");
125 debug!(config_keys = ?config.keys().collect::<Vec<_>>());
126
127 let server_url = config::get_server_url(&config)?;
128 debug!(server_url, "Configured server URL");
129
130 let token = config::get_token(&config)?;
131 debug!(token_length = token.len(), "Retrieved authentication token");
132
133 let insecure = config::is_insecure(&config);
134 if insecure {
135 warn!("Insecure TLS mode enabled - certificate verification disabled");
136 }
137
138 let organizations_filter = config::parse_organizations_filter(&config);
139 debug!(?organizations_filter, "Organizations filter configured");
140
141 let status_source = custom_status_source(&config)?;
142
143 let http_client = http_client.ok_or_else(|| {
144 PluginError::Internal("ArgoCD plugin requires an HTTP client".to_string())
145 })?;
146 let client = client::ArgocdClient::new(http_client, &server_url, &token);
147 debug!("ArgoCD client created successfully");
148
149 self.client = Some(client);
150 self.provider_id = Some(provider_id);
151 self.server_url = Some(server_url);
152 self.status_source = status_source;
153 self.organizations_filter = organizations_filter;
154 self.config = config;
155
156 info!("ArgoCD plugin initialization complete");
157 Ok(())
158 }
159
160 async fn validate_credentials(&self) -> PluginResult<bool> {
161 debug!("Validating ArgoCD credentials");
162 let client = self.client()?;
163 match client.list_applications(None).await {
164 Ok(apps) => {
165 info!(app_count = apps.len(), "Credentials validated successfully");
166 Ok(true)
167 }
168 Err(e) => {
169 warn!(error = ?e, "Credential validation failed");
170 Err(e)
171 }
172 }
173 }
174
175 async fn fetch_available_pipelines(
176 &self, params: Option<PaginationParams>,
177 ) -> PluginResult<PaginatedResponse<AvailablePipeline>> {
178 debug!("Fetching available pipelines");
179 let client = self.client()?;
180
181 let mut apps = client.list_applications(None).await?;
182 debug!(
183 total_apps = apps.len(),
184 "Retrieved applications from ArgoCD"
185 );
186
187 if let Some(ref orgs_filter) = self.organizations_filter {
188 debug!(?orgs_filter, "Filtering applications by organizations");
189 apps.retain(|app| {
190 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
191 orgs_filter.contains(&git_org)
192 });
193 debug!(
194 filtered_apps = apps.len(),
195 "Applications after organization filtering"
196 );
197 }
198
199 let total_count = apps.len();
200 let mut available_pipelines: Vec<AvailablePipeline> =
201 apps.iter().map(mapper::map_available_pipeline).collect();
202
203 let (page, page_size) = if let Some(p) = params {
204 let page_num = if p.page == 0 { 1 } else { p.page };
205 let size = if p.page_size == 0 {
206 DEFAULT_PAGE_SIZE
207 } else {
208 p.page_size
209 };
210
211 let offset = (page_num.saturating_sub(1)) * size;
212
213 available_pipelines = available_pipelines
214 .into_iter()
215 .skip(offset)
216 .take(size)
217 .collect();
218
219 (page_num, size)
220 } else {
221 (1, DEFAULT_PAGE_SIZE)
222 };
223
224 debug!(
225 pipeline_count = available_pipelines.len(),
226 total = total_count,
227 page,
228 page_size,
229 "Mapped and paginated available pipelines"
230 );
231
232 Ok(PaginatedResponse::new(
233 available_pipelines,
234 page,
235 page_size,
236 total_count,
237 ))
238 }
239
240 async fn fetch_organizations(&self) -> PluginResult<Vec<Organization>> {
241 debug!("Fetching Git organizations from applications");
242 let client = self.client()?;
243
244 let apps = client.list_applications(None).await?;
245
246 debug!(
247 app_count = apps.len(),
248 "Extracting organizations from applications"
249 );
250
251 let mut orgs_map: std::collections::HashMap<String, Organization> =
252 std::collections::HashMap::new();
253
254 for app in apps {
255 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
256
257 if git_org == "unknown" || git_org.is_empty() {
258 continue;
259 }
260
261 if !orgs_map.contains_key(&git_org) {
262 orgs_map.insert(
263 git_org.clone(),
264 Organization {
265 id: git_org.clone(),
266 name: git_org.clone(),
267 description: Some(format!("Git Organization: {}", git_org)),
268 },
269 );
270 }
271 }
272
273 let organizations: Vec<Organization> = orgs_map.into_values().collect();
274 debug!(
275 org_count = organizations.len(),
276 org_names = ?organizations.iter().map(|o| &o.name).collect::<Vec<_>>(),
277 "Extracted unique Git organizations"
278 );
279
280 Ok(organizations)
281 }
282
283 async fn fetch_available_pipelines_filtered(
284 &self, org: Option<String>, search: Option<String>, params: Option<PaginationParams>,
285 ) -> PluginResult<PaginatedResponse<AvailablePipeline>> {
286 debug!(?org, ?search, "Fetching filtered available pipelines");
287
288 let client = self.client()?;
289
290 let apps = client.list_applications(None).await?;
291
292 debug!(
293 total_apps = apps.len(),
294 "Retrieved applications for filtering"
295 );
296
297 let filtered_apps: Vec<_> = apps
298 .into_iter()
299 .filter(|app| {
300 let org_match = org.as_ref().is_none_or(|o| {
301 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
302 git_org == *o
303 });
304
305 let search_match = search.as_ref().is_none_or(|s| {
306 app.metadata.name.to_lowercase().contains(&s.to_lowercase())
307 || app
308 .spec
309 .primary_source()
310 .repo_url
311 .to_lowercase()
312 .contains(&s.to_lowercase())
313 });
314
315 org_match && search_match
316 })
317 .collect();
318
319 debug!(
320 filtered_apps = filtered_apps.len(),
321 "Applications after applying filters"
322 );
323
324 let total_count = filtered_apps.len();
325 let mut available_pipelines: Vec<AvailablePipeline> = filtered_apps
326 .iter()
327 .map(mapper::map_available_pipeline)
328 .collect();
329
330 let (page, page_size) = if let Some(p) = params {
331 let page_num = if p.page == 0 { 1 } else { p.page };
332 let size = if p.page_size == 0 {
333 DEFAULT_PAGE_SIZE
334 } else {
335 p.page_size
336 };
337
338 let offset = (page_num.saturating_sub(1)) * size;
339
340 available_pipelines = available_pipelines
341 .into_iter()
342 .skip(offset)
343 .take(size)
344 .collect();
345
346 (page_num, size)
347 } else {
348 (1, DEFAULT_PAGE_SIZE)
349 };
350
351 debug!(
352 pipeline_count = available_pipelines.len(),
353 total = total_count,
354 page,
355 page_size,
356 "Mapped and paginated filtered pipelines"
357 );
358
359 Ok(PaginatedResponse::new(
360 available_pipelines,
361 page,
362 page_size,
363 total_count,
364 ))
365 }
366
367 async fn fetch_pipelines(&self) -> PluginResult<Vec<Pipeline>> {
368 debug!("Fetching configured pipelines");
369 let provider_id = self
370 .provider_id
371 .ok_or_else(|| PluginError::Internal("Provider ID not set".to_string()))?;
372
373 let client = self.client()?;
374 let server_url = self.get_server_url()?;
375 debug!(server_url, "Using configured server URL");
376
377 let mut apps = client.list_applications(None).await?;
378 debug!(total_apps = apps.len(), "Retrieved all applications");
379
380 if let Some(ref orgs_filter) = self.organizations_filter {
381 debug!(?orgs_filter, "Applying organization filter");
382 apps.retain(|app| {
383 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
384 orgs_filter.contains(&git_org)
385 });
386 debug!(
387 filtered_apps = apps.len(),
388 "Applications after organization filter"
389 );
390 }
391
392 let filtered_apps = if let Some(selected_items) = config::parse_selected_items(&self.config)
393 {
394 debug!(
395 selected_count = selected_items.len(),
396 "Applying user selection filter"
397 );
398 apps.into_iter()
399 .filter(|app| selected_items.contains(&app.metadata.name))
400 .collect()
401 } else {
402 debug!("No user selection - returning all applications");
403 apps
404 };
405
406 debug!(
407 final_apps = filtered_apps.len(),
408 "Applications after all filters"
409 );
410
411 let pipelines: Vec<Pipeline> = filtered_apps
412 .iter()
413 .map(|app| mapper::map_application_to_pipeline(app, provider_id, server_url))
414 .collect();
415
416 debug!(
417 pipeline_count = pipelines.len(),
418 "Mapped applications to pipelines"
419 );
420 Ok(pipelines)
421 }
422
423 async fn fetch_run_history(
424 &self, pipeline_id: &str, limit: usize,
425 ) -> PluginResult<Vec<PipelineRun>> {
426 let (provider_id, _namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
427 let client = self.client()?;
428 let server_url = self.get_server_url()?;
429
430 let app = client.get_application(&app_name).await?;
431
432 Ok(mapper::map_runs(&app, provider_id, server_url, limit))
433 }
434
435 async fn fetch_run_details(
436 &self, pipeline_id: &str, run_number: i64,
437 ) -> PluginResult<PipelineRun> {
438 let (provider_id, _namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
439 let client = self.client()?;
440 let server_url = self.get_server_url()?;
441
442 let app = client.get_application(&app_name).await?;
443
444 if let Some(operation) = mapper::map_operation_to_run(&app, provider_id, server_url) {
445 if operation.run_number == run_number {
446 return Ok(operation);
447 }
448 }
449
450 let history = app.status.history.as_deref().unwrap_or(&[]);
451 let history_item = history
452 .iter()
453 .find(|h| h.deployed_at.timestamp() == run_number)
454 .ok_or_else(|| {
455 PluginError::PipelineNotFound(format!("Run {} not found", run_number))
456 })?;
457
458 Ok(mapper::map_history_to_run(
459 history_item,
460 &app,
461 provider_id,
462 server_url,
463 ))
464 }
465
466 async fn fetch_log_nodes(&self, run: RunRef<'_>) -> PluginResult<Vec<LogNode>> {
467 let (_provider_id, _namespace, app_name) = config::parse_pipeline_id(run.pipeline_id)?;
468 let client = self.client()?;
469 let (app, tree) = tokio::try_join!(
470 client.get_application(&app_name),
471 client.resource_tree(&app_name)
472 )?;
473 let sync = logs::find_sync(&app, run.run_number).ok_or_else(|| {
474 PluginError::PipelineNotFound(format!("Run {} not found", run.run_number))
475 })?;
476
477 Ok(logs::log_nodes(
478 &sync,
479 &tree,
480 &mapper::app_url(self.get_server_url()?, &app_name),
481 ))
482 }
483
484 async fn read_log(
485 &self, run: RunRef<'_>, node_id: &str, sink: &mut LogSink,
486 ) -> PluginResult<()> {
487 let (_provider_id, _namespace, app_name) = config::parse_pipeline_id(run.pipeline_id)?;
488 let client = self.client()?;
489 let mut out = Vec::new();
490
491 if node_id == logs::SYNC_NODE {
492 let app = client.get_application(&app_name).await?;
493 let sync = logs::find_sync(&app, run.run_number).ok_or_else(|| {
494 PluginError::PipelineNotFound(format!("Run {} not found", run.run_number))
495 })?;
496 logs::write_sync(&sync, &mut out);
497 } else if node_id == logs::EVENTS_NODE {
498 logs::write_events(client.application_events(&app_name).await?, &mut out);
499 } else {
500 let (namespace, pod_name) = logs::pod_of_node(node_id).ok_or_else(|| {
501 PluginError::InvalidConfig(format!("Invalid ArgoCD log node: {node_id}"))
502 })?;
503 return self
504 .read_pod_log(&app_name, namespace, pod_name, sink)
505 .await;
506 }
507 sink.write(out.into()).await
508 }
509
510 fn log_dialect(&self) -> &'static dyn LogDialect {
511 &ArgocdLogDialect
512 }
513
514 async fn trigger_pipeline(&self, params: TriggerParams) -> PluginResult<String> {
515 let (_provider_id, _namespace, app_name) = config::parse_pipeline_id(¶ms.workflow_id)?;
516 let client = self.client()?;
517
518 let inputs = params.inputs.as_ref();
519
520 let revision = inputs
521 .and_then(|i| i.get("revision"))
522 .and_then(|v| v.as_str())
523 .map(String::from);
524
525 let prune = inputs
526 .and_then(|i| i.get("prune"))
527 .and_then(|v| v.as_bool())
528 .unwrap_or(false);
529
530 let dry_run = inputs
531 .and_then(|i| i.get("dry_run"))
532 .and_then(|v| v.as_bool())
533 .unwrap_or(false);
534
535 let force = inputs
536 .and_then(|i| i.get("force"))
537 .and_then(|v| v.as_bool())
538 .unwrap_or(false);
539
540 let apply_only = inputs
541 .and_then(|i| i.get("apply_only"))
542 .and_then(|v| v.as_bool())
543 .unwrap_or(false);
544
545 info!(
546 app_name,
547 ?revision,
548 prune,
549 dry_run,
550 force,
551 apply_only,
552 "Triggering ArgoCD sync operation"
553 );
554
555 client
556 .sync_application(&app_name, revision, prune, dry_run, force, apply_only)
557 .await?;
558
559 let sync_type = if dry_run { "Dry run" } else { "Sync" };
560 Ok(format!(
561 "{} triggered for application: {}",
562 sync_type, app_name
563 ))
564 }
565
566 async fn cancel_run(&self, pipeline_id: &str, _run_number: i64) -> PluginResult<()> {
567 let (_provider_id, _namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
568 let client = self.client()?;
569
570 client.terminate_operation(&app_name).await?;
571
572 Ok(())
573 }
574
575 async fn fetch_workflow_parameters(
576 &self, _workflow_id: &str,
577 ) -> PluginResult<Vec<WorkflowParameter>> {
578 Ok(vec![
579 WorkflowParameter {
580 name: "revision".to_string(),
581 label: Some("Revision".to_string()),
582 description: Some("Git revision (branch, tag, or commit SHA) to sync to. Leave empty to use target revision.".to_string()),
583 param_type: WorkflowParameterType::String { default: None },
584 required: false,
585 },
586 WorkflowParameter {
587 name: "prune".to_string(),
588 label: Some("Prune Resources".to_string()),
589 description: Some("Delete resources that are no longer defined in Git".to_string()),
590 param_type: WorkflowParameterType::Boolean { default: false },
591 required: false,
592 },
593 WorkflowParameter {
594 name: "dry_run".to_string(),
595 label: Some("Dry Run".to_string()),
596 description: Some("Preview sync without applying changes".to_string()),
597 param_type: WorkflowParameterType::Boolean { default: false },
598 required: false,
599 },
600 WorkflowParameter {
601 name: "force".to_string(),
602 label: Some("Force Sync".to_string(),),
603 description: Some("Force sync even if resources are already synced (overrides any state)".to_string()),
604 param_type: WorkflowParameterType::Boolean { default: false },
605 required: false,
606 },
607 WorkflowParameter {
608 name: "apply_only".to_string(),
609 label: Some("Apply Only (Skip Hooks)".to_string()),
610 description: Some("Skip pre and post sync hooks".to_string()),
611 param_type: WorkflowParameterType::Boolean { default: false },
612 required: false,
613 },
614 ])
615 }
616
617 async fn fetch_agents(&self) -> PluginResult<Vec<BuildAgent>> {
618 Ok(vec![])
619 }
620
621 async fn fetch_artifacts(&self, _run_id: &str) -> PluginResult<Vec<BuildArtifact>> {
622 Ok(vec![])
623 }
624
625 async fn fetch_queues(&self) -> PluginResult<Vec<BuildQueue>> {
626 Ok(vec![])
627 }
628
629 fn get_migrations(&self) -> Vec<String> {
630 vec![]
631 }
632
633 async fn get_field_options(
634 &self, field_key: &str, _config: &HashMap<String, String>,
635 ) -> PluginResult<Vec<String>> {
636 if field_key == "organizations" {
637 let apps = self.client()?.list_applications(None).await?;
638
639 let mut git_orgs = std::collections::HashSet::new();
640 for app in apps {
641 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
642 if git_org != "unknown" && !git_org.is_empty() {
643 git_orgs.insert(git_org);
644 }
645 }
646
647 let mut orgs: Vec<String> = git_orgs.into_iter().collect();
648 orgs.sort();
649
650 debug!(
651 org_count = orgs.len(),
652 "Returning Git organizations for dropdown"
653 );
654 Ok(orgs)
655 } else {
656 Ok(vec![])
657 }
658 }
659
660 async fn sign_in_client(
661 &self, config: &HashMap<String, String>, http_client: &reqwest::Client,
662 ) -> PluginResult<SignInClient> {
663 let server_url = config::get_server_url(config)?;
664 let settings = client::ArgocdClient::fetch_settings(http_client, &server_url).await?;
665 sign_in::client_for(&settings, &server_url)
666 }
667}
668
669#[cfg(test)]
670mod tests {
671 use std::sync::Arc;
672
673 use super::*;
674
675 fn cfg(pairs: &[(&str, &str)]) -> HashMap<String, String> {
676 pairs
677 .iter()
678 .map(|(k, v)| (k.to_string(), v.to_string()))
679 .collect()
680 }
681
682 #[test]
683 fn client_options_parse_origin_and_insecure() {
684 let plugin = ArgocdPlugin::new();
685 let options = plugin.client_options(&cfg(&[
686 ("server_url", " https://Argo.example.com:8443/ "),
687 ("insecure", "true"),
688 ]));
689 assert_eq!(
690 options.origin.as_ref().map(|u| u.as_str()),
691 Some("https://argo.example.com:8443/")
692 );
693 assert!(options.accept_invalid_certs);
694 }
695
696 #[test]
697 fn client_options_default_secure_for_missing_or_bad_values() {
698 let plugin = ArgocdPlugin::new();
699 for insecure in ["false", "yes", ""] {
700 let options = plugin.client_options(&cfg(&[
701 ("server_url", "https://argo.example.com"),
702 ("insecure", insecure),
703 ]));
704 assert!(!options.accept_invalid_certs);
705 }
706 assert!(
707 !plugin
708 .client_options(&cfg(&[("server_url", "https://a.io")]))
709 .accept_invalid_certs
710 );
711 }
712
713 #[test]
714 fn client_options_origin_none_when_missing_or_invalid() {
715 let plugin = ArgocdPlugin::new();
716 assert_eq!(plugin.client_options(&cfg(&[])).origin, None);
717 assert_eq!(
718 plugin
719 .client_options(&cfg(&[("server_url", "not a url")]))
720 .origin,
721 None
722 );
723 }
724
725 #[test]
726 fn initialize_requires_client_and_validates_status_page() {
727 let base = [("server_url", "https://a.io"), ("token", "t")];
728 let mut plugin = ArgocdPlugin::new();
729
730 assert!(matches!(
731 plugin.initialize(1, cfg(&base), None),
732 Err(PluginError::Internal(_))
733 ));
734
735 let mut bad = base.to_vec();
736 bad.push(("status_page_url", "http://example.com"));
737 assert!(matches!(
738 plugin.initialize(1, cfg(&bad), None),
739 Err(PluginError::InvalidConfig(_))
740 ));
741 assert!(plugin.status_source().is_none());
742 }
743
744 const APP: &str = r#"{"metadata":{"name":"web","namespace":"argocd"},
745 "spec":{"source":{"repoURL":"https://github.com/acme/web","path":"deploy","targetRevision":"main"},
746 "destination":{"server":"https://kubernetes.default.svc","namespace":"web"},"project":"default"},
747 "status":{"sync":{"status":"OutOfSync","revision":"def456"},"health":{"status":"Degraded"},
748 "history":[{"revision":"abc123","deployedAt":"2026-10-26T09:00:30Z","deployStartedAt":"2026-10-26T09:00:00Z","id":3,
749 "source":{"repoURL":"https://ci:s3cret@github.com/acme/web?token=abc","path":"deploy"},"initiatedBy":{"username":"admin"}}],
750 "operationState":{"operation":{"sync":{"revision":"def456","prune":true},"initiatedBy":{"automated":true}},
751 "phase":"Failed","message":"one or more objects failed to apply","startedAt":"2026-10-27T10:00:00Z",
752 "finishedAt":"2026-10-27T10:00:42Z","retryCount":2,
753 "syncResult":{"revision":"def456","resources":[
754 {"group":"batch","version":"v1","kind":"Job","namespace":"web","name":"db-migrate","hookType":"PreSync","hookPhase":"Succeeded","syncPhase":"PreSync","message":"job completed"},
755 {"group":"apps","version":"v1","kind":"Deployment","namespace":"web","name":"web","status":"Synced","syncPhase":"Sync","message":"deployment.apps/web configured"},
756 {"group":"","version":"v1","kind":"ConfigMap","namespace":"web","name":"web-config","status":"SyncFailed","syncPhase":"Sync","message":"ConfigMap \"web-config\" is invalid"}]}}}}"#;
757
758 const TREE: &str = r#"{"nodes":[
759 {"group":"apps","version":"v1","kind":"Deployment","namespace":"web","name":"web","uid":"d1","health":{"status":"Degraded"}},
760 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-def","uid":"p2","health":{"status":"Healthy"}},
761 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-abc","uid":"p1","health":{"status":"Degraded"}}]}"#;
762
763 const APP_EVENTS: &str = r#"{"metadata":{},"items":[
764 {"type":"Warning","reason":"OperationCompleted","message":"Sync operation to def456 failed","count":1,"firstTimestamp":"2026-10-27T10:00:42Z","lastTimestamp":"2026-10-27T10:00:42Z"},
765 {"type":"Normal","reason":"OperationStarted","message":"Initiated automated sync to 'def456'","firstTimestamp":"2026-10-27T10:00:00Z","lastTimestamp":"2026-10-27T10:00:00Z","eventTime":null}]}"#;
766
767 const POD_EVENTS: &str = r#"{"metadata":{},"items":[
768 {"type":"Warning","reason":"BackOff","message":"Back-off restarting failed container app","count":12,"firstTimestamp":"2026-10-27T10:01:00Z","lastTimestamp":"2026-10-27T10:06:00Z"}]}"#;
769
770 const CRASHING_POD: &str = r#"{"metadata":{"name":"web-7f9c-abc","namespace":"web","uid":"p1"},
771 "spec":{"nodeName":"node-1","initContainers":[{"name":"migrate","image":"migrate:1"}],"containers":[{"name":"app","image":"web:2"}]},
772 "status":{"phase":"Running",
773 "initContainerStatuses":[{"name":"migrate","restartCount":0,"state":{"terminated":{"exitCode":0,"reason":"Completed"}}}],
774 "containerStatuses":[{"name":"app","restartCount":3,
775 "state":{"waiting":{"reason":"CrashLoopBackOff","message":"back-off 40s restarting failed container=app"}},
776 "lastState":{"terminated":{"exitCode":1,"reason":"Error","finishedAt":"2026-10-27T10:05:02Z"}}}]}}"#;
777
778 const HEALTHY_POD: &str = r#"{"metadata":{"name":"web-7f9c-def","namespace":"web","uid":"p2"},
779 "spec":{"containers":[{"name":"app"}]},
780 "status":{"phase":"Running","containerStatuses":[{"name":"app","restartCount":0,"state":{"running":{}}}]}}"#;
781
782 const LAST: &str = r#"{"result":{"content":"","timeStampStr":"2026-10-27T10:06:00Z","podName":"","last":true}}"#;
783
784 fn log_stream(lines: &[&str]) -> String {
785 lines
786 .iter()
787 .map(|content| {
788 format!(
789 "{}\n",
790 serde_json::json!({"result": {
791 "content": content,
792 "timeStampStr": "2026-10-27T10:05:01.5Z",
793 "podName": "web-7f9c-abc",
794 "last": false,
795 }})
796 )
797 })
798 .chain([format!("{LAST}\n")])
799 .collect()
800 }
801
802 fn argocd_reply(target: &str) -> (&'static str, String) {
803 let (path, query) = target.split_once('?').unwrap_or((target, ""));
804 let has = |pair: &str| query.split('&').any(|part| part == pair);
805 let ok = |body: &str| ("200 OK", body.to_string());
806 match path {
807 "/api/v1/settings" => ok(r#"{"url":"","dexConfig":{"connectors":[{"name":"GitHub","type":"github","id":"github"}]}}"#),
808 "/api/v1/applications/web" => ok(APP),
809 "/api/v1/applications/web/resource-tree" => ok(TREE),
810 "/api/v1/applications/web/events" if query.is_empty() => ok(APP_EVENTS),
811 "/api/v1/applications/web/events" if has("resourceName=web-7f9c-abc") => {
812 ok(POD_EVENTS)
813 }
814 "/api/v1/applications/web/events" => ok(r#"{"metadata":{},"items":null}"#),
815 "/api/v1/applications/web/resource" if has("kind=Pod") && has("version=v1") => {
816 let pod = if has("resourceName=web-7f9c-abc") {
817 CRASHING_POD
818 } else {
819 HEALTHY_POD
820 };
821 ok(&serde_json::json!({ "manifest": pod }).to_string())
822 }
823 "/api/v1/applications/web/logs" if has("podName=web-7f9c-def") => (
824 "403 Forbidden",
825 r#"{"error":"permission denied: logs, get, default/web","code":7,"message":"permission denied: logs, get, default/web"}"#
826 .to_string(),
827 ),
828 "/api/v1/applications/web/logs" if has("tailLines=1000") && has("follow=false") => {
829 if has("container=migrate") {
830 ok(&log_stream(&["migrations applied"]))
831 } else if has("previous=true") {
832 ok(&log_stream(&["panic: missing DATABASE_URL"]))
833 } else {
834 ok(&format!("{LAST}\n"))
835 }
836 }
837 _ => ("404 Not Found", r#"{"message":"not found"}"#.to_string()),
838 }
839 }
840
841 async fn stub_argocd(requests: Arc<tokio::sync::Mutex<Vec<String>>>) -> String {
842 use tokio::io::{
843 AsyncReadExt,
844 AsyncWriteExt,
845 };
846
847 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
848 let addr = listener.local_addr().unwrap();
849 tokio::spawn(async move {
850 while let Ok((mut stream, _)) = listener.accept().await {
851 let requests = requests.clone();
852 tokio::spawn(async move {
853 let mut head = Vec::new();
854 let mut buffer = [0; 4096];
855 while !head.windows(4).any(|w| w == b"\r\n\r\n") {
856 match stream.read(&mut buffer).await {
857 Ok(0) | Err(_) => return,
858 Ok(n) => head.extend_from_slice(&buffer[..n]),
859 }
860 }
861 let head = String::from_utf8_lossy(&head);
862 let target = head.split_whitespace().nth(1).unwrap_or("/").to_string();
863 let (status, body) = argocd_reply(&target);
864 requests.lock().await.push(target);
865 let response = format!(
866 "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
867 body.len()
868 );
869 let _ = stream.write_all(response.as_bytes()).await;
870 });
871 }
872 });
873 format!("http://{addr}")
874 }
875
876 async fn stub_plugin() -> (ArgocdPlugin, Arc<tokio::sync::Mutex<Vec<String>>>) {
877 let _ = rustls::crypto::ring::default_provider().install_default();
878 let requests = Arc::new(tokio::sync::Mutex::new(Vec::new()));
879 let server_url = stub_argocd(requests.clone()).await;
880 let mut plugin = ArgocdPlugin::new();
881 plugin
882 .initialize(
883 1,
884 cfg(&[("server_url", &server_url), ("token", "t")]),
885 Some(Arc::new(reqwest::Client::new())),
886 )
887 .unwrap();
888 (plugin, requests)
889 }
890
891 #[tokio::test]
892 async fn sign_in_client_reads_unauthenticated_settings() {
893 let _ = rustls::crypto::ring::default_provider().install_default();
894 let requests = Arc::new(tokio::sync::Mutex::new(Vec::new()));
895 let server_url = stub_argocd(requests.clone()).await;
896
897 let client = ArgocdPlugin::new()
898 .sign_in_client(
899 &cfg(&[("server_url", &server_url)]),
900 &reqwest::Client::new(),
901 )
902 .await
903 .unwrap();
904
905 assert_eq!(client.issuer, format!("{server_url}/api/dex"));
906 assert_eq!(client.label, "GitHub");
907 assert_eq!(*requests.lock().await, ["/api/v1/settings"]);
908 }
909
910 const PIPELINE_ID: &str = "argocd__1__argocd__web";
911
912 fn run_at(stamp: &str) -> i64 {
913 chrono::DateTime::parse_from_rfc3339(stamp)
914 .unwrap()
915 .timestamp()
916 }
917
918 async fn read(
919 plugin: &ArgocdPlugin, run_number: i64, node_id: &str,
920 ) -> PluginResult<Vec<(LineMarker, String)>> {
921 let metadata = HashMap::new();
922 let run = RunRef {
923 pipeline_id: PIPELINE_ID,
924 run_number,
925 run_id: "argocd-sync-web-current",
926 metadata: &metadata,
927 };
928 let (tx, mut rx) = tokio::sync::mpsc::channel(64);
929 let mut sink = LogSink::new(tx);
930 let result = plugin.read_log(run, node_id, &mut sink).await;
931 drop(sink);
932 let mut bytes = Vec::new();
933 while let Some(chunk) = rx.recv().await {
934 bytes.extend_from_slice(&chunk);
935 }
936 result?;
937 Ok(bytes
938 .split(|b| *b == b'\n')
939 .filter(|line| !line.is_empty())
940 .map(|line| {
941 let parsed = ArgocdLogDialect.parse(line);
942 (
943 parsed.marker,
944 String::from_utf8_lossy(parsed.body).into_owned(),
945 )
946 })
947 .collect())
948 }
949
950 fn line(marker: LineMarker, text: &str) -> (LineMarker, String) {
951 (marker, text.to_string())
952 }
953
954 const OPEN: LineMarker = LineMarker::SectionStart { open: true };
955 const CLOSED: LineMarker = LineMarker::SectionStart { open: false };
956
957 #[tokio::test]
958 async fn log_nodes_list_sync_result_events_and_pods() {
959 let (plugin, _) = stub_plugin().await;
960 let metadata = HashMap::new();
961 let run = RunRef {
962 pipeline_id: PIPELINE_ID,
963 run_number: run_at("2026-10-27T10:00:00Z"),
964 run_id: "argocd-sync-web-current",
965 metadata: &metadata,
966 };
967
968 let nodes = plugin.fetch_log_nodes(run).await.unwrap();
969
970 let summary: Vec<_> = nodes
971 .iter()
972 .map(|node| {
973 (
974 node.id.as_str(),
975 node.parent_id.as_deref(),
976 node.status,
977 node.log,
978 )
979 })
980 .collect();
981 assert_eq!(
982 summary,
983 [
984 (
985 "sync",
986 None,
987 PipelineStatus::Failed,
988 Some(LogAvailability::Ready)
989 ),
990 (
991 "events",
992 None,
993 PipelineStatus::Success,
994 Some(LogAvailability::Partial)
995 ),
996 ("pods", None, PipelineStatus::Failed, None),
997 (
998 "pod:web:web-7f9c-abc",
999 Some("pods"),
1000 PipelineStatus::Failed,
1001 Some(LogAvailability::Partial)
1002 ),
1003 (
1004 "pod:web:web-7f9c-def",
1005 Some("pods"),
1006 PipelineStatus::Success,
1007 Some(LogAvailability::Partial)
1008 ),
1009 ]
1010 );
1011 assert_eq!(nodes[0].name, "Sync result");
1012 assert_eq!(nodes[3].name, "web-7f9c-abc");
1013 }
1014
1015 #[tokio::test]
1016 async fn failed_sync_lists_resource_results_by_phase() {
1017 let (plugin, _) = stub_plugin().await;
1018
1019 let lines = read(&plugin, run_at("2026-10-27T10:00:00Z"), "sync")
1020 .await
1021 .unwrap();
1022
1023 assert_eq!(
1024 lines,
1025 [
1026 line(OPEN, "Sync operation"),
1027 line(LineMarker::Plain, "Started by the automated sync policy"),
1028 line(LineMarker::Plain, "Revision def456"),
1029 line(LineMarker::Plain, "Options: prune"),
1030 line(LineMarker::Plain, "Retried 2 times"),
1031 line(LineMarker::Error, "one or more objects failed to apply"),
1032 line(LineMarker::Plain, "Failed after 42s"),
1033 line(CLOSED, "PreSync phase, 1 resource"),
1034 line(
1035 LineMarker::Plain,
1036 "Succeeded batch/Job web/db-migrate (PreSync hook): job completed"
1037 ),
1038 line(OPEN, "Sync phase, 2 resources"),
1039 line(
1040 LineMarker::Plain,
1041 "Synced apps/Deployment web/web: deployment.apps/web configured"
1042 ),
1043 line(
1044 LineMarker::Error,
1045 "SyncFailed ConfigMap web/web-config: ConfigMap \"web-config\" is invalid"
1046 ),
1047 ]
1048 );
1049 }
1050
1051 #[tokio::test]
1052 async fn older_sync_shows_its_history_record() {
1053 let (plugin, _) = stub_plugin().await;
1054
1055 let lines = read(&plugin, run_at("2026-10-26T09:00:30Z"), "sync")
1056 .await
1057 .unwrap();
1058
1059 assert_eq!(
1060 lines,
1061 [
1062 line(OPEN, "Sync"),
1063 line(LineMarker::Plain, "Started by admin"),
1064 line(LineMarker::Plain, "Revision abc123"),
1065 line(
1066 LineMarker::Plain,
1067 "Source https://github.com/acme/web deploy"
1068 ),
1069 line(LineMarker::Plain, "Deployed after 30s"),
1070 line(
1071 LineMarker::Plain,
1072 "Argo CD keeps per-resource results only for the most recent operation of an app."
1073 ),
1074 ]
1075 );
1076 }
1077
1078 #[tokio::test]
1079 async fn application_events_come_in_time_order() {
1080 let (plugin, _) = stub_plugin().await;
1081
1082 let lines = read(&plugin, run_at("2026-10-27T10:00:00Z"), "events")
1083 .await
1084 .unwrap();
1085
1086 assert_eq!(
1087 lines,
1088 [
1089 line(
1090 LineMarker::Plain,
1091 "Normal OperationStarted: Initiated automated sync to 'def456'"
1092 ),
1093 line(
1094 LineMarker::Warning,
1095 "Warning OperationCompleted: Sync operation to def456 failed"
1096 ),
1097 ]
1098 );
1099 }
1100
1101 #[tokio::test]
1102 async fn crashing_pod_shows_status_events_and_every_container_attempt() {
1103 let (plugin, requests) = stub_plugin().await;
1104
1105 let lines = read(
1106 &plugin,
1107 run_at("2026-10-27T10:00:00Z"),
1108 "pod:web:web-7f9c-abc",
1109 )
1110 .await
1111 .unwrap();
1112
1113 assert_eq!(
1114 lines,
1115 [
1116 line(OPEN, "Pod web/web-7f9c-abc"),
1117 line(LineMarker::Plain, "Phase Running on node node-1"),
1118 line(
1119 LineMarker::Plain,
1120 "Init container migrate: exited with code 0 (Completed)"
1121 ),
1122 line(
1123 LineMarker::Error,
1124 "Container app: waiting (CrashLoopBackOff), 3 restarts, last exit code 1 (Error): back-off 40s restarting failed container=app"
1125 ),
1126 line(OPEN, "Events"),
1127 line(
1128 LineMarker::Warning,
1129 "Warning BackOff: Back-off restarting failed container app (x12)"
1130 ),
1131 line(CLOSED, "Init container migrate"),
1132 line(LineMarker::Plain, "migrations applied"),
1133 line(OPEN, "Container app, previous attempt"),
1134 line(LineMarker::Plain, "panic: missing DATABASE_URL"),
1135 line(OPEN, "Container app"),
1136 line(LineMarker::Plain, "No log output."),
1137 ]
1138 );
1139 let requests = requests.lock().await;
1140 assert!(
1141 requests
1142 .iter()
1143 .any(|r| r.contains("resourceUID=p1") && r.contains("resourceNamespace=web")),
1144 "{requests:?}"
1145 );
1146 }
1147
1148 #[tokio::test]
1149 async fn pod_log_without_the_logs_permission_is_permission_denied() {
1150 let (plugin, _) = stub_plugin().await;
1151
1152 let error = read(
1153 &plugin,
1154 run_at("2026-10-27T10:00:00Z"),
1155 "pod:web:web-7f9c-def",
1156 )
1157 .await
1158 .unwrap_err();
1159
1160 assert!(
1161 matches!(&error, PluginError::PermissionDenied(message) if message.contains("logs, get")),
1162 "{error:?}"
1163 );
1164 }
1165
1166 #[tokio::test]
1167 async fn unknown_node_ids_are_rejected_without_a_request() {
1168 let (plugin, requests) = stub_plugin().await;
1169
1170 for node_id in [
1171 "",
1172 "pods",
1173 "pod:web",
1174 "pod:web:a?b=1",
1175 "pod:..:x",
1176 "pod/web/a",
1177 ] {
1178 let error = read(&plugin, run_at("2026-10-27T10:00:00Z"), node_id)
1179 .await
1180 .unwrap_err();
1181 assert!(
1182 matches!(error, PluginError::InvalidConfig(_)),
1183 "{node_id}: {error:?}"
1184 );
1185 }
1186 assert!(requests.lock().await.is_empty());
1187 }
1188}