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
672#[cfg(test)]
673mod tests {
674 use std::sync::Arc;
675
676 use super::*;
677
678 fn cfg(pairs: &[(&str, &str)]) -> HashMap<String, String> {
679 pairs
680 .iter()
681 .map(|(k, v)| (k.to_string(), v.to_string()))
682 .collect()
683 }
684
685 #[test]
686 fn client_options_parse_origin_and_insecure() {
687 let plugin = ArgocdPlugin::new();
688 let options = plugin.client_options(&cfg(&[
689 ("server_url", " https://Argo.example.com:8443/ "),
690 ("insecure", "true"),
691 ]));
692 assert_eq!(
693 options.origin.as_ref().map(|u| u.as_str()),
694 Some("https://argo.example.com:8443/")
695 );
696 assert!(options.accept_invalid_certs);
697 }
698
699 #[test]
700 fn client_options_default_secure_for_missing_or_bad_values() {
701 let plugin = ArgocdPlugin::new();
702 for insecure in ["false", "yes", ""] {
703 let options = plugin.client_options(&cfg(&[
704 ("server_url", "https://argo.example.com"),
705 ("insecure", insecure),
706 ]));
707 assert!(!options.accept_invalid_certs);
708 }
709 assert!(
710 !plugin
711 .client_options(&cfg(&[("server_url", "https://a.io")]))
712 .accept_invalid_certs
713 );
714 }
715
716 #[test]
717 fn client_options_origin_none_when_missing_or_invalid() {
718 let plugin = ArgocdPlugin::new();
719 assert_eq!(plugin.client_options(&cfg(&[])).origin, None);
720 assert_eq!(
721 plugin
722 .client_options(&cfg(&[("server_url", "not a url")]))
723 .origin,
724 None
725 );
726 }
727
728 #[test]
729 fn initialize_requires_client_and_validates_status_page() {
730 let base = [("server_url", "https://a.io"), ("token", "t")];
731 let mut plugin = ArgocdPlugin::new();
732
733 assert!(matches!(
734 plugin.initialize(1, cfg(&base), None),
735 Err(PluginError::Internal(_))
736 ));
737
738 let mut bad = base.to_vec();
739 bad.push(("status_page_url", "http://example.com"));
740 assert!(matches!(
741 plugin.initialize(1, cfg(&bad), None),
742 Err(PluginError::InvalidConfig(_))
743 ));
744 assert!(plugin.status_source().is_none());
745 }
746
747 const APP: &str = r#"{"metadata":{"name":"web","namespace":"argocd"},
748 "spec":{"source":{"repoURL":"https://github.com/acme/web","path":"deploy","targetRevision":"main"},
749 "destination":{"server":"https://kubernetes.default.svc","namespace":"web"},"project":"default"},
750 "status":{"sync":{"status":"OutOfSync","revision":"def456"},"health":{"status":"Degraded"},
751 "history":[{"revision":"abc123","deployedAt":"2026-10-26T09:00:30Z","deployStartedAt":"2026-10-26T09:00:00Z","id":3,
752 "source":{"repoURL":"https://ci:s3cret@github.com/acme/web?token=abc","path":"deploy"},"initiatedBy":{"username":"admin"}}],
753 "operationState":{"operation":{"sync":{"revision":"def456","prune":true},"initiatedBy":{"automated":true}},
754 "phase":"Failed","message":"one or more objects failed to apply","startedAt":"2026-10-27T10:00:00Z",
755 "finishedAt":"2026-10-27T10:00:42Z","retryCount":2,
756 "syncResult":{"revision":"def456","resources":[
757 {"group":"batch","version":"v1","kind":"Job","namespace":"web","name":"db-migrate","hookType":"PreSync","hookPhase":"Succeeded","syncPhase":"PreSync","message":"job completed"},
758 {"group":"apps","version":"v1","kind":"Deployment","namespace":"web","name":"web","status":"Synced","syncPhase":"Sync","message":"deployment.apps/web configured"},
759 {"group":"","version":"v1","kind":"ConfigMap","namespace":"web","name":"web-config","status":"SyncFailed","syncPhase":"Sync","message":"ConfigMap \"web-config\" is invalid"}]}}}}"#;
760
761 const TREE: &str = r#"{"nodes":[
762 {"group":"apps","version":"v1","kind":"Deployment","namespace":"web","name":"web","uid":"d1","health":{"status":"Degraded"}},
763 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-def","uid":"p2","health":{"status":"Healthy"}},
764 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-abc","uid":"p1","health":{"status":"Degraded"}}]}"#;
765
766 const CRASH_TREE: &str = r#"{"nodes":[
767 {"group":"apps","version":"v1","kind":"Deployment","namespace":"web","name":"crash","uid":"d1","health":{"status":"Progressing"}},
768 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-def","uid":"p2","health":{"status":"Healthy"}},
769 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-abc","uid":"p1","health":{"status":"Degraded","message":"back-off 40s restarting failed container=app"}},
770 {"version":"v1","kind":"Pod","namespace":"web","name":"web-7f9c-ghi","uid":"p3","health":{"status":"Degraded","message":"Back-off pulling image"}}]}"#;
771
772 const ROLLOUT_TREE: &str = r#"{"nodes":[
773 {"group":"apps","version":"v1","kind":"Deployment","namespace":"web","name":"rollout","uid":"d1","health":{"status":"Progressing"}},
774 {"version":"v1","kind":"Pod","namespace":"web","name":"rollout-1","uid":"p1","health":{"status":"Progressing"}}]}"#;
775
776 fn listed_app(name: &str, health: &str) -> serde_json::Value {
777 serde_json::json!({
778 "metadata": {"name": name, "namespace": "argocd"},
779 "spec": {"source": {"repoURL": "https://github.com/acme/web"}, "destination": {"namespace": "web"}, "project": "default"},
780 "status": {"sync": {"status": "Synced"}, "health": {"status": health, "message": format!("{name} is {health}")}},
781 })
782 }
783
784 const APP_EVENTS: &str = r#"{"metadata":{},"items":[
785 {"type":"Warning","reason":"OperationCompleted","message":"Sync operation to def456 failed","count":1,"firstTimestamp":"2026-10-27T10:00:42Z","lastTimestamp":"2026-10-27T10:00:42Z"},
786 {"type":"Normal","reason":"OperationStarted","message":"Initiated automated sync to 'def456'","firstTimestamp":"2026-10-27T10:00:00Z","lastTimestamp":"2026-10-27T10:00:00Z","eventTime":null}]}"#;
787
788 const POD_EVENTS: &str = r#"{"metadata":{},"items":[
789 {"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"}]}"#;
790
791 const CRASHING_POD: &str = r#"{"metadata":{"name":"web-7f9c-abc","namespace":"web","uid":"p1"},
792 "spec":{"nodeName":"node-1","initContainers":[{"name":"migrate","image":"migrate:1"}],"containers":[{"name":"app","image":"web:2"}]},
793 "status":{"phase":"Running",
794 "initContainerStatuses":[{"name":"migrate","restartCount":0,"state":{"terminated":{"exitCode":0,"reason":"Completed"}}}],
795 "containerStatuses":[{"name":"app","restartCount":3,
796 "state":{"waiting":{"reason":"CrashLoopBackOff","message":"back-off 40s restarting failed container=app"}},
797 "lastState":{"terminated":{"exitCode":1,"reason":"Error","finishedAt":"2026-10-27T10:05:02Z"}}}]}}"#;
798
799 const HEALTHY_POD: &str = r#"{"metadata":{"name":"web-7f9c-def","namespace":"web","uid":"p2"},
800 "spec":{"containers":[{"name":"app"}]},
801 "status":{"phase":"Running","containerStatuses":[{"name":"app","restartCount":0,"state":{"running":{}}}]}}"#;
802
803 const LAST: &str = r#"{"result":{"content":"","timeStampStr":"2026-10-27T10:06:00Z","podName":"","last":true}}"#;
804
805 fn log_stream(lines: &[&str]) -> String {
806 lines
807 .iter()
808 .map(|content| {
809 format!(
810 "{}\n",
811 serde_json::json!({"result": {
812 "content": content,
813 "timeStampStr": "2026-10-27T10:05:01.5Z",
814 "podName": "web-7f9c-abc",
815 "last": false,
816 }})
817 )
818 })
819 .chain([format!("{LAST}\n")])
820 .collect()
821 }
822
823 fn argocd_reply(target: &str) -> (&'static str, String) {
824 let (path, query) = target.split_once('?').unwrap_or((target, ""));
825 let has = |pair: &str| query.split('&').any(|part| part == pair);
826 let ok = |body: &str| ("200 OK", body.to_string());
827 match path {
828 "/api/v1/settings" => ok(r#"{"url":"","dexConfig":{"connectors":[{"name":"GitHub","type":"github","id":"github"}]}}"#),
829 "/api/v1/applications/web" => ok(APP),
830 "/api/v1/applications/web/resource-tree" => ok(TREE),
831 "/api/v1/applications" => ok(&serde_json::json!({"items": [
832 listed_app("crash", "Progressing"),
833 listed_app("rollout", "Progressing"),
834 listed_app("ready", "Healthy"),
835 listed_app("forbidden", "Progressing"),
836 listed_app("broken", "Degraded"),
837 ]})
838 .to_string()),
839 "/api/v1/applications/crash/resource-tree" => ok(CRASH_TREE),
840 "/api/v1/applications/rollout/resource-tree" => ok(ROLLOUT_TREE),
841 "/api/v1/applications/forbidden/resource-tree" => (
842 "403 Forbidden",
843 r#"{"error":"permission denied: applications, get, default/forbidden","code":7,"message":"permission denied: applications, get, default/forbidden"}"#
844 .to_string(),
845 ),
846 "/api/v1/applications/broken/resource-tree" => (
847 "500 Internal Server Error",
848 r#"{"message":"boom"}"#.to_string(),
849 ),
850 "/api/v1/applications/web/events" if query.is_empty() => ok(APP_EVENTS),
851 "/api/v1/applications/web/events" if has("resourceName=web-7f9c-abc") => {
852 ok(POD_EVENTS)
853 }
854 "/api/v1/applications/web/events" => ok(r#"{"metadata":{},"items":null}"#),
855 "/api/v1/applications/web/resource" if has("kind=Pod") && has("version=v1") => {
856 let pod = if has("resourceName=web-7f9c-abc") {
857 CRASHING_POD
858 } else {
859 HEALTHY_POD
860 };
861 ok(&serde_json::json!({ "manifest": pod }).to_string())
862 }
863 "/api/v1/applications/web/logs" if has("podName=web-7f9c-def") => (
864 "403 Forbidden",
865 r#"{"error":"permission denied: logs, get, default/web","code":7,"message":"permission denied: logs, get, default/web"}"#
866 .to_string(),
867 ),
868 "/api/v1/applications/web/logs" if has("tailLines=1000") && has("follow=false") => {
869 if has("container=migrate") {
870 ok(&log_stream(&["migrations applied"]))
871 } else if has("previous=true") {
872 ok(&log_stream(&["panic: missing DATABASE_URL"]))
873 } else {
874 ok(&format!("{LAST}\n"))
875 }
876 }
877 _ => ("404 Not Found", r#"{"message":"not found"}"#.to_string()),
878 }
879 }
880
881 async fn stub_argocd(requests: Arc<tokio::sync::Mutex<Vec<String>>>) -> String {
882 use tokio::io::{
883 AsyncReadExt,
884 AsyncWriteExt,
885 };
886
887 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
888 let addr = listener.local_addr().unwrap();
889 tokio::spawn(async move {
890 while let Ok((mut stream, _)) = listener.accept().await {
891 let requests = requests.clone();
892 tokio::spawn(async move {
893 let mut head = Vec::new();
894 let mut buffer = [0; 4096];
895 while !head.windows(4).any(|w| w == b"\r\n\r\n") {
896 match stream.read(&mut buffer).await {
897 Ok(0) | Err(_) => return,
898 Ok(n) => head.extend_from_slice(&buffer[..n]),
899 }
900 }
901 let head = String::from_utf8_lossy(&head);
902 let target = head.split_whitespace().nth(1).unwrap_or("/").to_string();
903 let (status, body) = argocd_reply(&target);
904 requests.lock().await.push(target);
905 let response = format!(
906 "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
907 body.len()
908 );
909 let _ = stream.write_all(response.as_bytes()).await;
910 });
911 }
912 });
913 format!("http://{addr}")
914 }
915
916 async fn stub_plugin() -> (ArgocdPlugin, Arc<tokio::sync::Mutex<Vec<String>>>) {
917 let _ = rustls::crypto::ring::default_provider().install_default();
918 let requests = Arc::new(tokio::sync::Mutex::new(Vec::new()));
919 let server_url = stub_argocd(requests.clone()).await;
920 let mut plugin = ArgocdPlugin::new();
921 plugin
922 .initialize(
923 1,
924 cfg(&[("server_url", &server_url), ("token", "t")]),
925 Some(Arc::new(reqwest::Client::new())),
926 )
927 .unwrap();
928 (plugin, requests)
929 }
930
931 #[tokio::test]
932 async fn sign_in_client_reads_unauthenticated_settings() {
933 let _ = rustls::crypto::ring::default_provider().install_default();
934 let requests = Arc::new(tokio::sync::Mutex::new(Vec::new()));
935 let server_url = stub_argocd(requests.clone()).await;
936
937 let client = ArgocdPlugin::new()
938 .sign_in_client(
939 &cfg(&[("server_url", &server_url)]),
940 &reqwest::Client::new(),
941 )
942 .await
943 .unwrap();
944
945 assert_eq!(client.issuer, format!("{server_url}/api/dex"));
946 assert_eq!(client.label, "GitHub");
947 assert_eq!(*requests.lock().await, ["/api/v1/settings"]);
948 }
949
950 async fn fetch_states() -> (HashMap<String, Pipeline>, Vec<String>) {
951 let (plugin, requests) = stub_plugin().await;
952 let pipelines = plugin.fetch_pipelines().await.unwrap();
953 let requests = requests.lock().await.clone();
954 (
955 pipelines
956 .into_iter()
957 .map(|pipeline| (pipeline.name.clone(), pipeline))
958 .collect(),
959 requests,
960 )
961 }
962
963 fn state_of(pipeline: &Pipeline) -> (PipelineStatus, &str, Option<&str>) {
964 let state = pipeline.resource_state.as_ref().unwrap();
965 (
966 pipeline.status,
967 state.label.as_str(),
968 state.message.as_deref(),
969 )
970 }
971
972 #[tokio::test]
973 async fn progressing_app_with_crash_looping_pod_is_degraded() {
974 let (pipelines, _) = fetch_states().await;
975
976 assert_eq!(
977 state_of(&pipelines["crash"]),
978 (
979 PipelineStatus::Degraded,
980 "Degraded",
981 Some(
982 "Pod web/web-7f9c-abc: back-off 40s restarting failed container=app (+1 more)"
983 )
984 )
985 );
986 }
987
988 #[tokio::test]
989 async fn progressing_app_with_healthy_tree_stays_progressing() {
990 let (pipelines, _) = fetch_states().await;
991
992 assert_eq!(
993 state_of(&pipelines["rollout"]),
994 (
995 PipelineStatus::Running,
996 "Progressing",
997 Some("rollout is Progressing")
998 )
999 );
1000 }
1001
1002 #[tokio::test]
1003 async fn healthy_app_costs_no_resource_tree_request() {
1004 let (pipelines, requests) = fetch_states().await;
1005
1006 assert_eq!(
1007 state_of(&pipelines["ready"]),
1008 (PipelineStatus::Success, "Synced", Some("ready is Healthy"))
1009 );
1010 assert!(requests.iter().all(|target| !target.contains("/ready")));
1011 for unhealthy in ["crash", "rollout", "forbidden", "broken"] {
1012 let tree = format!("/api/v1/applications/{unhealthy}/resource-tree");
1013 assert!(requests.contains(&tree), "{unhealthy}");
1014 }
1015 }
1016
1017 #[tokio::test]
1018 async fn failing_resource_tree_keeps_the_provider_state() {
1019 let (pipelines, requests) = fetch_states().await;
1020
1021 assert_eq!(
1022 state_of(&pipelines["forbidden"]),
1023 (
1024 PipelineStatus::Running,
1025 "Progressing",
1026 Some("forbidden is Progressing")
1027 )
1028 );
1029 assert_eq!(
1030 state_of(&pipelines["broken"]),
1031 (
1032 PipelineStatus::Degraded,
1033 "Degraded",
1034 Some("broken is Degraded")
1035 )
1036 );
1037 let forbidden = "/api/v1/applications/forbidden/resource-tree";
1038 assert_eq!(requests.iter().filter(|t| *t == forbidden).count(), 1);
1039 }
1040
1041 const PIPELINE_ID: &str = "argocd__1__argocd__web";
1042
1043 fn run_at(stamp: &str) -> i64 {
1044 chrono::DateTime::parse_from_rfc3339(stamp)
1045 .unwrap()
1046 .timestamp()
1047 }
1048
1049 async fn read(
1050 plugin: &ArgocdPlugin, run_number: i64, node_id: &str,
1051 ) -> PluginResult<Vec<(LineMarker, String)>> {
1052 let metadata = HashMap::new();
1053 let run = RunRef {
1054 pipeline_id: PIPELINE_ID,
1055 run_number,
1056 run_id: "argocd-sync-web-current",
1057 metadata: &metadata,
1058 };
1059 let (tx, mut rx) = tokio::sync::mpsc::channel(64);
1060 let mut sink = LogSink::new(tx);
1061 let result = plugin.read_log(run, node_id, None, &mut sink).await;
1062 assert!(!sink.restarted());
1063 drop(sink);
1064 let mut bytes = Vec::new();
1065 while let Some(chunk) = rx.recv().await {
1066 bytes.extend_from_slice(&chunk);
1067 }
1068 assert_eq!(result?, LogRead::replace(None));
1069 Ok(bytes
1070 .split(|b| *b == b'\n')
1071 .filter(|line| !line.is_empty())
1072 .map(|line| {
1073 let parsed = ArgocdLogDialect.parse(line);
1074 (
1075 parsed.marker,
1076 String::from_utf8_lossy(parsed.body).into_owned(),
1077 )
1078 })
1079 .collect())
1080 }
1081
1082 fn line(marker: LineMarker, text: &str) -> (LineMarker, String) {
1083 (marker, text.to_string())
1084 }
1085
1086 const OPEN: LineMarker = LineMarker::SectionStart { open: true };
1087 const CLOSED: LineMarker = LineMarker::SectionStart { open: false };
1088
1089 #[tokio::test]
1090 async fn log_nodes_list_sync_result_events_and_pods() {
1091 let (plugin, _) = stub_plugin().await;
1092 let metadata = HashMap::new();
1093 let run = RunRef {
1094 pipeline_id: PIPELINE_ID,
1095 run_number: run_at("2026-10-27T10:00:00Z"),
1096 run_id: "argocd-sync-web-current",
1097 metadata: &metadata,
1098 };
1099
1100 let nodes = plugin.fetch_log_nodes(run).await.unwrap();
1101
1102 let summary: Vec<_> = nodes
1103 .iter()
1104 .map(|node| {
1105 (
1106 node.id.as_str(),
1107 node.parent_id.as_deref(),
1108 node.status,
1109 node.log,
1110 )
1111 })
1112 .collect();
1113 assert_eq!(
1114 summary,
1115 [
1116 (
1117 "sync",
1118 None,
1119 PipelineStatus::Failed,
1120 Some(LogAvailability::Ready)
1121 ),
1122 (
1123 "events",
1124 None,
1125 PipelineStatus::Success,
1126 Some(LogAvailability::Partial)
1127 ),
1128 ("pods", None, PipelineStatus::Failed, None),
1129 (
1130 "pod:web:web-7f9c-abc",
1131 Some("pods"),
1132 PipelineStatus::Failed,
1133 Some(LogAvailability::Partial)
1134 ),
1135 (
1136 "pod:web:web-7f9c-def",
1137 Some("pods"),
1138 PipelineStatus::Success,
1139 Some(LogAvailability::Partial)
1140 ),
1141 ]
1142 );
1143 assert_eq!(nodes[0].name, "Sync result");
1144 assert_eq!(nodes[3].name, "web-7f9c-abc");
1145 }
1146
1147 #[tokio::test]
1148 async fn failed_sync_lists_resource_results_by_phase() {
1149 let (plugin, _) = stub_plugin().await;
1150
1151 let lines = read(&plugin, run_at("2026-10-27T10:00:00Z"), "sync")
1152 .await
1153 .unwrap();
1154
1155 assert_eq!(
1156 lines,
1157 [
1158 line(OPEN, "Sync operation"),
1159 line(LineMarker::Plain, "Started by the automated sync policy"),
1160 line(LineMarker::Plain, "Revision def456"),
1161 line(LineMarker::Plain, "Options: prune"),
1162 line(LineMarker::Plain, "Retried 2 times"),
1163 line(LineMarker::Error, "one or more objects failed to apply"),
1164 line(LineMarker::Plain, "Failed after 42s"),
1165 line(CLOSED, "PreSync phase, 1 resource"),
1166 line(
1167 LineMarker::Plain,
1168 "Succeeded batch/Job web/db-migrate (PreSync hook): job completed"
1169 ),
1170 line(OPEN, "Sync phase, 2 resources"),
1171 line(
1172 LineMarker::Plain,
1173 "Synced apps/Deployment web/web: deployment.apps/web configured"
1174 ),
1175 line(
1176 LineMarker::Error,
1177 "SyncFailed ConfigMap web/web-config: ConfigMap \"web-config\" is invalid"
1178 ),
1179 ]
1180 );
1181 }
1182
1183 #[tokio::test]
1184 async fn older_sync_shows_its_history_record() {
1185 let (plugin, _) = stub_plugin().await;
1186
1187 let lines = read(&plugin, run_at("2026-10-26T09:00:30Z"), "sync")
1188 .await
1189 .unwrap();
1190
1191 assert_eq!(
1192 lines,
1193 [
1194 line(OPEN, "Sync"),
1195 line(LineMarker::Plain, "Started by admin"),
1196 line(LineMarker::Plain, "Revision abc123"),
1197 line(
1198 LineMarker::Plain,
1199 "Source https://github.com/acme/web deploy"
1200 ),
1201 line(LineMarker::Plain, "Deployed after 30s"),
1202 line(
1203 LineMarker::Plain,
1204 "Argo CD keeps per-resource results only for the most recent operation of an app."
1205 ),
1206 ]
1207 );
1208 }
1209
1210 #[tokio::test]
1211 async fn application_events_come_in_time_order() {
1212 let (plugin, _) = stub_plugin().await;
1213
1214 let lines = read(&plugin, run_at("2026-10-27T10:00:00Z"), "events")
1215 .await
1216 .unwrap();
1217
1218 assert_eq!(
1219 lines,
1220 [
1221 line(
1222 LineMarker::Plain,
1223 "Normal OperationStarted: Initiated automated sync to 'def456'"
1224 ),
1225 line(
1226 LineMarker::Warning,
1227 "Warning OperationCompleted: Sync operation to def456 failed"
1228 ),
1229 ]
1230 );
1231 }
1232
1233 #[tokio::test]
1234 async fn crashing_pod_shows_status_events_and_every_container_attempt() {
1235 let (plugin, requests) = stub_plugin().await;
1236
1237 let lines = read(
1238 &plugin,
1239 run_at("2026-10-27T10:00:00Z"),
1240 "pod:web:web-7f9c-abc",
1241 )
1242 .await
1243 .unwrap();
1244
1245 assert_eq!(
1246 lines,
1247 [
1248 line(OPEN, "Pod web/web-7f9c-abc"),
1249 line(LineMarker::Plain, "Phase Running on node node-1"),
1250 line(
1251 LineMarker::Plain,
1252 "Init container migrate: exited with code 0 (Completed)"
1253 ),
1254 line(
1255 LineMarker::Error,
1256 "Container app: waiting (CrashLoopBackOff), 3 restarts, last exit code 1 (Error): back-off 40s restarting failed container=app"
1257 ),
1258 line(OPEN, "Events"),
1259 line(
1260 LineMarker::Warning,
1261 "Warning BackOff: Back-off restarting failed container app (x12)"
1262 ),
1263 line(CLOSED, "Init container migrate"),
1264 line(LineMarker::Plain, "migrations applied"),
1265 line(OPEN, "Container app, previous attempt"),
1266 line(LineMarker::Plain, "panic: missing DATABASE_URL"),
1267 line(OPEN, "Container app"),
1268 line(LineMarker::Plain, "No log output."),
1269 ]
1270 );
1271 let requests = requests.lock().await;
1272 assert!(
1273 requests
1274 .iter()
1275 .any(|r| r.contains("resourceUID=p1") && r.contains("resourceNamespace=web")),
1276 "{requests:?}"
1277 );
1278 }
1279
1280 #[tokio::test]
1281 async fn pod_log_without_the_logs_permission_is_permission_denied() {
1282 let (plugin, _) = stub_plugin().await;
1283
1284 let error = read(
1285 &plugin,
1286 run_at("2026-10-27T10:00:00Z"),
1287 "pod:web:web-7f9c-def",
1288 )
1289 .await
1290 .unwrap_err();
1291
1292 assert!(
1293 matches!(&error, PluginError::PermissionDenied(message) if message.contains("logs, get")),
1294 "{error:?}"
1295 );
1296 }
1297
1298 #[tokio::test]
1299 async fn unknown_node_ids_are_rejected_without_a_request() {
1300 let (plugin, requests) = stub_plugin().await;
1301
1302 for node_id in [
1303 "",
1304 "pods",
1305 "pod:web",
1306 "pod:web:a?b=1",
1307 "pod:..:x",
1308 "pod/web/a",
1309 ] {
1310 let error = read(&plugin, run_at("2026-10-27T10:00:00Z"), node_id)
1311 .await
1312 .unwrap_err();
1313 assert!(
1314 matches!(error, PluginError::InvalidConfig(_)),
1315 "{node_id}: {error:?}"
1316 );
1317 }
1318 assert!(requests.lock().await.is_empty());
1319 }
1320}