rigg-client 1.4.3

Azure AI Search and Microsoft Foundry REST API client and authentication for rigg
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Client error types

use thiserror::Error;

use crate::auth::AuthError;

/// Azure Search client errors
#[derive(Debug, Error)]
pub enum ClientError {
    // NOTE: `{0}` embeds the cause's Display in this variant's own message,
    // so we deliberately do NOT also mark it `#[from]` (which would make
    // thiserror implement `source()` to return the same value). Doing both
    // renders the cause twice in an anyhow chain (`{:#}` walks both the
    // Display text and the `source()` chain). Conversion via `?` is instead
    // provided by the manual `impl From<...>` below, which is functionally
    // identical to `#[from]` except it does not wire up `source()`.
    #[error("Authentication error: {0}")]
    Auth(AuthError),

    // Unlike Auth/Json, reqwest errors carry deeper causes in their own
    // source chain (TLS `UnknownIssuer`, connect-refused detail, ...), so
    // this variant keeps a `#[source]` (without `#[from]`) and does NOT
    // embed `{0}` in its message. anyhow's `{:#}` then renders
    // `HTTP request failed: <reqwest display>: <deeper causes>` — prefix
    // plus the full chain, each segment exactly once.
    #[error("HTTP request failed")]
    Request(#[source] reqwest::Error),

    #[error("API error ({status}): {message}")]
    Api { status: u16, message: String },

    #[error("Access denied (403 Forbidden): {service}")]
    Forbidden {
        service: String,
        message: String,
        body: String,
    },

    #[error("Resource not found: {kind} '{name}'")]
    NotFound { kind: String, name: String },

    #[error("Resource already exists: {kind} '{name}'")]
    AlreadyExists { kind: String, name: String },

    #[error("Invalid response: {0}")]
    InvalidResponse(String),

    #[error("Rate limited, retry after {retry_after} seconds")]
    RateLimited { retry_after: u64 },

    #[error("Service unavailable: {0}")]
    ServiceUnavailable(String),

    #[error("JSON error: {0}")]
    Json(serde_json::Error),

    #[error("Local agent error: {0}")]
    LocalAgent(String),
}

// Manual `From` impls replacing `#[from]` for the variants above — see the
// comments on `ClientError::Auth` and `ClientError::Request` for why. These
// preserve `?`-based conversion exactly as `#[from]` would, while letting
// each variant choose independently whether the cause lives in its Display
// (`Auth`, `Json`) or in `source()` (`Request`) — never both, which is what
// duplicated the cause when rendering anyhow chains.
impl From<AuthError> for ClientError {
    fn from(err: AuthError) -> Self {
        ClientError::Auth(err)
    }
}

impl From<reqwest::Error> for ClientError {
    fn from(err: reqwest::Error) -> Self {
        ClientError::Request(err)
    }
}

impl From<serde_json::Error> for ClientError {
    fn from(err: serde_json::Error) -> Self {
        ClientError::Json(err)
    }
}

impl ClientError {
    /// Create a local agent error
    pub fn local_agent(msg: impl Into<String>) -> Self {
        Self::LocalAgent(msg.into())
    }
}

impl ClientError {
    /// Create an API error from HTTP status, response body, and request URL
    pub fn from_response(status: u16, body: &str) -> Self {
        Self::from_response_with_url(status, body, None)
    }

    /// Create an API error with the originating URL for richer diagnostics
    pub fn from_response_with_url(status: u16, body: &str, url: Option<&str>) -> Self {
        // Extract message from Azure error format
        let parsed_message = serde_json::from_str::<serde_json::Value>(body)
            .ok()
            .and_then(|json| {
                json.get("error")
                    .and_then(|e| e.get("message"))
                    .and_then(|m| m.as_str())
                    .map(String::from)
            });

        // For 403, create a Forbidden error with actionable context
        if status == 403 {
            let service = url
                .and_then(|u| u.strip_prefix("https://").and_then(|s| s.split('/').next()))
                .unwrap_or("unknown service")
                .to_string();
            let message = parsed_message.unwrap_or_default();
            return Self::Forbidden {
                service,
                message,
                body: body.to_string(),
            };
        }

        if let Some(message) = parsed_message {
            return Self::Api { status, message };
        }

        // Provide a human-readable fallback when the body is empty
        let message = if body.trim().is_empty() {
            format!("HTTP {} with no error details from the server", status)
        } else {
            body.to_string()
        };

        Self::Api { status, message }
    }

    /// Check if this error is retryable
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            ClientError::RateLimited { .. } | ClientError::ServiceUnavailable(_)
        )
    }

    /// Get suggested action for this error
    pub fn suggestion(&self) -> &'static str {
        match self {
            ClientError::Auth(AuthError::NotLoggedIn) => {
                "Run 'az login' to authenticate with Azure CLI"
            }
            ClientError::Auth(AuthError::AzCliNotFound) => {
                "Install Azure CLI: https://docs.microsoft.com/cli/azure/install-azure-cli"
            }
            ClientError::Auth(AuthError::MissingEnvVar(_)) => {
                "Set AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables"
            }
            ClientError::Forbidden { .. } => {
                "Access denied. The three most common causes are:\n\n\
                 1. RBAC is not enabled on the data plane (most likely)\n\
                 \x20  Azure AI Search uses API keys by default. To use Entra ID\n\
                 \x20  authentication (which rigg uses), enable RBAC:\n\
                 \x20  Portal: Settings > Keys > select \"Both\" or \"Role-based access control\"\n\
                 \x20  CLI:    az search service update --name <name> --resource-group <rg> --auth-options aadOrApiKey\n\n\
                 2. Missing RBAC role assignment\n\
                 \x20  Assign roles on the search service resource:\n\
                 \x20  az role assignment create --assignee <you> --role \"Search Service Contributor\" --scope <resource-id>\n\
                 \x20  az role assignment create --assignee <you> --role \"Search Index Data Contributor\" --scope <resource-id>\n\
                 \x20  Role assignments can take up to 10 minutes to propagate.\n\n\
                 3. IP firewall blocking your request\n\
                 \x20  If the service has network restrictions, add your IP under Networking > Firewalls.\n\n\
                 See: https://learn.microsoft.com/en-us/azure/search/search-security-enable-roles"
            }
            ClientError::NotFound { .. } => {
                "Verify the resource name and that you have access to it"
            }
            ClientError::AlreadyExists { .. } => {
                "Use a different name or delete the existing resource first"
            }
            ClientError::Request(e) => {
                if has_certificate_error(e) {
                    "TLS certificate verification failed.\n\
                     The remote server's certificate was not trusted. This typically happens on\n\
                     corporate networks that use TLS inspection with a custom CA certificate.\n\n\
                     Fix: Install the corporate root CA certificate into your operating system's\n\
                     certificate store:\n\
                       macOS:   Add to Keychain Access > System > Certificates\n\
                       Linux:   Copy to /usr/local/share/ca-certificates/ and run update-ca-certificates\n\
                       Windows: Import via certmgr.msc > Trusted Root Certification Authorities"
                } else if e.is_connect() {
                    "Could not connect to the service endpoint.\n\
                     Possible causes:\n\
                     - The endpoint URL in rigg.toml may be incorrect (re-run 'rigg init' to rediscover)\n\
                     - The service may be behind a private endpoint or VNet\n\
                     - A firewall or DNS issue may be blocking the connection"
                } else if e.is_timeout() {
                    "The request timed out. The service may be unavailable or unreachable."
                } else {
                    "The HTTP request failed. Check network connectivity and the endpoint URL in rigg.toml."
                }
            }
            ClientError::RateLimited { .. } => "Wait and retry the operation",
            ClientError::ServiceUnavailable(_) => {
                "The Azure Search service may be temporarily unavailable. Try again later."
            }
            ClientError::LocalAgent(_) => {
                "Check that the AI provider is installed and configured. Run 'rigg ai init' to reconfigure."
            }
            _ => "Check the error message for details",
        }
    }

    /// Get the raw response body (for error log details)
    pub fn raw_body(&self) -> Option<&str> {
        match self {
            ClientError::Forbidden { body, .. } => Some(body),
            ClientError::Api { message, .. } => Some(message),
            ClientError::ServiceUnavailable(body) => Some(body),
            _ => None,
        }
    }
}

/// Check if a reqwest error is caused by a TLS certificate verification failure
fn has_certificate_error(err: &reqwest::Error) -> bool {
    use std::error::Error;
    let mut source = err.source();
    while let Some(cause) = source {
        let msg = cause.to_string();
        if msg.contains("certificate") || msg.contains("UnknownIssuer") {
            return true;
        }
        source = cause.source();
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_from_response_azure_error_format() {
        let body = r#"{"error": {"message": "Index not found", "code": "ResourceNotFound"}}"#;
        let err = ClientError::from_response(404, body);
        match err {
            ClientError::Api { status, message } => {
                assert_eq!(status, 404);
                assert_eq!(message, "Index not found");
            }
            _ => panic!("Expected Api error"),
        }
    }

    #[test]
    fn test_from_response_plain_text() {
        let body = "Something went wrong";
        let err = ClientError::from_response(500, body);
        match err {
            ClientError::Api { status, message } => {
                assert_eq!(status, 500);
                assert_eq!(message, "Something went wrong");
            }
            _ => panic!("Expected Api error"),
        }
    }

    #[test]
    fn test_from_response_403_creates_forbidden() {
        let body = r#"{"detail": "forbidden"}"#;
        let err = ClientError::from_response(403, body);
        match err {
            ClientError::Forbidden {
                service,
                message,
                body: raw,
            } => {
                assert_eq!(service, "unknown service");
                assert!(message.is_empty()); // no error.message key in body
                assert_eq!(raw, body);
            }
            _ => panic!("Expected Forbidden error, got {:?}", err),
        }
    }

    #[test]
    fn test_from_response_with_url_403_extracts_service() {
        let body = r#"{"error": {"message": "Access denied"}}"#;
        let err = ClientError::from_response_with_url(
            403,
            body,
            Some("https://irma-prod-aisearch.search.windows.net/indexes?api-version=2024-07-01"),
        );
        match err {
            ClientError::Forbidden {
                service,
                message,
                body: _,
            } => {
                assert_eq!(service, "irma-prod-aisearch.search.windows.net");
                assert_eq!(message, "Access denied");
            }
            _ => panic!("Expected Forbidden error, got {:?}", err),
        }
    }

    #[test]
    fn test_from_response_with_url_403_empty_body() {
        let err = ClientError::from_response_with_url(
            403,
            "",
            Some("https://my-svc.search.windows.net/indexes?api-version=2024-07-01"),
        );
        match err {
            ClientError::Forbidden {
                service,
                message,
                body,
            } => {
                assert_eq!(service, "my-svc.search.windows.net");
                assert!(message.is_empty());
                assert!(body.is_empty());
            }
            _ => panic!("Expected Forbidden error, got {:?}", err),
        }
    }

    #[test]
    fn test_from_response_empty_body_fallback() {
        let err = ClientError::from_response(500, "  ");
        match err {
            ClientError::Api { status, message } => {
                assert_eq!(status, 500);
                assert!(message.contains("HTTP 500"));
                assert!(message.contains("no error details"));
            }
            _ => panic!("Expected Api error"),
        }
    }

    #[test]
    fn test_suggestion_forbidden() {
        let err = ClientError::Forbidden {
            service: "my-svc.search.windows.net".to_string(),
            message: "".to_string(),
            body: "".to_string(),
        };
        let suggestion = err.suggestion();
        assert!(suggestion.contains("RBAC is not enabled"));
        assert!(suggestion.contains("Search Service Contributor"));
        assert!(suggestion.contains("Search Index Data Contributor"));
        assert!(suggestion.contains("aadOrApiKey"));
        assert!(suggestion.contains("IP firewall"));
    }

    #[test]
    fn test_raw_body_forbidden() {
        let err = ClientError::Forbidden {
            service: "svc".to_string(),
            message: "".to_string(),
            body: "raw error body".to_string(),
        };
        assert_eq!(err.raw_body(), Some("raw error body"));
    }

    #[test]
    fn test_raw_body_api() {
        let err = ClientError::Api {
            status: 400,
            message: "bad request".to_string(),
        };
        assert_eq!(err.raw_body(), Some("bad request"));
    }

    #[test]
    fn test_raw_body_not_found_returns_none() {
        let err = ClientError::NotFound {
            kind: "Index".to_string(),
            name: "x".to_string(),
        };
        assert_eq!(err.raw_body(), None);
    }

    #[test]
    fn test_forbidden_display() {
        let err = ClientError::Forbidden {
            service: "my-svc.search.windows.net".to_string(),
            message: "".to_string(),
            body: "".to_string(),
        };
        let display = format!("{}", err);
        assert!(display.contains("403 Forbidden"));
        assert!(display.contains("my-svc.search.windows.net"));
    }

    #[test]
    fn test_is_retryable_rate_limited() {
        let err = ClientError::RateLimited { retry_after: 30 };
        assert!(err.is_retryable());
    }

    #[test]
    fn test_is_retryable_service_unavailable() {
        let err = ClientError::ServiceUnavailable("down".to_string());
        assert!(err.is_retryable());
    }

    #[test]
    fn test_is_not_retryable_api_error() {
        let err = ClientError::Api {
            status: 400,
            message: "bad request".to_string(),
        };
        assert!(!err.is_retryable());
    }

    #[test]
    fn test_is_not_retryable_not_found() {
        let err = ClientError::NotFound {
            kind: "Index".to_string(),
            name: "missing".to_string(),
        };
        assert!(!err.is_retryable());
    }

    #[test]
    fn test_suggestion_not_logged_in() {
        let err = ClientError::Auth(AuthError::NotLoggedIn);
        assert!(err.suggestion().contains("az login"));
    }

    #[test]
    fn test_suggestion_cli_not_found() {
        let err = ClientError::Auth(AuthError::AzCliNotFound);
        assert!(err.suggestion().contains("Install"));
    }

    #[test]
    fn test_suggestion_not_found() {
        let err = ClientError::NotFound {
            kind: "Index".to_string(),
            name: "x".to_string(),
        };
        assert!(err.suggestion().contains("Verify"));
    }

    #[test]
    fn test_suggestion_rate_limited() {
        let err = ClientError::RateLimited { retry_after: 60 };
        assert!(err.suggestion().contains("retry"));
    }

    #[test]
    fn test_has_certificate_error_with_cert_message() {
        // Test the helper function directly with string matching logic
        let check =
            |msg: &str| -> bool { msg.contains("certificate") || msg.contains("UnknownIssuer") };
        assert!(check("invalid peer certificate: UnknownIssuer"));
        assert!(check("certificate verify failed"));
        assert!(check("self signed certificate in certificate chain"));
        assert!(!check("connection refused"));
        assert!(!check("timeout"));
    }

    #[test]
    fn test_suggestion_for_generic_request_error() {
        // Verify that non-cert request errors still get the generic message
        // We can't easily construct a reqwest::Error, but we can verify
        // the suggestion arm logic: if not cert, not connect, not timeout → generic
        let suggestion = "The HTTP request failed. Check network connectivity and the endpoint URL in rigg.toml.";
        assert!(suggestion.contains("HTTP request failed"));
    }

    #[test]
    fn auth_error_chain_renders_cause_exactly_once() {
        let client_err = ClientError::from(AuthError::TokenError("boom".to_string()));
        let chained = anyhow::Error::from(client_err).context("failed to list remote data-sources");
        let rendered = format!("{chained:#}");
        assert_eq!(
            rendered.matches("boom").count(),
            1,
            "cause must appear exactly once: {rendered}"
        );
        assert!(rendered.contains("Authentication error"), "{rendered}");
        assert!(
            rendered.contains("failed to list remote data-sources"),
            "{rendered}"
        );
    }

    #[test]
    fn request_error_chain_keeps_deep_causes_and_renders_each_once() {
        // A cheaply-constructible reqwest error with a real deeper cause:
        // building a request from an unparseable URL yields a "builder error"
        // whose source() is the underlying url::ParseError.
        let reqwest_err = reqwest::Client::new()
            .get("not-a-valid-url")
            .build()
            .unwrap_err();
        let reqwest_display = reqwest_err.to_string();
        let client_err = ClientError::from(reqwest_err);
        let chained = anyhow::Error::from(client_err).context("failed to list remote indexes");
        let rendered = format!("{chained:#}");
        assert_eq!(
            rendered.matches("HTTP request failed").count(),
            1,
            "prefix must appear exactly once: {rendered}"
        );
        assert_eq!(
            rendered.matches(reqwest_display.as_str()).count(),
            1,
            "reqwest display must appear exactly once: {rendered}"
        );
        // The deeper cause (url::ParseError) must still surface via source().
        assert!(
            rendered.contains("relative URL without a base"),
            "deep cause must not be dropped: {rendered}"
        );
    }
}