Skip to main content

pipedash_plugin_argocd/
plugin.rs

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