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