Skip to main content

purple_ssh/providers/
oracle.rs

1use std::collections::HashMap;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::SystemTime;
4
5use base64::Engine;
6use base64::engine::general_purpose::STANDARD;
7use rsa::pkcs1::DecodeRsaPrivateKey;
8use rsa::pkcs8::DecodePrivateKey;
9use rsa::signature::{SignatureEncoding, Signer};
10use serde::Deserialize;
11
12use super::{Provider, ProviderError, ProviderHost};
13
14/// Oracle Cloud Infrastructure provider configuration.
15pub struct Oracle {
16    pub regions: Vec<String>,
17    pub compartment: String,
18}
19
20/// Parsed OCI API credentials.
21#[derive(Debug)]
22struct OciCredentials {
23    tenancy: String,
24    user: String,
25    fingerprint: String,
26    key_pem: String,
27    region: String,
28}
29
30/// Parse an OCI config file and return credentials.
31///
32/// Only the `[DEFAULT]` profile is read (case-sensitive). The `key_pem`
33/// field comes from the already-read key file content passed as
34/// `key_content`.
35fn parse_oci_config(content: &str, key_content: &str) -> Result<OciCredentials, ProviderError> {
36    let mut in_default = false;
37    let mut tenancy: Option<String> = None;
38    let mut user: Option<String> = None;
39    let mut fingerprint: Option<String> = None;
40    let mut region: Option<String> = None;
41
42    for raw_line in content.lines() {
43        // Strip CRLF by stripping trailing \r after lines() removes \n
44        let line = raw_line.trim_end_matches('\r');
45        let trimmed = line.trim();
46
47        if trimmed.starts_with('[') && trimmed.ends_with(']') {
48            let profile = &trimmed[1..trimmed.len() - 1];
49            in_default = profile == "DEFAULT";
50            continue;
51        }
52
53        if !in_default {
54            continue;
55        }
56
57        if trimmed.starts_with('#') || trimmed.is_empty() {
58            continue;
59        }
60
61        if let Some(eq) = trimmed.find('=') {
62            let key = trimmed[..eq].trim();
63            let val = trimmed[eq + 1..].trim().to_string();
64            match key {
65                "tenancy" => tenancy = Some(val),
66                "user" => user = Some(val),
67                "fingerprint" => fingerprint = Some(val),
68                "region" => region = Some(val),
69                _ => {}
70            }
71        }
72    }
73
74    let tenancy = tenancy
75        .ok_or_else(|| ProviderError::Http("OCI config missing 'tenancy' in [DEFAULT]".into()))?;
76    let user =
77        user.ok_or_else(|| ProviderError::Http("OCI config missing 'user' in [DEFAULT]".into()))?;
78    let fingerprint = fingerprint.ok_or_else(|| {
79        ProviderError::Http("OCI config missing 'fingerprint' in [DEFAULT]".into())
80    })?;
81    let region = region.unwrap_or_default();
82
83    Ok(OciCredentials {
84        tenancy,
85        user,
86        fingerprint,
87        key_pem: key_content.to_string(),
88        region,
89    })
90}
91
92/// Extract the `key_file` path from the `[DEFAULT]` profile of an OCI
93/// config file.
94fn extract_key_file(config_content: &str) -> Result<String, ProviderError> {
95    let mut in_default = false;
96
97    for raw_line in config_content.lines() {
98        let line = raw_line.trim_end_matches('\r');
99        let trimmed = line.trim();
100
101        if trimmed.starts_with('[') && trimmed.ends_with(']') {
102            let profile = &trimmed[1..trimmed.len() - 1];
103            in_default = profile == "DEFAULT";
104            continue;
105        }
106
107        if !in_default || trimmed.starts_with('#') || trimmed.is_empty() {
108            continue;
109        }
110
111        if let Some(eq) = trimmed.find('=') {
112            let key = trimmed[..eq].trim();
113            if key == "key_file" {
114                return Ok(trimmed[eq + 1..].trim().to_string());
115            }
116        }
117    }
118
119    Err(ProviderError::Http(
120        "OCI config missing 'key_file' in [DEFAULT]".into(),
121    ))
122}
123
124/// Validate that an OCID string has a compartment or tenancy prefix.
125fn validate_compartment(ocid: &str) -> Result<(), ProviderError> {
126    if ocid.starts_with("ocid1.compartment.oc1..") || ocid.starts_with("ocid1.tenancy.oc1..") {
127        Ok(())
128    } else {
129        Err(ProviderError::Http(format!(
130            "Invalid compartment OCID: '{}'. Must start with 'ocid1.compartment.oc1..' or 'ocid1.tenancy.oc1..'",
131            ocid
132        )))
133    }
134}
135
136// ---------------------------------------------------------------------------
137// RFC 7231 date formatting
138// ---------------------------------------------------------------------------
139
140const WEEKDAYS: [&str; 7] = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"];
141const MONTHS: [&str; 12] = [
142    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
143];
144
145/// Format a Unix timestamp as an RFC 7231 date string.
146///
147/// Example: `Thu, 26 Mar 2026 12:00:00 GMT`
148fn format_rfc7231(epoch_secs: u64) -> String {
149    let d = super::epoch_to_date(epoch_secs);
150    // Day of week: Jan 1 1970 was a Thursday (index 0 in WEEKDAYS)
151    let weekday = WEEKDAYS[(d.epoch_days % 7) as usize];
152    format!(
153        "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT",
154        weekday,
155        d.day,
156        MONTHS[(d.month - 1) as usize],
157        d.year,
158        d.hours,
159        d.minutes,
160        d.seconds,
161    )
162}
163
164// ---------------------------------------------------------------------------
165// RSA private key parsing
166// ---------------------------------------------------------------------------
167
168/// Parse a PEM-encoded RSA private key (PKCS#1 or PKCS#8).
169fn parse_private_key(pem: &str) -> Result<rsa::RsaPrivateKey, ProviderError> {
170    if pem.contains("ENCRYPTED") {
171        return Err(ProviderError::Http(
172            "OCI private key is encrypted. Please provide an unencrypted key.".into(),
173        ));
174    }
175
176    // Try PKCS#1 first, then PKCS#8
177    if let Ok(key) = rsa::RsaPrivateKey::from_pkcs1_pem(pem) {
178        return Ok(key);
179    }
180
181    rsa::RsaPrivateKey::from_pkcs8_pem(pem)
182        .map_err(|e| ProviderError::Http(format!("Failed to parse OCI private key: {}", e)))
183}
184
185// ---------------------------------------------------------------------------
186// HTTP request signing
187// ---------------------------------------------------------------------------
188
189/// Build the OCI `Authorization` header value for a GET request.
190///
191/// Signs `date`, `(request-target)` and `host` headers using RSA-SHA256.
192/// The caller must parse the RSA private key once and pass it in to avoid
193/// re-parsing on every request.
194fn sign_request(
195    creds: &OciCredentials,
196    rsa_key: &rsa::RsaPrivateKey,
197    date: &str,
198    host: &str,
199    path_and_query: &str,
200) -> Result<String, ProviderError> {
201    let signing_string = format!(
202        "date: {}\n(request-target): get {}\nhost: {}",
203        date, path_and_query, host
204    );
205
206    let signing_key = rsa::pkcs1v15::SigningKey::<sha2::Sha256>::new(rsa_key.clone());
207    let signature = signing_key.sign(signing_string.as_bytes());
208    let sig_b64 = STANDARD.encode(signature.to_bytes());
209
210    let key_id = format!("{}/{}/{}", creds.tenancy, creds.user, creds.fingerprint);
211    Ok(format!(
212        "Signature version=\"1\",keyId=\"{}\",algorithm=\"rsa-sha256\",headers=\"date (request-target) host\",signature=\"{}\"",
213        key_id, sig_b64
214    ))
215}
216
217// ---------------------------------------------------------------------------
218// JSON response models
219// ---------------------------------------------------------------------------
220
221#[derive(Deserialize)]
222struct OciCompartment {
223    id: String,
224    #[serde(rename = "lifecycleState")]
225    lifecycle_state: String,
226}
227
228#[derive(Deserialize)]
229struct OciInstance {
230    id: String,
231    #[serde(rename = "displayName")]
232    display_name: String,
233    #[serde(rename = "lifecycleState")]
234    lifecycle_state: String,
235    shape: String,
236    #[serde(rename = "imageId")]
237    image_id: Option<String>,
238    #[serde(rename = "freeformTags")]
239    freeform_tags: Option<std::collections::HashMap<String, String>>,
240}
241
242#[derive(Deserialize)]
243struct OciVnicAttachment {
244    #[serde(rename = "instanceId")]
245    instance_id: String,
246    #[serde(rename = "vnicId")]
247    vnic_id: Option<String>,
248    #[serde(rename = "lifecycleState")]
249    lifecycle_state: String,
250    #[serde(rename = "isPrimary")]
251    is_primary: Option<bool>,
252}
253
254#[derive(Deserialize)]
255struct OciVnic {
256    #[serde(rename = "publicIp")]
257    public_ip: Option<String>,
258    #[serde(rename = "privateIp")]
259    private_ip: Option<String>,
260}
261
262#[derive(Deserialize)]
263struct OciImage {
264    #[serde(rename = "displayName")]
265    display_name: Option<String>,
266}
267
268// ureq 3.x does not expose the response body on StatusCode errors, so we
269// cannot parse OCI error JSON from failed responses. Other providers in this
270// codebase handle errors the same way (status code only). Kept for future use
271// if ureq adds body-on-error support.
272#[derive(Deserialize)]
273#[allow(dead_code)]
274struct OciErrorBody {
275    code: Option<String>,
276    message: Option<String>,
277}
278
279// ---------------------------------------------------------------------------
280// IP selection, VNIC mapping and helpers
281// ---------------------------------------------------------------------------
282
283fn select_ip(vnic: &OciVnic) -> String {
284    if let Some(ip) = &vnic.public_ip {
285        if !ip.is_empty() {
286            return ip.clone();
287        }
288    }
289    if let Some(ip) = &vnic.private_ip {
290        if !ip.is_empty() {
291            return ip.clone();
292        }
293    }
294    String::new()
295}
296
297fn select_vnic_for_instance(
298    attachments: &[OciVnicAttachment],
299    instance_id: &str,
300) -> Option<String> {
301    let matching: Vec<_> = attachments
302        .iter()
303        .filter(|a| a.instance_id == instance_id && a.lifecycle_state == "ATTACHED")
304        .collect();
305    if let Some(primary) = matching.iter().find(|a| a.is_primary == Some(true)) {
306        return primary.vnic_id.clone();
307    }
308    matching.first().and_then(|a| a.vnic_id.clone())
309}
310
311fn extract_tags(freeform_tags: &Option<std::collections::HashMap<String, String>>) -> Vec<String> {
312    match freeform_tags {
313        Some(tags) => {
314            let mut result: Vec<String> = tags
315                .iter()
316                .map(|(k, v)| {
317                    if v.is_empty() {
318                        k.clone()
319                    } else {
320                        format!("{}:{}", k, v)
321                    }
322                })
323                .collect();
324            result.sort();
325            result
326        }
327        None => Vec::new(),
328    }
329}
330
331// ---------------------------------------------------------------------------
332// Region constants
333// ---------------------------------------------------------------------------
334
335pub const OCI_REGIONS: &[(&str, &str)] = &[
336    // Americas (0..12)
337    ("us-ashburn-1", "Ashburn"),
338    ("us-phoenix-1", "Phoenix"),
339    ("us-sanjose-1", "San Jose"),
340    ("us-chicago-1", "Chicago"),
341    ("ca-toronto-1", "Toronto"),
342    ("ca-montreal-1", "Montreal"),
343    ("br-saopaulo-1", "Sao Paulo"),
344    ("br-vinhedo-1", "Vinhedo"),
345    ("mx-queretaro-1", "Queretaro"),
346    ("mx-monterrey-1", "Monterrey"),
347    ("cl-santiago-1", "Santiago"),
348    ("co-bogota-1", "Bogota"),
349    // EMEA (12..29)
350    ("eu-amsterdam-1", "Amsterdam"),
351    ("eu-frankfurt-1", "Frankfurt"),
352    ("eu-zurich-1", "Zurich"),
353    ("eu-stockholm-1", "Stockholm"),
354    ("eu-marseille-1", "Marseille"),
355    ("eu-milan-1", "Milan"),
356    ("eu-paris-1", "Paris"),
357    ("eu-madrid-1", "Madrid"),
358    ("eu-jovanovac-1", "Jovanovac"),
359    ("uk-london-1", "London"),
360    ("uk-cardiff-1", "Cardiff"),
361    ("me-jeddah-1", "Jeddah"),
362    ("me-abudhabi-1", "Abu Dhabi"),
363    ("me-dubai-1", "Dubai"),
364    ("me-riyadh-1", "Riyadh"),
365    ("af-johannesburg-1", "Johannesburg"),
366    ("il-jerusalem-1", "Jerusalem"),
367    // Asia Pacific (29..38)
368    ("ap-tokyo-1", "Tokyo"),
369    ("ap-osaka-1", "Osaka"),
370    ("ap-seoul-1", "Seoul"),
371    ("ap-chuncheon-1", "Chuncheon"),
372    ("ap-singapore-1", "Singapore"),
373    ("ap-sydney-1", "Sydney"),
374    ("ap-melbourne-1", "Melbourne"),
375    ("ap-mumbai-1", "Mumbai"),
376    ("ap-hyderabad-1", "Hyderabad"),
377];
378
379pub const OCI_REGION_GROUPS: &[(&str, usize, usize)] = &[
380    ("Americas", 0, 12),
381    ("EMEA", 12, 29),
382    ("Asia Pacific", 29, 38),
383];
384
385// ---------------------------------------------------------------------------
386// Provider trait implementation
387// ---------------------------------------------------------------------------
388
389impl Provider for Oracle {
390    fn name(&self) -> &str {
391        "oracle"
392    }
393
394    fn short_label(&self) -> &str {
395        "oci"
396    }
397
398    fn fetch_hosts_cancellable(
399        &self,
400        token: &str,
401        cancel: &AtomicBool,
402    ) -> Result<Vec<ProviderHost>, ProviderError> {
403        self.fetch_hosts_with_progress(token, cancel, &|_| {})
404    }
405
406    fn fetch_hosts_with_progress(
407        &self,
408        token: &str,
409        cancel: &AtomicBool,
410        progress: &dyn Fn(&str),
411    ) -> Result<Vec<ProviderHost>, ProviderError> {
412        if self.compartment.is_empty() {
413            return Err(ProviderError::Http(
414                "No compartment configured. Run: purple provider add oracle --token ~/.oci/config --compartment <OCID>".to_string(),
415            ));
416        }
417        validate_compartment(&self.compartment)?;
418
419        let config_content = std::fs::read_to_string(token).map_err(|e| {
420            ProviderError::Http(format!("Cannot read OCI config file '{}': {}", token, e))
421        })?;
422        let key_file = extract_key_file(&config_content)?;
423        let expanded = if key_file.starts_with("~/") {
424            if let Some(home) = dirs::home_dir() {
425                format!("{}{}", home.display(), &key_file[1..])
426            } else {
427                key_file.clone()
428            }
429        } else {
430            key_file.clone()
431        };
432        let key_content = std::fs::read_to_string(&expanded).map_err(|e| {
433            ProviderError::Http(format!("Cannot read OCI private key '{}': {}", expanded, e))
434        })?;
435        let creds = parse_oci_config(&config_content, &key_content)?;
436        let rsa_key = parse_private_key(&creds.key_pem)?;
437
438        let regions: Vec<String> = if self.regions.is_empty() {
439            if creds.region.is_empty() {
440                return Err(ProviderError::Http(
441                    "No regions configured and OCI config has no default region".to_string(),
442                ));
443            }
444            vec![creds.region.clone()]
445        } else {
446            self.regions.clone()
447        };
448
449        let mut all_hosts = Vec::new();
450        let mut region_failures = 0usize;
451        let total_regions = regions.len();
452        for region in &regions {
453            if cancel.load(std::sync::atomic::Ordering::Relaxed) {
454                return Err(ProviderError::Cancelled);
455            }
456            progress(&format!("Syncing {} ...", region));
457            match self.fetch_region(&creds, &rsa_key, region, cancel, progress) {
458                Ok(mut hosts) => all_hosts.append(&mut hosts),
459                Err(ProviderError::AuthFailed) => return Err(ProviderError::AuthFailed),
460                Err(ProviderError::RateLimited) => return Err(ProviderError::RateLimited),
461                Err(ProviderError::Cancelled) => return Err(ProviderError::Cancelled),
462                Err(ProviderError::PartialResult {
463                    hosts: mut partial, ..
464                }) => {
465                    all_hosts.append(&mut partial);
466                    region_failures += 1;
467                }
468                Err(_) => {
469                    region_failures += 1;
470                }
471            }
472        }
473        if region_failures > 0 {
474            if all_hosts.is_empty() {
475                return Err(ProviderError::Http(format!(
476                    "Failed to sync all {} region(s)",
477                    total_regions
478                )));
479            }
480            return Err(ProviderError::PartialResult {
481                hosts: all_hosts,
482                failures: region_failures,
483                total: total_regions,
484            });
485        }
486        Ok(all_hosts)
487    }
488}
489
490impl Oracle {
491    /// Perform a signed GET request against the OCI API.
492    fn signed_get(
493        &self,
494        creds: &OciCredentials,
495        rsa_key: &rsa::RsaPrivateKey,
496        agent: &ureq::Agent,
497        host: &str,
498        url: &str,
499    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
500        let now = SystemTime::now()
501            .duration_since(SystemTime::UNIX_EPOCH)
502            .unwrap_or_default()
503            .as_secs();
504        let date = format_rfc7231(now);
505
506        // Extract path+query from URL (everything after the host part)
507        let path_and_query = if let Some(pos) = url.find(host) {
508            &url[pos + host.len()..]
509        } else {
510            // Fallback: strip scheme + host
511            url.splitn(4, '/').nth(3).map_or("/", |p| {
512                // We need the leading slash
513                &url[url.len() - p.len() - 1..]
514            })
515        };
516
517        let auth = sign_request(creds, rsa_key, &date, host, path_and_query)?;
518
519        agent
520            .get(url)
521            .header("date", &date)
522            .header("Authorization", &auth)
523            .call()
524            .map_err(|e| match e {
525                ureq::Error::StatusCode(401 | 403) => ProviderError::AuthFailed,
526                ureq::Error::StatusCode(429) => ProviderError::RateLimited,
527                ureq::Error::StatusCode(code) => ProviderError::Http(format!("HTTP {}", code)),
528                other => super::map_ureq_error(other),
529            })
530    }
531
532    /// List active sub-compartments (Identity API supports compartmentIdInSubtree).
533    fn list_compartments(
534        &self,
535        creds: &OciCredentials,
536        rsa_key: &rsa::RsaPrivateKey,
537        agent: &ureq::Agent,
538        region: &str,
539        cancel: &AtomicBool,
540    ) -> Result<Vec<String>, ProviderError> {
541        let host = format!("identity.{}.oraclecloud.com", region);
542        let compartment_encoded = urlencoding_encode(&self.compartment);
543
544        let mut compartment_ids = vec![self.compartment.clone()];
545        let mut next_page: Option<String> = None;
546        for _ in 0..500 {
547            if cancel.load(Ordering::Relaxed) {
548                return Err(ProviderError::Cancelled);
549            }
550
551            let url = match &next_page {
552                Some(page) => format!(
553                    "https://{}/20160918/compartments?compartmentId={}&compartmentIdInSubtree=true&lifecycleState=ACTIVE&limit=100&page={}",
554                    host,
555                    compartment_encoded,
556                    urlencoding_encode(page)
557                ),
558                None => format!(
559                    "https://{}/20160918/compartments?compartmentId={}&compartmentIdInSubtree=true&lifecycleState=ACTIVE&limit=100",
560                    host, compartment_encoded
561                ),
562            };
563
564            let mut resp = self.signed_get(creds, rsa_key, agent, &host, &url)?;
565
566            let opc_next = resp
567                .headers()
568                .get("opc-next-page")
569                .and_then(|v| v.to_str().ok())
570                .filter(|s| !s.is_empty())
571                .map(String::from);
572
573            let items: Vec<OciCompartment> = resp
574                .body_mut()
575                .read_json()
576                .map_err(|e| ProviderError::Parse(e.to_string()))?;
577
578            compartment_ids.extend(
579                items
580                    .into_iter()
581                    .filter(|c| c.lifecycle_state == "ACTIVE")
582                    .map(|c| c.id),
583            );
584
585            match opc_next {
586                Some(p) => next_page = Some(p),
587                None => break,
588            }
589        }
590        Ok(compartment_ids)
591    }
592
593    fn fetch_region(
594        &self,
595        creds: &OciCredentials,
596        rsa_key: &rsa::RsaPrivateKey,
597        region: &str,
598        cancel: &AtomicBool,
599        progress: &dyn Fn(&str),
600    ) -> Result<Vec<ProviderHost>, ProviderError> {
601        let agent = super::http_agent();
602        let host = format!("iaas.{}.oraclecloud.com", region);
603
604        // Step 0: Discover all compartments (root + sub-compartments)
605        progress("Listing compartments...");
606        let compartment_ids = self.list_compartments(creds, rsa_key, &agent, region, cancel)?;
607        let total_compartments = compartment_ids.len();
608
609        // Step 1: List instances across all compartments (paginated per compartment)
610        let mut instances: Vec<OciInstance> = Vec::new();
611        for (ci, comp_id) in compartment_ids.iter().enumerate() {
612            if cancel.load(Ordering::Relaxed) {
613                return Err(ProviderError::Cancelled);
614            }
615            if total_compartments > 1 {
616                progress(&format!(
617                    "Listing instances ({}/{} compartments)...",
618                    ci + 1,
619                    total_compartments
620                ));
621            } else {
622                progress("Listing instances...");
623            }
624            let compartment_encoded = urlencoding_encode(comp_id);
625            let mut next_page: Option<String> = None;
626            for _ in 0..500 {
627                if cancel.load(Ordering::Relaxed) {
628                    return Err(ProviderError::Cancelled);
629                }
630
631                let url = match &next_page {
632                    Some(page) => format!(
633                        "https://{}/20160918/instances?compartmentId={}&limit=100&page={}",
634                        host,
635                        compartment_encoded,
636                        urlencoding_encode(page)
637                    ),
638                    None => format!(
639                        "https://{}/20160918/instances?compartmentId={}&limit=100",
640                        host, compartment_encoded
641                    ),
642                };
643
644                let mut resp = self.signed_get(creds, rsa_key, &agent, &host, &url)?;
645
646                let opc_next = resp
647                    .headers()
648                    .get("opc-next-page")
649                    .and_then(|v| v.to_str().ok())
650                    .filter(|s| !s.is_empty())
651                    .map(String::from);
652
653                let page_items: Vec<OciInstance> = resp
654                    .body_mut()
655                    .read_json()
656                    .map_err(|e| ProviderError::Parse(e.to_string()))?;
657
658                instances.extend(
659                    page_items
660                        .into_iter()
661                        .filter(|i| i.lifecycle_state != "TERMINATED"),
662                );
663
664                match opc_next {
665                    Some(p) => next_page = Some(p),
666                    None => break,
667                }
668            }
669        }
670
671        // Step 2: List VNIC attachments across all compartments (paginated per compartment)
672        progress("Listing VNIC attachments...");
673        let mut attachments: Vec<OciVnicAttachment> = Vec::new();
674        for comp_id in &compartment_ids {
675            if cancel.load(Ordering::Relaxed) {
676                return Err(ProviderError::Cancelled);
677            }
678            let compartment_encoded = urlencoding_encode(comp_id);
679            let mut next_page: Option<String> = None;
680            for _ in 0..500 {
681                if cancel.load(Ordering::Relaxed) {
682                    return Err(ProviderError::Cancelled);
683                }
684
685                let url = match &next_page {
686                    Some(page) => format!(
687                        "https://{}/20160918/vnicAttachments?compartmentId={}&limit=100&page={}",
688                        host,
689                        compartment_encoded,
690                        urlencoding_encode(page)
691                    ),
692                    None => format!(
693                        "https://{}/20160918/vnicAttachments?compartmentId={}&limit=100",
694                        host, compartment_encoded
695                    ),
696                };
697
698                let mut resp = self.signed_get(creds, rsa_key, &agent, &host, &url)?;
699
700                let opc_next = resp
701                    .headers()
702                    .get("opc-next-page")
703                    .and_then(|v| v.to_str().ok())
704                    .filter(|s| !s.is_empty())
705                    .map(String::from);
706
707                let page_items: Vec<OciVnicAttachment> = resp
708                    .body_mut()
709                    .read_json()
710                    .map_err(|e| ProviderError::Parse(e.to_string()))?;
711
712                attachments.extend(page_items);
713
714                match opc_next {
715                    Some(p) => next_page = Some(p),
716                    None => break,
717                }
718            }
719        }
720
721        // Step 3: Resolve images (N+1 per unique imageId)
722        let unique_image_ids: Vec<String> = {
723            let mut ids: Vec<String> = instances
724                .iter()
725                .filter_map(|i| i.image_id.clone())
726                .collect();
727            ids.sort_unstable();
728            ids.dedup();
729            ids
730        };
731        let total_images = unique_image_ids.len();
732        let mut image_names: HashMap<String, String> = HashMap::new();
733        for (n, image_id) in unique_image_ids.iter().enumerate() {
734            if cancel.load(Ordering::Relaxed) {
735                return Err(ProviderError::Cancelled);
736            }
737            progress(&format!("Resolving images ({}/{})...", n + 1, total_images));
738
739            let url = format!("https://{}/20160918/images/{}", host, image_id);
740            match self.signed_get(creds, rsa_key, &agent, &host, &url) {
741                Ok(mut resp) => {
742                    if let Ok(img) = resp.body_mut().read_json::<OciImage>() {
743                        if let Some(name) = img.display_name {
744                            image_names.insert(image_id.clone(), name);
745                        }
746                    }
747                }
748                Err(ProviderError::AuthFailed) => return Err(ProviderError::AuthFailed),
749                Err(ProviderError::RateLimited) => return Err(ProviderError::RateLimited),
750                Err(_) => {} // Non-fatal: skip silently
751            }
752        }
753
754        // Step 4: Get VNIC + build hosts (N+1 per VNIC for RUNNING instances)
755        let total_instances = instances.len();
756        let mut hosts: Vec<ProviderHost> = Vec::new();
757        let mut fetch_failures = 0usize;
758        for (n, instance) in instances.iter().enumerate() {
759            if cancel.load(Ordering::Relaxed) {
760                return Err(ProviderError::Cancelled);
761            }
762            progress(&format!("Fetching IPs ({}/{})...", n + 1, total_instances));
763
764            let ip = if instance.lifecycle_state == "RUNNING" {
765                match select_vnic_for_instance(&attachments, &instance.id) {
766                    Some(vnic_id) => {
767                        let url = format!("https://{}/20160918/vnics/{}", host, vnic_id);
768                        match self.signed_get(creds, rsa_key, &agent, &host, &url) {
769                            Ok(mut resp) => match resp.body_mut().read_json::<OciVnic>() {
770                                Ok(vnic) => {
771                                    let raw = select_ip(&vnic);
772                                    super::strip_cidr(&raw).to_string()
773                                }
774                                Err(_) => {
775                                    fetch_failures += 1;
776                                    String::new()
777                                }
778                            },
779                            Err(ProviderError::AuthFailed) => {
780                                return Err(ProviderError::AuthFailed);
781                            }
782                            Err(ProviderError::RateLimited) => {
783                                return Err(ProviderError::RateLimited);
784                            }
785                            Err(ProviderError::Http(ref msg)) if msg == "HTTP 404" => {
786                                // 404: race condition, silent skip
787                                String::new()
788                            }
789                            Err(_) => {
790                                fetch_failures += 1;
791                                String::new()
792                            }
793                        }
794                    }
795                    None => String::new(),
796                }
797            } else {
798                String::new()
799            };
800
801            let os_name = instance
802                .image_id
803                .as_ref()
804                .and_then(|id| image_names.get(id))
805                .cloned()
806                .unwrap_or_default();
807
808            let mut metadata = Vec::new();
809            metadata.push(("region".to_string(), region.to_string()));
810            metadata.push(("shape".to_string(), instance.shape.clone()));
811            if !os_name.is_empty() {
812                metadata.push(("os".to_string(), os_name));
813            }
814            metadata.push(("status".to_string(), instance.lifecycle_state.clone()));
815
816            hosts.push(ProviderHost {
817                server_id: instance.id.clone(),
818                name: instance.display_name.clone(),
819                ip,
820                tags: extract_tags(&instance.freeform_tags),
821                metadata,
822            });
823        }
824
825        if fetch_failures > 0 {
826            if hosts.is_empty() {
827                return Err(ProviderError::Http(format!(
828                    "Failed to fetch details for all {} instances",
829                    total_instances
830                )));
831            }
832            return Err(ProviderError::PartialResult {
833                hosts,
834                failures: fetch_failures,
835                total: total_instances,
836            });
837        }
838
839        Ok(hosts)
840    }
841}
842
843/// Minimal percent-encoding for query parameter values (delegates to shared implementation).
844fn urlencoding_encode(input: &str) -> String {
845    super::percent_encode(input)
846}
847
848// ---------------------------------------------------------------------------
849// Tests
850// ---------------------------------------------------------------------------
851
852#[cfg(test)]
853#[path = "oracle_tests.rs"]
854mod tests;