Skip to main content

rigg_client/
arm.rs

1//! Azure Resource Manager client for discovering Search and Foundry services
2
3use reqwest::Client;
4use serde::Deserialize;
5use tracing::debug;
6
7use crate::auth::AzCliAuth;
8use crate::error::ClientError;
9
10const ARM_BASE_URL: &str = "https://management.azure.com";
11
12/// Azure Resource Manager client for subscription/service discovery
13pub struct ArmClient {
14    http: Client,
15    token: String,
16}
17
18/// Azure subscription
19#[derive(Debug, Clone, Deserialize)]
20#[serde(rename_all = "camelCase")]
21pub struct Subscription {
22    pub subscription_id: String,
23    pub display_name: String,
24    pub state: String,
25}
26
27impl std::fmt::Display for Subscription {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        write!(f, "{} ({})", self.display_name, self.subscription_id)
30    }
31}
32
33/// Azure AI Search service
34#[derive(Debug, Clone, Deserialize)]
35pub struct SearchService {
36    pub name: String,
37    pub location: String,
38    pub sku: SearchServiceSku,
39    #[serde(default)]
40    pub id: String,
41}
42
43#[derive(Debug, Clone, Deserialize)]
44pub struct SearchServiceSku {
45    pub name: String,
46}
47
48impl std::fmt::Display for SearchService {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(
51            f,
52            "{} ({}, {})",
53            self.name,
54            self.location,
55            self.sku.name.to_uppercase()
56        )
57    }
58}
59
60/// Result of the discovery flow
61#[derive(Debug, Clone)]
62pub struct DiscoveredService {
63    pub name: String,
64    pub subscription_id: String,
65    pub location: String,
66}
67
68/// Azure AI Services account (kind=AIServices)
69#[derive(Debug, Clone, Deserialize)]
70pub struct AiServicesAccount {
71    pub name: String,
72    pub location: String,
73    #[serde(default)]
74    pub kind: String,
75    #[serde(default)]
76    pub id: String,
77    #[serde(default)]
78    pub properties: AiServicesAccountProperties,
79}
80
81#[derive(Debug, Clone, Default, Deserialize)]
82pub struct AiServicesAccountProperties {
83    /// Primary endpoint (e.g., "https://name.cognitiveservices.azure.com/")
84    #[serde(default)]
85    pub endpoint: Option<String>,
86}
87
88impl AiServicesAccount {
89    /// Derive the `.services.ai.azure.com` endpoint for the agents API.
90    ///
91    /// Extracts the custom subdomain from the ARM `properties.endpoint`
92    /// (which may differ from the resource name), then constructs the
93    /// AI services endpoint. Falls back to the resource name.
94    pub fn agents_endpoint(&self) -> String {
95        if let Some(ref endpoint) = self.properties.endpoint {
96            if let Some(subdomain) = extract_subdomain(endpoint) {
97                return format!("https://{}.services.ai.azure.com", subdomain);
98            }
99        }
100        format!("https://{}.services.ai.azure.com", self.name)
101    }
102}
103
104/// Extract the subdomain from an Azure endpoint URL.
105///
106/// `"https://my-svc.cognitiveservices.azure.com/"` → `"my-svc"`
107fn extract_subdomain(endpoint: &str) -> Option<&str> {
108    let host = endpoint.strip_prefix("https://")?.split('/').next()?;
109    host.split('.').next()
110}
111
112impl std::fmt::Display for AiServicesAccount {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        write!(f, "{} ({})", self.name, self.location)
115    }
116}
117
118/// Microsoft Foundry project (sub-resource of AI Services account)
119#[derive(Debug, Clone, Deserialize)]
120pub struct FoundryProject {
121    /// ARM name — may be "accountName/projectName" for sub-resources
122    #[serde(default)]
123    name: String,
124    pub location: String,
125    #[serde(default)]
126    pub id: String,
127    #[serde(default)]
128    pub properties: FoundryProjectProperties,
129}
130
131#[derive(Debug, Clone, Default, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct FoundryProjectProperties {
134    #[serde(default)]
135    pub display_name: String,
136}
137
138impl FoundryProject {
139    /// The project display name (human-friendly, e.g. "proj-default")
140    pub fn display_name(&self) -> &str {
141        if !self.properties.display_name.is_empty() {
142            &self.properties.display_name
143        } else {
144            // Fallback: parse from "account/project" ARM name
145            self.name.rsplit('/').next().unwrap_or(&self.name)
146        }
147    }
148}
149
150impl std::fmt::Display for FoundryProject {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        write!(f, "{} ({})", self.display_name(), self.location)
153    }
154}
155
156/// Azure Storage account
157#[derive(Debug, Clone, Deserialize)]
158pub struct StorageAccount {
159    pub name: String,
160    pub location: String,
161    #[serde(default)]
162    pub id: String,
163}
164
165impl std::fmt::Display for StorageAccount {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        write!(f, "{} ({})", self.name, self.location)
168    }
169}
170
171/// Storage account key
172#[derive(Debug, Clone, Deserialize)]
173struct StorageKey {
174    value: String,
175}
176
177/// Storage account key list response
178#[derive(Debug, Deserialize)]
179struct StorageKeyList {
180    keys: Vec<StorageKey>,
181}
182
183/// Azure OpenAI model deployment
184#[derive(Debug, Clone, Deserialize)]
185pub struct ModelDeployment {
186    pub name: String,
187    #[serde(default)]
188    pub properties: ModelDeploymentProperties,
189    #[serde(default)]
190    pub sku: ModelDeploymentSku,
191}
192
193#[derive(Debug, Clone, Default, Deserialize)]
194pub struct ModelDeploymentProperties {
195    #[serde(default)]
196    pub model: ModelDeploymentModel,
197}
198
199#[derive(Debug, Clone, Default, Deserialize)]
200pub struct ModelDeploymentModel {
201    #[serde(default)]
202    pub name: String,
203    #[serde(default)]
204    pub version: String,
205}
206
207#[derive(Debug, Clone, Default, Deserialize)]
208pub struct ModelDeploymentSku {
209    #[serde(default)]
210    pub name: String,
211    #[serde(default)]
212    pub capacity: u32,
213}
214
215impl std::fmt::Display for ModelDeployment {
216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217        write!(
218            f,
219            "{} ({}, {})",
220            self.name, self.properties.model.name, self.sku.name
221        )
222    }
223}
224
225/// A resource's managed identity block.
226#[derive(Debug, Clone)]
227pub struct ResourceIdentity {
228    /// `SystemAssigned`, `UserAssigned`, `SystemAssigned, UserAssigned`, or `None`.
229    pub kind: String,
230    /// System-assigned principal id, when enabled.
231    pub principal_id: Option<String>,
232    /// (resource id, principal id) of attached user-assigned identities.
233    pub user_assigned: Vec<(String, String)>,
234}
235
236impl ResourceIdentity {
237    /// All principal ids this resource can act as.
238    pub fn principal_ids(&self) -> Vec<&str> {
239        let mut ids: Vec<&str> = self.principal_id.iter().map(String::as_str).collect();
240        ids.extend(self.user_assigned.iter().map(|(_, p)| p.as_str()));
241        ids
242    }
243}
244
245/// Deterministic UUID-shaped name from a string (stable role-assignment names).
246fn deterministic_uuid(input: &str) -> String {
247    let mut h1: u64 = 0xcbf29ce484222325;
248    let mut h2: u64 = 0x9e3779b97f4a7c15;
249    for b in input.as_bytes() {
250        h1 ^= u64::from(*b);
251        h1 = h1.wrapping_mul(0x100000001b3);
252        h2 = h2.rotate_left(7) ^ u64::from(*b);
253        h2 = h2.wrapping_mul(0x2545f4914f6cdd1d);
254    }
255    let bytes = [h1.to_be_bytes(), h2.to_be_bytes()].concat();
256    format!(
257        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
258        bytes[0],
259        bytes[1],
260        bytes[2],
261        bytes[3],
262        bytes[4],
263        bytes[5],
264        bytes[6],
265        bytes[7],
266        bytes[8],
267        bytes[9],
268        bytes[10],
269        bytes[11],
270        bytes[12],
271        bytes[13],
272        bytes[14],
273        bytes[15]
274    )
275}
276
277/// ARM list response envelope
278#[derive(Debug, Deserialize)]
279struct ArmListResponse<T> {
280    value: Vec<T>,
281}
282
283impl ArmClient {
284    /// Create a new ARM client using Azure CLI credentials
285    pub fn new() -> Result<Self, ClientError> {
286        let token = AzCliAuth::get_arm_token()?;
287        let http = Client::builder()
288            .timeout(std::time::Duration::from_secs(30))
289            .build()?;
290
291        Ok(Self { http, token })
292    }
293
294    /// Read a resource's managed identity block: `GET {id}?api-version=...`.
295    pub async fn get_resource_identity(
296        &self,
297        resource_id: &str,
298        api_version: &str,
299    ) -> Result<Option<ResourceIdentity>, ClientError> {
300        let url = format!("{ARM_BASE_URL}{resource_id}?api-version={api_version}");
301        let response = self
302            .http
303            .get(&url)
304            .header("Authorization", format!("Bearer {}", self.token))
305            .send()
306            .await?;
307        let status = response.status();
308        if !status.is_success() {
309            let body = response.text().await?;
310            return Err(ClientError::from_response(status.as_u16(), &body));
311        }
312        let value: serde_json::Value = response.json().await?;
313        let Some(identity) = value.get("identity") else {
314            return Ok(None);
315        };
316        let kind = identity
317            .get("type")
318            .and_then(|t| t.as_str())
319            .unwrap_or("None")
320            .to_string();
321        let principal_id = identity
322            .get("principalId")
323            .and_then(|p| p.as_str())
324            .map(str::to_string);
325        let user_assigned = identity
326            .get("userAssignedIdentities")
327            .and_then(|u| u.as_object())
328            .map(|map| {
329                map.iter()
330                    .filter_map(|(id, v)| {
331                        v.get("principalId")
332                            .and_then(|p| p.as_str())
333                            .map(|p| (id.clone(), p.to_string()))
334                    })
335                    .collect()
336            })
337            .unwrap_or_default();
338        Ok(Some(ResourceIdentity {
339            kind,
340            principal_id,
341            user_assigned,
342        }))
343    }
344
345    /// Role definition IDs assigned to `principal_id` at (or inherited by) `scope`.
346    pub async fn list_role_assignments(
347        &self,
348        scope: &str,
349        principal_id: &str,
350    ) -> Result<Vec<String>, ClientError> {
351        let url = format!(
352            "{ARM_BASE_URL}{scope}/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01&$filter=principalId%20eq%20'{principal_id}'"
353        );
354        let response = self
355            .http
356            .get(&url)
357            .header("Authorization", format!("Bearer {}", self.token))
358            .send()
359            .await?;
360        let status = response.status();
361        if !status.is_success() {
362            let body = response.text().await?;
363            return Err(ClientError::from_response(status.as_u16(), &body));
364        }
365        let value: serde_json::Value = response.json().await?;
366        Ok(value
367            .get("value")
368            .and_then(|v| v.as_array())
369            .map(|arr| {
370                arr.iter()
371                    .filter_map(|a| {
372                        a.get("properties")
373                            .and_then(|p| p.get("roleDefinitionId"))
374                            .and_then(|r| r.as_str())
375                            .map(str::to_string)
376                    })
377                    .collect()
378            })
379            .unwrap_or_default())
380    }
381
382    /// Create a role assignment for a principal at a scope.
383    pub async fn create_role_assignment(
384        &self,
385        scope: &str,
386        principal_id: &str,
387        role_definition_guid: &str,
388    ) -> Result<(), ClientError> {
389        let assignment_name =
390            deterministic_uuid(&format!("{scope}|{principal_id}|{role_definition_guid}"));
391        let url = format!(
392            "{ARM_BASE_URL}{scope}/providers/Microsoft.Authorization/roleAssignments/{assignment_name}?api-version=2022-04-01"
393        );
394        let sub = scope.split('/').nth(2).unwrap_or_default();
395        let body = serde_json::json!({
396            "properties": {
397                "roleDefinitionId": format!(
398                    "/subscriptions/{sub}/providers/Microsoft.Authorization/roleDefinitions/{role_definition_guid}"
399                ),
400                "principalId": principal_id,
401                "principalType": "ServicePrincipal"
402            }
403        });
404        let response = self
405            .http
406            .put(&url)
407            .header("Authorization", format!("Bearer {}", self.token))
408            .json(&body)
409            .send()
410            .await?;
411        let status = response.status();
412        // 409 = already exists → fine
413        if status.is_success() || status.as_u16() == 409 {
414            return Ok(());
415        }
416        let text = response.text().await?;
417        Err(ClientError::from_response(status.as_u16(), &text))
418    }
419
420    /// Enable a system-assigned managed identity on a resource (PATCH).
421    pub async fn enable_system_identity(
422        &self,
423        resource_id: &str,
424        api_version: &str,
425    ) -> Result<(), ClientError> {
426        let url = format!("{ARM_BASE_URL}{resource_id}?api-version={api_version}");
427        let response = self
428            .http
429            .patch(&url)
430            .header("Authorization", format!("Bearer {}", self.token))
431            .json(&serde_json::json!({"identity": {"type": "SystemAssigned"}}))
432            .send()
433            .await?;
434        let status = response.status();
435        if status.is_success() {
436            return Ok(());
437        }
438        let text = response.text().await?;
439        Err(ClientError::from_response(status.as_u16(), &text))
440    }
441
442    /// Find the full ARM resource id of a search service by name.
443    pub async fn find_search_service_id(&self, name: &str) -> Result<String, ClientError> {
444        for sub in self.list_subscriptions().await? {
445            for svc in self.list_search_services(&sub.subscription_id).await? {
446                if svc.name.eq_ignore_ascii_case(name) && !svc.id.is_empty() {
447                    return Ok(svc.id);
448                }
449            }
450        }
451        Err(ClientError::NotFound {
452            kind: "search service".to_string(),
453            name: name.to_string(),
454        })
455    }
456
457    /// The ARM bearer token this client authenticated with.
458    pub fn token(&self) -> &str {
459        &self.token
460    }
461
462    /// List subscriptions the user has access to
463    pub async fn list_subscriptions(&self) -> Result<Vec<Subscription>, ClientError> {
464        let url = format!("{}/subscriptions?api-version=2022-12-01", ARM_BASE_URL);
465        debug!("Listing subscriptions: {}", url);
466
467        let response = self
468            .http
469            .get(&url)
470            .header("Authorization", format!("Bearer {}", self.token))
471            .send()
472            .await?;
473
474        let status = response.status();
475        if !status.is_success() {
476            let body = response.text().await?;
477            return Err(ClientError::from_response(status.as_u16(), &body));
478        }
479
480        let result: ArmListResponse<Subscription> = response.json().await?;
481        // Only return enabled subscriptions
482        Ok(result
483            .value
484            .into_iter()
485            .filter(|s| s.state == "Enabled")
486            .collect())
487    }
488
489    /// List Azure AI Search services in a subscription
490    pub async fn list_search_services(
491        &self,
492        subscription_id: &str,
493    ) -> Result<Vec<SearchService>, ClientError> {
494        let url = format!(
495            "{}/subscriptions/{}/providers/Microsoft.Search/searchServices?api-version=2023-11-01",
496            ARM_BASE_URL, subscription_id
497        );
498        debug!("Listing search services: {}", url);
499
500        let response = self
501            .http
502            .get(&url)
503            .header("Authorization", format!("Bearer {}", self.token))
504            .send()
505            .await?;
506
507        let status = response.status();
508        if !status.is_success() {
509            let body = response.text().await?;
510            return Err(ClientError::from_response(status.as_u16(), &body));
511        }
512
513        let result: ArmListResponse<SearchService> = response.json().await?;
514        Ok(result.value)
515    }
516
517    /// Find the resource group of a search service by scanning the subscription.
518    ///
519    /// Returns the resource group name extracted from the service's ARM resource ID.
520    pub async fn find_resource_group(
521        &self,
522        subscription_id: &str,
523        service_name: &str,
524    ) -> Result<String, ClientError> {
525        let services = self.list_search_services(subscription_id).await?;
526
527        for svc in &services {
528            if svc.name.eq_ignore_ascii_case(service_name) {
529                // Parse resource group from ARM ID:
530                // /subscriptions/{sub}/resourceGroups/{rg}/providers/...
531                return parse_resource_group(&svc.id).ok_or_else(|| ClientError::Api {
532                    status: 0,
533                    message: format!("Could not parse resource group from ARM ID: {}", svc.id),
534                });
535            }
536        }
537
538        Err(ClientError::NotFound {
539            kind: "Search service".to_string(),
540            name: service_name.to_string(),
541        })
542    }
543
544    /// List Azure AI Services accounts in a subscription (filtered to kind=AIServices)
545    pub async fn list_ai_services_accounts(
546        &self,
547        subscription_id: &str,
548    ) -> Result<Vec<AiServicesAccount>, ClientError> {
549        let url = format!(
550            "{}/subscriptions/{}/providers/Microsoft.CognitiveServices/accounts?api-version=2024-10-01",
551            ARM_BASE_URL, subscription_id
552        );
553        debug!("Listing AI Services accounts: {}", url);
554
555        let response = self
556            .http
557            .get(&url)
558            .header("Authorization", format!("Bearer {}", self.token))
559            .send()
560            .await?;
561
562        let status = response.status();
563        if !status.is_success() {
564            let body = response.text().await?;
565            return Err(ClientError::from_response(status.as_u16(), &body));
566        }
567
568        let result: ArmListResponse<AiServicesAccount> = response.json().await?;
569        Ok(result
570            .value
571            .into_iter()
572            .filter(|a| a.kind.eq_ignore_ascii_case("AIServices"))
573            .collect())
574    }
575
576    /// List Microsoft Foundry projects under a specific AI Services account.
577    ///
578    /// Projects are sub-resources at:
579    /// `Microsoft.CognitiveServices/accounts/{accountName}/projects`
580    ///
581    /// The `account_id` should be the full ARM resource ID of the account,
582    /// from which we extract the resource group.
583    pub async fn list_foundry_projects(
584        &self,
585        account: &AiServicesAccount,
586        subscription_id: &str,
587    ) -> Result<Vec<FoundryProject>, ClientError> {
588        let resource_group = parse_resource_group(&account.id).ok_or_else(|| ClientError::Api {
589            status: 0,
590            message: format!("Could not parse resource group from ARM ID: {}", account.id),
591        })?;
592
593        let url = format!(
594            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.CognitiveServices/accounts/{}/projects?api-version=2025-06-01",
595            ARM_BASE_URL, subscription_id, resource_group, account.name
596        );
597        debug!("Listing Foundry projects: {}", url);
598
599        let response = self
600            .http
601            .get(&url)
602            .header("Authorization", format!("Bearer {}", self.token))
603            .send()
604            .await?;
605
606        let status = response.status();
607        if !status.is_success() {
608            let body = response.text().await?;
609            return Err(ClientError::from_response(status.as_u16(), &body));
610        }
611
612        let result: ArmListResponse<FoundryProject> = response.json().await?;
613        Ok(result.value)
614    }
615
616    /// List storage accounts in a resource group.
617    pub async fn list_storage_accounts(
618        &self,
619        subscription_id: &str,
620        resource_group: &str,
621    ) -> Result<Vec<StorageAccount>, ClientError> {
622        let url = format!(
623            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts?api-version=2023-05-01",
624            ARM_BASE_URL, subscription_id, resource_group
625        );
626        debug!("Listing storage accounts: {}", url);
627
628        let response = self
629            .http
630            .get(&url)
631            .header("Authorization", format!("Bearer {}", self.token))
632            .send()
633            .await?;
634
635        let status = response.status();
636        if !status.is_success() {
637            let body = response.text().await?;
638            return Err(ClientError::from_response(status.as_u16(), &body));
639        }
640
641        let result: ArmListResponse<StorageAccount> = response.json().await?;
642        Ok(result.value)
643    }
644
645    /// List storage accounts across a whole subscription.
646    pub async fn list_storage_accounts_subscription(
647        &self,
648        subscription_id: &str,
649    ) -> Result<Vec<StorageAccount>, ClientError> {
650        let url = format!(
651            "{}/subscriptions/{}/providers/Microsoft.Storage/storageAccounts?api-version=2023-05-01",
652            ARM_BASE_URL, subscription_id
653        );
654        debug!("Listing storage accounts (subscription-wide): {}", url);
655
656        let response = self
657            .http
658            .get(&url)
659            .header("Authorization", format!("Bearer {}", self.token))
660            .send()
661            .await?;
662
663        let status = response.status();
664        if !status.is_success() {
665            let body = response.text().await?;
666            return Err(ClientError::from_response(status.as_u16(), &body));
667        }
668
669        let result: ArmListResponse<StorageAccount> = response.json().await?;
670        Ok(result.value)
671    }
672
673    /// Whether a storage account contains a blob container with this name
674    /// (checked via ARM with the caller's CLI token — no data-plane access
675    /// or account keys involved).
676    pub async fn storage_account_has_container(
677        &self,
678        account_id: &str,
679        container: &str,
680    ) -> Result<bool, ClientError> {
681        let url = format!(
682            "{ARM_BASE_URL}{account_id}/blobServices/default/containers/{container}?api-version=2023-05-01"
683        );
684        debug!("Checking container: {}", url);
685
686        let response = self
687            .http
688            .get(&url)
689            .header("Authorization", format!("Bearer {}", self.token))
690            .send()
691            .await?;
692
693        match response.status().as_u16() {
694            200 => Ok(true),
695            404 => Ok(false),
696            status => {
697                let body = response.text().await?;
698                Err(ClientError::from_response(status, &body))
699            }
700        }
701    }
702
703    /// Find every storage account (across all visible subscriptions) that
704    /// holds a blob container named `container`. Used to auto-construct
705    /// identity-based `ResourceId=` data-source connections — the user is
706    /// already logged in via Azure CLI, so rigg discovers instead of asking.
707    /// Accounts that fail the container check (e.g. insufficient RBAC on an
708    /// unrelated subscription) are skipped, not fatal.
709    pub async fn find_storage_accounts_with_container(
710        &self,
711        container: &str,
712    ) -> Result<Vec<StorageAccount>, ClientError> {
713        let mut matches = Vec::new();
714        for sub in self.list_subscriptions().await? {
715            let accounts = match self
716                .list_storage_accounts_subscription(&sub.subscription_id)
717                .await
718            {
719                Ok(a) => a,
720                Err(e) => {
721                    debug!(
722                        "skipping subscription {} ({}): {e}",
723                        sub.display_name, sub.subscription_id
724                    );
725                    continue;
726                }
727            };
728            for account in accounts {
729                if account.id.is_empty() {
730                    continue;
731                }
732                match self
733                    .storage_account_has_container(&account.id, container)
734                    .await
735                {
736                    Ok(true) => matches.push(account),
737                    Ok(false) => {}
738                    Err(e) => debug!("skipping account {} ({e})", account.name),
739                }
740            }
741        }
742        Ok(matches)
743    }
744
745    /// Get the primary access key for a storage account.
746    pub async fn get_storage_account_key(
747        &self,
748        subscription_id: &str,
749        resource_group: &str,
750        account_name: &str,
751    ) -> Result<String, ClientError> {
752        let url = format!(
753            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/listKeys?api-version=2023-05-01",
754            ARM_BASE_URL, subscription_id, resource_group, account_name
755        );
756        debug!("Getting storage account keys: {}", url);
757
758        let response = self
759            .http
760            .post(&url)
761            .header("Authorization", format!("Bearer {}", self.token))
762            .header("Content-Length", "0")
763            .send()
764            .await?;
765
766        let status = response.status();
767        if !status.is_success() {
768            let body = response.text().await?;
769            return Err(ClientError::from_response(status.as_u16(), &body));
770        }
771
772        let key_list: StorageKeyList = response.json().await?;
773        key_list
774            .keys
775            .into_iter()
776            .next()
777            .map(|k| k.value)
778            .ok_or_else(|| ClientError::Api {
779                status: 0,
780                message: "No keys found for storage account".to_string(),
781            })
782    }
783
784    /// List model deployments for an AI Services account.
785    pub async fn list_model_deployments(
786        &self,
787        account: &AiServicesAccount,
788        subscription_id: &str,
789    ) -> Result<Vec<ModelDeployment>, ClientError> {
790        let resource_group = parse_resource_group(&account.id).ok_or_else(|| ClientError::Api {
791            status: 0,
792            message: format!("Could not parse resource group from ARM ID: {}", account.id),
793        })?;
794
795        let url = format!(
796            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.CognitiveServices/accounts/{}/deployments?api-version=2024-10-01",
797            ARM_BASE_URL, subscription_id, resource_group, account.name
798        );
799        debug!("Listing model deployments: {}", url);
800
801        let response = self
802            .http
803            .get(&url)
804            .header("Authorization", format!("Bearer {}", self.token))
805            .send()
806            .await?;
807
808        let status = response.status();
809        if !status.is_success() {
810            let body = response.text().await?;
811            return Err(ClientError::from_response(status.as_u16(), &body));
812        }
813
814        let result: ArmListResponse<ModelDeployment> = response.json().await?;
815        Ok(result.value)
816    }
817
818    /// Create a model deployment on an AI Services account.
819    pub async fn create_model_deployment(
820        &self,
821        account: &AiServicesAccount,
822        subscription_id: &str,
823        deployment_name: &str,
824        model_name: &str,
825        model_version: &str,
826    ) -> Result<(), ClientError> {
827        let resource_group = parse_resource_group(&account.id).ok_or_else(|| ClientError::Api {
828            status: 0,
829            message: format!("Could not parse resource group from ARM ID: {}", account.id),
830        })?;
831
832        let url = format!(
833            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.CognitiveServices/accounts/{}/deployments/{}?api-version=2024-10-01",
834            ARM_BASE_URL, subscription_id, resource_group, account.name, deployment_name
835        );
836        debug!("Creating model deployment: {}", url);
837
838        let body = serde_json::json!({
839            "sku": {
840                "name": "GlobalStandard",
841                "capacity": 1
842            },
843            "properties": {
844                "model": {
845                    "format": "OpenAI",
846                    "name": model_name,
847                    "version": model_version
848                }
849            }
850        });
851
852        let response = self
853            .http
854            .put(&url)
855            .header("Authorization", format!("Bearer {}", self.token))
856            .json(&body)
857            .send()
858            .await?;
859
860        let status = response.status();
861        if !status.is_success() {
862            let body = response.text().await?;
863            return Err(ClientError::from_response(status.as_u16(), &body));
864        }
865
866        Ok(())
867    }
868
869    /// Build a full connection string for a storage account.
870    pub async fn get_storage_connection_string(
871        &self,
872        subscription_id: &str,
873        resource_group: &str,
874        account_name: &str,
875    ) -> Result<String, ClientError> {
876        let key = self
877            .get_storage_account_key(subscription_id, resource_group, account_name)
878            .await?;
879
880        Ok(format!(
881            "DefaultEndpointsProtocol=https;AccountName={};AccountKey={};EndpointSuffix=core.windows.net",
882            account_name, key
883        ))
884    }
885}
886
887/// Parse resource group from an ARM resource ID.
888///
889/// ARM IDs look like: `/subscriptions/{sub}/resourceGroups/{rg}/providers/...`
890fn parse_resource_group(arm_id: &str) -> Option<String> {
891    let parts: Vec<&str> = arm_id.split('/').collect();
892    for (i, part) in parts.iter().enumerate() {
893        if part.eq_ignore_ascii_case("resourceGroups")
894            || part.eq_ignore_ascii_case("resourcegroups")
895        {
896            return parts.get(i + 1).map(|s| s.to_string());
897        }
898    }
899    None
900}
901
902#[cfg(test)]
903mod tests {
904    use super::*;
905
906    #[test]
907    fn test_parse_resource_group() {
908        let id = "/subscriptions/abc-123/resourceGroups/my-rg/providers/Microsoft.Search/searchServices/my-svc";
909        assert_eq!(parse_resource_group(id), Some("my-rg".to_string()));
910    }
911
912    #[test]
913    fn test_parse_resource_group_case_insensitive() {
914        let id = "/subscriptions/abc/resourcegroups/MyRG/providers/Something";
915        assert_eq!(parse_resource_group(id), Some("MyRG".to_string()));
916    }
917
918    #[test]
919    fn test_parse_resource_group_missing() {
920        let id = "/subscriptions/abc/providers/Something";
921        assert_eq!(parse_resource_group(id), None);
922    }
923
924    #[test]
925    fn test_ai_services_account_display() {
926        let account = AiServicesAccount {
927            name: "my-ai-service".to_string(),
928            location: "eastus".to_string(),
929            kind: "AIServices".to_string(),
930            id: String::new(),
931            properties: AiServicesAccountProperties::default(),
932        };
933        assert_eq!(format!("{}", account), "my-ai-service (eastus)");
934    }
935
936    #[test]
937    fn test_agents_endpoint_from_arm_endpoint() {
938        let account = AiServicesAccount {
939            name: "irma-prod-foundry".to_string(),
940            location: "swedencentral".to_string(),
941            kind: "AIServices".to_string(),
942            id: String::new(),
943            properties: AiServicesAccountProperties {
944                endpoint: Some("https://custom-subdomain.cognitiveservices.azure.com/".to_string()),
945            },
946        };
947        assert_eq!(
948            account.agents_endpoint(),
949            "https://custom-subdomain.services.ai.azure.com"
950        );
951    }
952
953    #[test]
954    fn test_agents_endpoint_fallback_to_name() {
955        let account = AiServicesAccount {
956            name: "irma-prod-foundry".to_string(),
957            location: "swedencentral".to_string(),
958            kind: "AIServices".to_string(),
959            id: String::new(),
960            properties: AiServicesAccountProperties::default(),
961        };
962        assert_eq!(
963            account.agents_endpoint(),
964            "https://irma-prod-foundry.services.ai.azure.com"
965        );
966    }
967
968    #[test]
969    fn test_extract_subdomain() {
970        assert_eq!(
971            extract_subdomain("https://my-svc.cognitiveservices.azure.com/"),
972            Some("my-svc")
973        );
974        assert_eq!(
975            extract_subdomain("https://custom.services.ai.azure.com"),
976            Some("custom")
977        );
978        assert_eq!(extract_subdomain("not-a-url"), None);
979    }
980
981    #[test]
982    fn test_foundry_project_display_with_display_name() {
983        let project = FoundryProject {
984            name: "my-account/my-project".to_string(),
985            location: "westus2".to_string(),
986            id: String::new(),
987            properties: FoundryProjectProperties {
988                display_name: "my-project".to_string(),
989            },
990        };
991        assert_eq!(format!("{}", project), "my-project (westus2)");
992        assert_eq!(project.display_name(), "my-project");
993    }
994
995    #[test]
996    fn test_model_deployment_display() {
997        let deployment = ModelDeployment {
998            name: "gpt-4o-mini".to_string(),
999            properties: ModelDeploymentProperties {
1000                model: ModelDeploymentModel {
1001                    name: "gpt-4o-mini".to_string(),
1002                    version: "2024-07-18".to_string(),
1003                },
1004            },
1005            sku: ModelDeploymentSku {
1006                name: "GlobalStandard".to_string(),
1007                capacity: 1,
1008            },
1009        };
1010        assert_eq!(
1011            format!("{}", deployment),
1012            "gpt-4o-mini (gpt-4o-mini, GlobalStandard)"
1013        );
1014    }
1015
1016    #[test]
1017    fn test_foundry_project_display_name_fallback() {
1018        let project = FoundryProject {
1019            name: "my-account/proj-default".to_string(),
1020            location: "swedencentral".to_string(),
1021            id: String::new(),
1022            properties: FoundryProjectProperties::default(),
1023        };
1024        assert_eq!(project.display_name(), "proj-default");
1025        assert_eq!(format!("{}", project), "proj-default (swedencentral)");
1026    }
1027}
1028
1029#[cfg(test)]
1030mod identity_tests {
1031    use super::*;
1032
1033    #[test]
1034    fn deterministic_uuid_stable_and_shaped() {
1035        let a = deterministic_uuid("scope|principal|role");
1036        let b = deterministic_uuid("scope|principal|role");
1037        let c = deterministic_uuid("scope|principal|other-role");
1038        assert_eq!(a, b);
1039        assert_ne!(a, c);
1040        assert_eq!(a.len(), 36);
1041        assert_eq!(a.chars().filter(|ch| *ch == '-').count(), 4);
1042    }
1043
1044    #[test]
1045    fn resource_identity_principal_ids() {
1046        let id = ResourceIdentity {
1047            kind: "SystemAssigned, UserAssigned".into(),
1048            principal_id: Some("sys".into()),
1049            user_assigned: vec![("id1".into(), "ua1".into())],
1050        };
1051        assert_eq!(id.principal_ids(), vec!["sys", "ua1"]);
1052    }
1053}