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        env: &crate::runtime::env::Env,
403    ) -> Result<Vec<ProviderHost>, ProviderError> {
404        self.fetch_hosts_with_progress(token, cancel, env, &|_| {})
405    }
406
407    fn fetch_hosts_with_progress(
408        &self,
409        token: &str,
410        cancel: &AtomicBool,
411        env: &crate::runtime::env::Env,
412        progress: &dyn Fn(&str),
413    ) -> Result<Vec<ProviderHost>, ProviderError> {
414        if self.compartment.is_empty() {
415            return Err(ProviderError::Http(
416                "No compartment configured. Run: purple provider add oracle --token ~/.oci/config --compartment <OCID>".to_string(),
417            ));
418        }
419        validate_compartment(&self.compartment)?;
420
421        let config_content = std::fs::read_to_string(token).map_err(|e| {
422            ProviderError::Http(format!("Cannot read OCI config file '{}': {}", token, e))
423        })?;
424        let key_file = extract_key_file(&config_content)?;
425        let expanded = if let Some(rest) = key_file.strip_prefix("~/") {
426            match env.paths() {
427                Some(p) => p.home().join(rest).to_string_lossy().into_owned(),
428                None => key_file.clone(),
429            }
430        } else {
431            key_file.clone()
432        };
433        let key_content = std::fs::read_to_string(&expanded).map_err(|e| {
434            ProviderError::Http(format!("Cannot read OCI private key '{}': {}", expanded, e))
435        })?;
436        let creds = parse_oci_config(&config_content, &key_content)?;
437        let rsa_key = parse_private_key(&creds.key_pem)?;
438
439        let regions: Vec<String> = if self.regions.is_empty() {
440            if creds.region.is_empty() {
441                return Err(ProviderError::Http(
442                    "No regions configured and OCI config has no default region".to_string(),
443                ));
444            }
445            vec![creds.region.clone()]
446        } else {
447            self.regions.clone()
448        };
449
450        let mut all_hosts = Vec::new();
451        let mut region_failures = 0usize;
452        let total_regions = regions.len();
453        for region in &regions {
454            if cancel.load(std::sync::atomic::Ordering::Relaxed) {
455                return Err(ProviderError::Cancelled);
456            }
457            progress(&format!("Syncing {} ...", region));
458            match self.fetch_region(&creds, &rsa_key, region, cancel, progress) {
459                Ok(mut hosts) => all_hosts.append(&mut hosts),
460                Err(ProviderError::AuthFailed) => return Err(ProviderError::AuthFailed),
461                Err(ProviderError::RateLimited) => return Err(ProviderError::RateLimited),
462                Err(ProviderError::Cancelled) => return Err(ProviderError::Cancelled),
463                Err(ProviderError::PartialResult {
464                    hosts: mut partial, ..
465                }) => {
466                    all_hosts.append(&mut partial);
467                    region_failures += 1;
468                }
469                Err(_) => {
470                    region_failures += 1;
471                }
472            }
473        }
474        if region_failures > 0 {
475            if all_hosts.is_empty() {
476                return Err(ProviderError::Http(format!(
477                    "Failed to sync all {} region(s)",
478                    total_regions
479                )));
480            }
481            return Err(ProviderError::PartialResult {
482                hosts: all_hosts,
483                failures: region_failures,
484                total: total_regions,
485            });
486        }
487        Ok(all_hosts)
488    }
489}
490
491impl Oracle {
492    /// Perform a signed GET request against the OCI API.
493    fn signed_get(
494        &self,
495        creds: &OciCredentials,
496        rsa_key: &rsa::RsaPrivateKey,
497        agent: &ureq::Agent,
498        host: &str,
499        url: &str,
500    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
501        let now = SystemTime::now()
502            .duration_since(SystemTime::UNIX_EPOCH)
503            .unwrap_or_default()
504            .as_secs();
505        let date = format_rfc7231(now);
506
507        // Extract path+query from URL (everything after the host part)
508        let path_and_query = if let Some(pos) = url.find(host) {
509            &url[pos + host.len()..]
510        } else {
511            // Fallback: strip scheme + host
512            url.splitn(4, '/').nth(3).map_or("/", |p| {
513                // We need the leading slash
514                &url[url.len() - p.len() - 1..]
515            })
516        };
517
518        let auth = sign_request(creds, rsa_key, &date, host, path_and_query)?;
519
520        agent
521            .get(url)
522            .header("date", &date)
523            .header("Authorization", &auth)
524            .call()
525            .map_err(|e| match e {
526                ureq::Error::StatusCode(401 | 403) => ProviderError::AuthFailed,
527                ureq::Error::StatusCode(429) => ProviderError::RateLimited,
528                ureq::Error::StatusCode(code) => ProviderError::Http(format!("HTTP {}", code)),
529                other => super::map_ureq_error(other),
530            })
531    }
532
533    /// List active sub-compartments (Identity API supports compartmentIdInSubtree).
534    fn list_compartments(
535        &self,
536        creds: &OciCredentials,
537        rsa_key: &rsa::RsaPrivateKey,
538        agent: &ureq::Agent,
539        region: &str,
540        cancel: &AtomicBool,
541    ) -> Result<Vec<String>, ProviderError> {
542        let host = format!("identity.{}.oraclecloud.com", region);
543        let compartment_encoded = urlencoding_encode(&self.compartment);
544
545        let mut compartment_ids = vec![self.compartment.clone()];
546        let mut next_page: Option<String> = None;
547        for _ in 0..500 {
548            if cancel.load(Ordering::Relaxed) {
549                return Err(ProviderError::Cancelled);
550            }
551
552            let url = match &next_page {
553                Some(page) => format!(
554                    "https://{}/20160918/compartments?compartmentId={}&compartmentIdInSubtree=true&lifecycleState=ACTIVE&limit=100&page={}",
555                    host,
556                    compartment_encoded,
557                    urlencoding_encode(page)
558                ),
559                None => format!(
560                    "https://{}/20160918/compartments?compartmentId={}&compartmentIdInSubtree=true&lifecycleState=ACTIVE&limit=100",
561                    host, compartment_encoded
562                ),
563            };
564
565            let mut resp = self.signed_get(creds, rsa_key, agent, &host, &url)?;
566
567            let opc_next = resp
568                .headers()
569                .get("opc-next-page")
570                .and_then(|v| v.to_str().ok())
571                .filter(|s| !s.is_empty())
572                .map(String::from);
573
574            let items: Vec<OciCompartment> = resp
575                .body_mut()
576                .read_json()
577                .map_err(|e| ProviderError::Parse(e.to_string()))?;
578
579            compartment_ids.extend(
580                items
581                    .into_iter()
582                    .filter(|c| c.lifecycle_state == "ACTIVE")
583                    .map(|c| c.id),
584            );
585
586            match opc_next {
587                Some(p) => next_page = Some(p),
588                None => break,
589            }
590        }
591        Ok(compartment_ids)
592    }
593
594    fn fetch_region(
595        &self,
596        creds: &OciCredentials,
597        rsa_key: &rsa::RsaPrivateKey,
598        region: &str,
599        cancel: &AtomicBool,
600        progress: &dyn Fn(&str),
601    ) -> Result<Vec<ProviderHost>, ProviderError> {
602        let agent = super::http_agent();
603        let host = format!("iaas.{}.oraclecloud.com", region);
604
605        // Step 0: Discover all compartments (root + sub-compartments)
606        progress("Listing compartments...");
607        let compartment_ids = self.list_compartments(creds, rsa_key, &agent, region, cancel)?;
608        let total_compartments = compartment_ids.len();
609
610        // Step 1: List instances across all compartments (paginated per compartment)
611        let mut instances: Vec<OciInstance> = Vec::new();
612        for (ci, comp_id) in compartment_ids.iter().enumerate() {
613            if cancel.load(Ordering::Relaxed) {
614                return Err(ProviderError::Cancelled);
615            }
616            if total_compartments > 1 {
617                progress(&format!(
618                    "Listing instances ({}/{} compartments)...",
619                    ci + 1,
620                    total_compartments
621                ));
622            } else {
623                progress("Listing instances...");
624            }
625            let compartment_encoded = urlencoding_encode(comp_id);
626            let mut next_page: Option<String> = None;
627            for _ in 0..500 {
628                if cancel.load(Ordering::Relaxed) {
629                    return Err(ProviderError::Cancelled);
630                }
631
632                let url = match &next_page {
633                    Some(page) => format!(
634                        "https://{}/20160918/instances?compartmentId={}&limit=100&page={}",
635                        host,
636                        compartment_encoded,
637                        urlencoding_encode(page)
638                    ),
639                    None => format!(
640                        "https://{}/20160918/instances?compartmentId={}&limit=100",
641                        host, compartment_encoded
642                    ),
643                };
644
645                let mut resp = self.signed_get(creds, rsa_key, &agent, &host, &url)?;
646
647                let opc_next = resp
648                    .headers()
649                    .get("opc-next-page")
650                    .and_then(|v| v.to_str().ok())
651                    .filter(|s| !s.is_empty())
652                    .map(String::from);
653
654                let page_items: Vec<OciInstance> = resp
655                    .body_mut()
656                    .read_json()
657                    .map_err(|e| ProviderError::Parse(e.to_string()))?;
658
659                instances.extend(
660                    page_items
661                        .into_iter()
662                        .filter(|i| i.lifecycle_state != "TERMINATED"),
663                );
664
665                match opc_next {
666                    Some(p) => next_page = Some(p),
667                    None => break,
668                }
669            }
670        }
671
672        // Step 2: List VNIC attachments across all compartments (paginated per compartment)
673        progress("Listing VNIC attachments...");
674        let mut attachments: Vec<OciVnicAttachment> = Vec::new();
675        for comp_id in &compartment_ids {
676            if cancel.load(Ordering::Relaxed) {
677                return Err(ProviderError::Cancelled);
678            }
679            let compartment_encoded = urlencoding_encode(comp_id);
680            let mut next_page: Option<String> = None;
681            for _ in 0..500 {
682                if cancel.load(Ordering::Relaxed) {
683                    return Err(ProviderError::Cancelled);
684                }
685
686                let url = match &next_page {
687                    Some(page) => format!(
688                        "https://{}/20160918/vnicAttachments?compartmentId={}&limit=100&page={}",
689                        host,
690                        compartment_encoded,
691                        urlencoding_encode(page)
692                    ),
693                    None => format!(
694                        "https://{}/20160918/vnicAttachments?compartmentId={}&limit=100",
695                        host, compartment_encoded
696                    ),
697                };
698
699                let mut resp = self.signed_get(creds, rsa_key, &agent, &host, &url)?;
700
701                let opc_next = resp
702                    .headers()
703                    .get("opc-next-page")
704                    .and_then(|v| v.to_str().ok())
705                    .filter(|s| !s.is_empty())
706                    .map(String::from);
707
708                let page_items: Vec<OciVnicAttachment> = resp
709                    .body_mut()
710                    .read_json()
711                    .map_err(|e| ProviderError::Parse(e.to_string()))?;
712
713                attachments.extend(page_items);
714
715                match opc_next {
716                    Some(p) => next_page = Some(p),
717                    None => break,
718                }
719            }
720        }
721
722        // Step 3: Resolve images (N+1 per unique imageId)
723        let unique_image_ids: Vec<String> = {
724            let mut ids: Vec<String> = instances
725                .iter()
726                .filter_map(|i| i.image_id.clone())
727                .collect();
728            ids.sort_unstable();
729            ids.dedup();
730            ids
731        };
732        let total_images = unique_image_ids.len();
733        let mut image_names: HashMap<String, String> = HashMap::new();
734        for (n, image_id) in unique_image_ids.iter().enumerate() {
735            if cancel.load(Ordering::Relaxed) {
736                return Err(ProviderError::Cancelled);
737            }
738            progress(&format!("Resolving images ({}/{})...", n + 1, total_images));
739
740            let url = format!("https://{}/20160918/images/{}", host, image_id);
741            match self.signed_get(creds, rsa_key, &agent, &host, &url) {
742                Ok(mut resp) => {
743                    if let Ok(img) = resp.body_mut().read_json::<OciImage>() {
744                        if let Some(name) = img.display_name {
745                            image_names.insert(image_id.clone(), name);
746                        }
747                    }
748                }
749                Err(ProviderError::AuthFailed) => return Err(ProviderError::AuthFailed),
750                Err(ProviderError::RateLimited) => return Err(ProviderError::RateLimited),
751                Err(_) => {} // Non-fatal: skip silently
752            }
753        }
754
755        // Step 4: Get VNIC + build hosts (N+1 per VNIC for RUNNING instances)
756        let total_instances = instances.len();
757        let mut hosts: Vec<ProviderHost> = Vec::new();
758        let mut fetch_failures = 0usize;
759        for (n, instance) in instances.iter().enumerate() {
760            if cancel.load(Ordering::Relaxed) {
761                return Err(ProviderError::Cancelled);
762            }
763            progress(&format!("Fetching IPs ({}/{})...", n + 1, total_instances));
764
765            let ip = if instance.lifecycle_state == "RUNNING" {
766                match select_vnic_for_instance(&attachments, &instance.id) {
767                    Some(vnic_id) => {
768                        let url = format!("https://{}/20160918/vnics/{}", host, vnic_id);
769                        match self.signed_get(creds, rsa_key, &agent, &host, &url) {
770                            Ok(mut resp) => match resp.body_mut().read_json::<OciVnic>() {
771                                Ok(vnic) => {
772                                    let raw = select_ip(&vnic);
773                                    super::strip_cidr(&raw).to_string()
774                                }
775                                Err(_) => {
776                                    fetch_failures += 1;
777                                    String::new()
778                                }
779                            },
780                            Err(ProviderError::AuthFailed) => {
781                                return Err(ProviderError::AuthFailed);
782                            }
783                            Err(ProviderError::RateLimited) => {
784                                return Err(ProviderError::RateLimited);
785                            }
786                            Err(ProviderError::Http(ref msg)) if msg == "HTTP 404" => {
787                                // 404: race condition, silent skip
788                                String::new()
789                            }
790                            Err(_) => {
791                                fetch_failures += 1;
792                                String::new()
793                            }
794                        }
795                    }
796                    None => String::new(),
797                }
798            } else {
799                String::new()
800            };
801
802            let os_name = instance
803                .image_id
804                .as_ref()
805                .and_then(|id| image_names.get(id))
806                .cloned()
807                .unwrap_or_default();
808
809            let mut metadata = Vec::new();
810            metadata.push(("region".to_string(), region.to_string()));
811            metadata.push(("shape".to_string(), instance.shape.clone()));
812            if !os_name.is_empty() {
813                metadata.push(("os".to_string(), os_name));
814            }
815            metadata.push(("status".to_string(), instance.lifecycle_state.clone()));
816
817            hosts.push(ProviderHost {
818                server_id: instance.id.clone(),
819                name: instance.display_name.clone(),
820                ip,
821                tags: extract_tags(&instance.freeform_tags),
822                metadata,
823            });
824        }
825
826        if fetch_failures > 0 {
827            if hosts.is_empty() {
828                return Err(ProviderError::Http(format!(
829                    "Failed to fetch details for all {} instances",
830                    total_instances
831                )));
832            }
833            return Err(ProviderError::PartialResult {
834                hosts,
835                failures: fetch_failures,
836                total: total_instances,
837            });
838        }
839
840        Ok(hosts)
841    }
842}
843
844/// Minimal percent-encoding for query parameter values (delegates to shared implementation).
845fn urlencoding_encode(input: &str) -> String {
846    super::percent_encode(input)
847}
848
849// ---------------------------------------------------------------------------
850// Tests
851// ---------------------------------------------------------------------------
852
853#[cfg(test)]
854#[path = "oracle_tests.rs"]
855mod tests;