1use 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
12pub struct ArmClient {
14 http: Client,
15 token: String,
16}
17
18#[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#[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#[derive(Debug, Clone)]
62pub struct DiscoveredService {
63 pub name: String,
64 pub subscription_id: String,
65 pub location: String,
66}
67
68#[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 #[serde(default)]
85 pub endpoint: Option<String>,
86}
87
88impl AiServicesAccount {
89 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
104fn 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#[derive(Debug, Clone, Deserialize)]
120pub struct FoundryProject {
121 #[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 pub fn display_name(&self) -> &str {
141 if !self.properties.display_name.is_empty() {
142 &self.properties.display_name
143 } else {
144 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#[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#[derive(Debug, Clone, Deserialize)]
173struct StorageKey {
174 value: String,
175}
176
177#[derive(Debug, Deserialize)]
179struct StorageKeyList {
180 keys: Vec<StorageKey>,
181}
182
183#[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#[derive(Debug, Clone)]
227pub struct ResourceIdentity {
228 pub kind: String,
230 pub principal_id: Option<String>,
232 pub user_assigned: Vec<(String, String)>,
234}
235
236impl ResourceIdentity {
237 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
245fn 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#[derive(Debug, Deserialize)]
279struct ArmListResponse<T> {
280 value: Vec<T>,
281}
282
283impl ArmClient {
284 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 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 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 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 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 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 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 pub fn token(&self) -> &str {
459 &self.token
460 }
461
462 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 Ok(result
483 .value
484 .into_iter()
485 .filter(|s| s.state == "Enabled")
486 .collect())
487 }
488
489 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 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 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 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 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 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 pub async fn get_storage_account_key(
647 &self,
648 subscription_id: &str,
649 resource_group: &str,
650 account_name: &str,
651 ) -> Result<String, ClientError> {
652 let url = format!(
653 "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/listKeys?api-version=2023-05-01",
654 ARM_BASE_URL, subscription_id, resource_group, account_name
655 );
656 debug!("Getting storage account keys: {}", url);
657
658 let response = self
659 .http
660 .post(&url)
661 .header("Authorization", format!("Bearer {}", self.token))
662 .header("Content-Length", "0")
663 .send()
664 .await?;
665
666 let status = response.status();
667 if !status.is_success() {
668 let body = response.text().await?;
669 return Err(ClientError::from_response(status.as_u16(), &body));
670 }
671
672 let key_list: StorageKeyList = response.json().await?;
673 key_list
674 .keys
675 .into_iter()
676 .next()
677 .map(|k| k.value)
678 .ok_or_else(|| ClientError::Api {
679 status: 0,
680 message: "No keys found for storage account".to_string(),
681 })
682 }
683
684 pub async fn list_model_deployments(
686 &self,
687 account: &AiServicesAccount,
688 subscription_id: &str,
689 ) -> Result<Vec<ModelDeployment>, ClientError> {
690 let resource_group = parse_resource_group(&account.id).ok_or_else(|| ClientError::Api {
691 status: 0,
692 message: format!("Could not parse resource group from ARM ID: {}", account.id),
693 })?;
694
695 let url = format!(
696 "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.CognitiveServices/accounts/{}/deployments?api-version=2024-10-01",
697 ARM_BASE_URL, subscription_id, resource_group, account.name
698 );
699 debug!("Listing model deployments: {}", url);
700
701 let response = self
702 .http
703 .get(&url)
704 .header("Authorization", format!("Bearer {}", self.token))
705 .send()
706 .await?;
707
708 let status = response.status();
709 if !status.is_success() {
710 let body = response.text().await?;
711 return Err(ClientError::from_response(status.as_u16(), &body));
712 }
713
714 let result: ArmListResponse<ModelDeployment> = response.json().await?;
715 Ok(result.value)
716 }
717
718 pub async fn create_model_deployment(
720 &self,
721 account: &AiServicesAccount,
722 subscription_id: &str,
723 deployment_name: &str,
724 model_name: &str,
725 model_version: &str,
726 ) -> Result<(), ClientError> {
727 let resource_group = parse_resource_group(&account.id).ok_or_else(|| ClientError::Api {
728 status: 0,
729 message: format!("Could not parse resource group from ARM ID: {}", account.id),
730 })?;
731
732 let url = format!(
733 "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.CognitiveServices/accounts/{}/deployments/{}?api-version=2024-10-01",
734 ARM_BASE_URL, subscription_id, resource_group, account.name, deployment_name
735 );
736 debug!("Creating model deployment: {}", url);
737
738 let body = serde_json::json!({
739 "sku": {
740 "name": "GlobalStandard",
741 "capacity": 1
742 },
743 "properties": {
744 "model": {
745 "format": "OpenAI",
746 "name": model_name,
747 "version": model_version
748 }
749 }
750 });
751
752 let response = self
753 .http
754 .put(&url)
755 .header("Authorization", format!("Bearer {}", self.token))
756 .json(&body)
757 .send()
758 .await?;
759
760 let status = response.status();
761 if !status.is_success() {
762 let body = response.text().await?;
763 return Err(ClientError::from_response(status.as_u16(), &body));
764 }
765
766 Ok(())
767 }
768
769 pub async fn get_storage_connection_string(
771 &self,
772 subscription_id: &str,
773 resource_group: &str,
774 account_name: &str,
775 ) -> Result<String, ClientError> {
776 let key = self
777 .get_storage_account_key(subscription_id, resource_group, account_name)
778 .await?;
779
780 Ok(format!(
781 "DefaultEndpointsProtocol=https;AccountName={};AccountKey={};EndpointSuffix=core.windows.net",
782 account_name, key
783 ))
784 }
785}
786
787fn parse_resource_group(arm_id: &str) -> Option<String> {
791 let parts: Vec<&str> = arm_id.split('/').collect();
792 for (i, part) in parts.iter().enumerate() {
793 if part.eq_ignore_ascii_case("resourceGroups")
794 || part.eq_ignore_ascii_case("resourcegroups")
795 {
796 return parts.get(i + 1).map(|s| s.to_string());
797 }
798 }
799 None
800}
801
802#[cfg(test)]
803mod tests {
804 use super::*;
805
806 #[test]
807 fn test_parse_resource_group() {
808 let id = "/subscriptions/abc-123/resourceGroups/my-rg/providers/Microsoft.Search/searchServices/my-svc";
809 assert_eq!(parse_resource_group(id), Some("my-rg".to_string()));
810 }
811
812 #[test]
813 fn test_parse_resource_group_case_insensitive() {
814 let id = "/subscriptions/abc/resourcegroups/MyRG/providers/Something";
815 assert_eq!(parse_resource_group(id), Some("MyRG".to_string()));
816 }
817
818 #[test]
819 fn test_parse_resource_group_missing() {
820 let id = "/subscriptions/abc/providers/Something";
821 assert_eq!(parse_resource_group(id), None);
822 }
823
824 #[test]
825 fn test_ai_services_account_display() {
826 let account = AiServicesAccount {
827 name: "my-ai-service".to_string(),
828 location: "eastus".to_string(),
829 kind: "AIServices".to_string(),
830 id: String::new(),
831 properties: AiServicesAccountProperties::default(),
832 };
833 assert_eq!(format!("{}", account), "my-ai-service (eastus)");
834 }
835
836 #[test]
837 fn test_agents_endpoint_from_arm_endpoint() {
838 let account = AiServicesAccount {
839 name: "irma-prod-foundry".to_string(),
840 location: "swedencentral".to_string(),
841 kind: "AIServices".to_string(),
842 id: String::new(),
843 properties: AiServicesAccountProperties {
844 endpoint: Some("https://custom-subdomain.cognitiveservices.azure.com/".to_string()),
845 },
846 };
847 assert_eq!(
848 account.agents_endpoint(),
849 "https://custom-subdomain.services.ai.azure.com"
850 );
851 }
852
853 #[test]
854 fn test_agents_endpoint_fallback_to_name() {
855 let account = AiServicesAccount {
856 name: "irma-prod-foundry".to_string(),
857 location: "swedencentral".to_string(),
858 kind: "AIServices".to_string(),
859 id: String::new(),
860 properties: AiServicesAccountProperties::default(),
861 };
862 assert_eq!(
863 account.agents_endpoint(),
864 "https://irma-prod-foundry.services.ai.azure.com"
865 );
866 }
867
868 #[test]
869 fn test_extract_subdomain() {
870 assert_eq!(
871 extract_subdomain("https://my-svc.cognitiveservices.azure.com/"),
872 Some("my-svc")
873 );
874 assert_eq!(
875 extract_subdomain("https://custom.services.ai.azure.com"),
876 Some("custom")
877 );
878 assert_eq!(extract_subdomain("not-a-url"), None);
879 }
880
881 #[test]
882 fn test_foundry_project_display_with_display_name() {
883 let project = FoundryProject {
884 name: "my-account/my-project".to_string(),
885 location: "westus2".to_string(),
886 id: String::new(),
887 properties: FoundryProjectProperties {
888 display_name: "my-project".to_string(),
889 },
890 };
891 assert_eq!(format!("{}", project), "my-project (westus2)");
892 assert_eq!(project.display_name(), "my-project");
893 }
894
895 #[test]
896 fn test_model_deployment_display() {
897 let deployment = ModelDeployment {
898 name: "gpt-4o-mini".to_string(),
899 properties: ModelDeploymentProperties {
900 model: ModelDeploymentModel {
901 name: "gpt-4o-mini".to_string(),
902 version: "2024-07-18".to_string(),
903 },
904 },
905 sku: ModelDeploymentSku {
906 name: "GlobalStandard".to_string(),
907 capacity: 1,
908 },
909 };
910 assert_eq!(
911 format!("{}", deployment),
912 "gpt-4o-mini (gpt-4o-mini, GlobalStandard)"
913 );
914 }
915
916 #[test]
917 fn test_foundry_project_display_name_fallback() {
918 let project = FoundryProject {
919 name: "my-account/proj-default".to_string(),
920 location: "swedencentral".to_string(),
921 id: String::new(),
922 properties: FoundryProjectProperties::default(),
923 };
924 assert_eq!(project.display_name(), "proj-default");
925 assert_eq!(format!("{}", project), "proj-default (swedencentral)");
926 }
927}
928
929#[cfg(test)]
930mod identity_tests {
931 use super::*;
932
933 #[test]
934 fn deterministic_uuid_stable_and_shaped() {
935 let a = deterministic_uuid("scope|principal|role");
936 let b = deterministic_uuid("scope|principal|role");
937 let c = deterministic_uuid("scope|principal|other-role");
938 assert_eq!(a, b);
939 assert_ne!(a, c);
940 assert_eq!(a.len(), 36);
941 assert_eq!(a.chars().filter(|ch| *ch == '-').count(), 4);
942 }
943
944 #[test]
945 fn resource_identity_principal_ids() {
946 let id = ResourceIdentity {
947 kind: "SystemAssigned, UserAssigned".into(),
948 principal_id: Some("sys".into()),
949 user_assigned: vec![("id1".into(), "ua1".into())],
950 };
951 assert_eq!(id.principal_ids(), vec!["sys", "ua1"]);
952 }
953}