unifly-api 0.8.0

Async Rust client, reactive data layer, and domain model for UniFi controller APIs
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
// Legacy API HTTP client
//
// Wraps `reqwest::Client` with UniFi-specific URL construction, envelope
// unwrapping, and platform-aware path prefixing. All endpoint modules
// (devices, clients, etc.) are implemented as inherent methods via
// separate files to keep this module focused on transport mechanics.

use std::sync::{Arc, RwLock};

use reqwest::cookie::{CookieStore, Jar};
use serde::Serialize;
use serde::de::DeserializeOwned;
use tracing::{debug, trace};
use url::Url;

use crate::auth::ControllerPlatform;
use crate::error::Error;
use crate::legacy::models::LegacyResponse;
use crate::transport::TransportConfig;

/// UniFi OS wraps some errors as `{"error":{"code":N,"message":"..."}}` with HTTP 200.
#[derive(serde::Deserialize)]
struct UnifiOsError {
    error: Option<UnifiOsErrorInner>,
}

#[derive(serde::Deserialize)]
struct UnifiOsErrorInner {
    code: u16,
    message: Option<String>,
}

/// Raw HTTP client for the UniFi controller's legacy API.
///
/// Handles the `{ data: [], meta: { rc, msg } }` envelope, site-scoped
/// URL construction, and platform-aware path prefixing. All methods return
/// unwrapped `data` payloads -- the envelope is stripped before the caller
/// sees it.
pub struct LegacyClient {
    http: reqwest::Client,
    base_url: Url,
    site: String,
    platform: ControllerPlatform,
    /// CSRF token for UniFi OS. Required on all POST/PUT/DELETE requests
    /// through the `/proxy/network/` path. Captured from login response
    /// headers and rotated via `X-Updated-CSRF-Token`.
    csrf_token: RwLock<Option<String>>,
    /// Cookie jar reference for extracting session cookies (e.g. for WebSocket auth).
    cookie_jar: Option<Arc<Jar>>,
}

impl LegacyClient {
    /// Create a new legacy client from a `TransportConfig`.
    ///
    /// If the config doesn't already include a cookie jar, one is created
    /// automatically (legacy auth requires cookies). The `base_url` should be
    /// the controller root (e.g. `https://192.168.1.1` for UniFi OS or
    /// `https://controller:8443` for standalone).
    pub fn new(
        base_url: Url,
        site: String,
        platform: ControllerPlatform,
        transport: &TransportConfig,
    ) -> Result<Self, Error> {
        let config = if transport.cookie_jar.is_some() {
            transport.clone()
        } else {
            transport.clone().with_cookie_jar()
        };
        let cookie_jar = config.cookie_jar.clone();
        let http = config.build_client()?;
        Ok(Self {
            http,
            base_url,
            site,
            platform,
            csrf_token: RwLock::new(None),
            cookie_jar,
        })
    }

    /// Create a legacy client with a pre-built `reqwest::Client`.
    ///
    /// Use this when you already have a client with a session cookie in its
    /// jar (e.g. after authenticating via a shared client).
    pub fn with_client(
        http: reqwest::Client,
        base_url: Url,
        site: String,
        platform: ControllerPlatform,
    ) -> Self {
        Self {
            http,
            base_url,
            site,
            platform,
            csrf_token: RwLock::new(None),
            cookie_jar: None,
        }
    }

    /// The current site identifier.
    pub fn site(&self) -> &str {
        &self.site
    }

    /// The underlying HTTP client (for auth flows that need direct access).
    pub fn http(&self) -> &reqwest::Client {
        &self.http
    }

    /// The controller base URL.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// The detected controller platform.
    pub fn platform(&self) -> ControllerPlatform {
        self.platform
    }

    /// Extract the session cookie header value for WebSocket auth.
    ///
    /// Returns the `Cookie` header string (e.g. `"TOKEN=abc123"`) if a
    /// cookie jar is available and contains cookies for the controller URL.
    pub fn cookie_header(&self) -> Option<String> {
        let jar = self.cookie_jar.as_ref()?;
        let cookies = jar.cookies(&self.base_url)?;
        cookies.to_str().ok().map(String::from)
    }

    // ── Cookie injection (for MFA flow) ───────────────────────────────

    /// Inject a `Set-Cookie` header value into the client's cookie jar.
    ///
    /// Used by the MFA flow to inject the `UBIC_2FA` cookie before retrying
    /// login with the TOTP token.
    pub(crate) fn add_cookie(&self, set_cookie_value: &str, url: &Url) -> Result<(), Error> {
        let jar = self
            .cookie_jar
            .as_ref()
            .ok_or_else(|| Error::Authentication {
                message: "no cookie jar available for MFA flow".into(),
            })?;
        let header_value: reqwest::header::HeaderValue =
            set_cookie_value
                .parse()
                .map_err(|_| Error::Authentication {
                    message: "failed to parse MFA cookie value".into(),
                })?;
        jar.set_cookies(&mut std::iter::once(&header_value), url);
        Ok(())
    }

    // ── CSRF token management ─────────────────────────────────────────

    /// Read the current CSRF token value (for session caching).
    pub(crate) fn csrf_token_value(&self) -> Option<String> {
        self.csrf_token.read().expect("CSRF lock poisoned").clone()
    }

    /// Store a CSRF token (captured from login response headers).
    pub(crate) fn set_csrf_token(&self, token: String) {
        debug!("storing CSRF token");
        *self.csrf_token.write().expect("CSRF lock poisoned") = Some(token);
    }

    /// Update CSRF token if the response contains a rotated value.
    fn update_csrf_from_response(&self, headers: &reqwest::header::HeaderMap) {
        // UniFi OS may rotate tokens — prefer the updated one.
        let new_token = headers
            .get("X-Updated-CSRF-Token")
            .or_else(|| headers.get("x-csrf-token"))
            .and_then(|v| v.to_str().ok())
            .map(String::from);

        if let Some(token) = new_token {
            trace!("CSRF token rotated");
            *self.csrf_token.write().expect("CSRF lock poisoned") = Some(token);
        }
    }

    /// Apply the stored CSRF token to a request builder.
    fn apply_csrf(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        let guard = self.csrf_token.read().expect("CSRF lock poisoned");
        match guard.as_deref() {
            Some(token) => builder.header("X-CSRF-Token", token),
            None => builder,
        }
    }

    // ── URL builders ─────────────────────────────────────────────────

    /// Build a full URL for a controller-level API path.
    ///
    /// Applies the platform-specific legacy prefix, then appends `/api/{path}`.
    /// For example, on UniFi OS: `https://host/proxy/network/api/{path}`
    pub(crate) fn api_url(&self, path: &str) -> Url {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let full = format!("{base}{prefix}/api/{path}");
        Url::parse(&full).expect("invalid API URL")
    }

    /// Build a site-scoped URL: `{base}{prefix}/api/s/{site}/{path}`
    ///
    /// Most legacy endpoints are site-scoped: stat/device, cmd/devmgr, etc.
    pub(crate) fn site_url(&self, path: &str) -> Url {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let full = format!("{base}{prefix}/api/s/{}/{path}", self.site);
        Url::parse(&full).expect("invalid site URL")
    }

    /// Build a v2 site-scoped URL: `{base}{prefix}/v2/api/site/{site}/{path}`
    ///
    /// Used by newer endpoints (Network Application 9+) that use the v2 path
    /// format, e.g. traffic-flow-latest-statistics.
    pub(crate) fn site_url_v2(&self, path: &str) -> Url {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let full = format!("{base}{prefix}/v2/api/site/{}/{path}", self.site);
        Url::parse(&full).expect("invalid v2 site URL")
    }

    // ── Request helpers ──────────────────────────────────────────────

    /// Send a GET request and unwrap the legacy envelope.
    pub(crate) async fn get<T: DeserializeOwned>(&self, url: Url) -> Result<Vec<T>, Error> {
        debug!("GET {}", url);

        let resp = self.http.get(url).send().await.map_err(Error::Transport)?;

        self.parse_envelope(resp).await
    }

    /// Send a GET request and return the raw JSON response (no envelope unwrapping).
    ///
    /// Used for v2 API endpoints that return plain JSON instead of the
    /// legacy `{ meta, data }` envelope.
    pub(crate) async fn get_raw(&self, url: Url) -> Result<serde_json::Value, Error> {
        debug!("GET (raw) {}", url);

        let resp = self.http.get(url).send().await.map_err(Error::Transport)?;
        let status = resp.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::Authentication {
                message: "session expired or invalid credentials".into(),
            });
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::LegacyApi {
                message: format!("HTTP {status}: {}", &body[..body.len().min(200)]),
            });
        }

        let body = resp.text().await.map_err(Error::Transport)?;
        serde_json::from_str(&body).map_err(|e| Error::Deserialization {
            message: format!("{e}"),
            body,
        })
    }

    /// Send a POST request with JSON body and unwrap the legacy envelope.
    pub(crate) async fn post<T: DeserializeOwned>(
        &self,
        url: Url,
        body: &(impl Serialize + Sync),
    ) -> Result<Vec<T>, Error> {
        debug!("POST {}", url);

        let builder = self.apply_csrf(self.http.post(url).json(body));
        let resp = builder.send().await.map_err(Error::Transport)?;

        self.parse_envelope(resp).await
    }

    /// Send a PUT request with JSON body and unwrap the legacy envelope.
    #[allow(dead_code)]
    pub(crate) async fn put<T: DeserializeOwned>(
        &self,
        url: Url,
        body: &(impl Serialize + Sync),
    ) -> Result<Vec<T>, Error> {
        debug!("PUT {}", url);

        let builder = self.apply_csrf(self.http.put(url).json(body));
        let resp = builder.send().await.map_err(Error::Transport)?;

        self.parse_envelope(resp).await
    }

    /// Send a DELETE request and unwrap the legacy envelope.
    #[allow(dead_code)]
    pub(crate) async fn delete<T: DeserializeOwned>(&self, url: Url) -> Result<Vec<T>, Error> {
        debug!("DELETE {}", url);

        let builder = self.apply_csrf(self.http.delete(url));
        let resp = builder.send().await.map_err(Error::Transport)?;

        self.parse_envelope(resp).await
    }

    /// Send a raw GET to an arbitrary path (no envelope unwrapping).
    ///
    /// The `path` is appended directly after `{base}{prefix}/`.
    pub async fn raw_get(&self, path: &str) -> Result<serde_json::Value, Error> {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let url = Url::parse(&format!("{base}{prefix}/{path}")).expect("invalid raw URL");
        self.get_raw(url).await
    }

    /// Send a raw POST to an arbitrary path (no envelope unwrapping).
    pub async fn raw_post(
        &self,
        path: &str,
        body: &serde_json::Value,
    ) -> Result<serde_json::Value, Error> {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let url = Url::parse(&format!("{base}{prefix}/{path}")).expect("invalid raw URL");
        debug!("POST (raw) {}", url);

        let builder = self.apply_csrf(self.http.post(url).json(body));
        let resp = builder.send().await.map_err(Error::Transport)?;
        let status = resp.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::Authentication {
                message: "session expired or invalid credentials".into(),
            });
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::LegacyApi {
                message: format!("HTTP {status}: {}", &body[..body.len().min(200)]),
            });
        }

        let body = resp.text().await.map_err(Error::Transport)?;
        serde_json::from_str(&body).map_err(|e| Error::Deserialization {
            message: format!("{e}"),
            body,
        })
    }

    /// Send a raw PUT to an arbitrary path (no envelope unwrapping).
    pub async fn raw_put(
        &self,
        path: &str,
        body: &serde_json::Value,
    ) -> Result<serde_json::Value, Error> {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let url = Url::parse(&format!("{base}{prefix}/{path}")).expect("invalid raw URL");
        debug!("PUT (raw) {}", url);

        let builder = self.apply_csrf(self.http.put(url).json(body));
        let resp = builder.send().await.map_err(Error::Transport)?;
        let status = resp.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::Authentication {
                message: "session expired or invalid credentials".into(),
            });
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::LegacyApi {
                message: format!("HTTP {status}: {}", &body[..body.len().min(200)]),
            });
        }

        let body = resp.text().await.map_err(Error::Transport)?;
        serde_json::from_str(&body).map_err(|e| Error::Deserialization {
            message: format!("{e}"),
            body,
        })
    }

    /// Send a raw DELETE to an arbitrary path (no envelope unwrapping).
    pub async fn raw_delete(&self, path: &str) -> Result<(), Error> {
        let prefix = self.platform.legacy_prefix().unwrap_or("");
        let base = self.base_url.as_str().trim_end_matches('/');
        let prefix = prefix.trim_end_matches('/');
        let url = Url::parse(&format!("{base}{prefix}/{path}")).expect("invalid raw URL");
        debug!("DELETE (raw) {}", url);

        let builder = self.apply_csrf(self.http.delete(url));
        let resp = builder.send().await.map_err(Error::Transport)?;
        let status = resp.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::Authentication {
                message: "session expired or invalid credentials".into(),
            });
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::LegacyApi {
                message: format!("HTTP {status}: {}", &body[..body.len().min(200)]),
            });
        }

        Ok(())
    }

    /// Parse the `{ meta, data }` envelope, returning `data` on success
    /// or an `Error::LegacyApi` if `meta.rc != "ok"`.
    ///
    /// Also handles UniFi OS error responses that use a different shape:
    /// `{"error": {"code": 403, "message": "..."}}` (returned with HTTP 200).
    async fn parse_envelope<T: DeserializeOwned>(
        &self,
        resp: reqwest::Response,
    ) -> Result<Vec<T>, Error> {
        let status = resp.status();

        // Capture any CSRF token rotation before consuming the response.
        self.update_csrf_from_response(resp.headers());

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::Authentication {
                message: "session expired or invalid credentials".into(),
            });
        }

        if status == reqwest::StatusCode::FORBIDDEN {
            return Err(Error::LegacyApi {
                message: "insufficient permissions (HTTP 403)".into(),
            });
        }

        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::LegacyApi {
                message: format!("HTTP {status}: {}", &body[..body.len().min(200)]),
            });
        }

        let body = resp.text().await.map_err(Error::Transport)?;

        // UniFi OS sometimes returns `{"error":{"code":N,"message":"..."}}` with HTTP 200.
        if let Ok(wrapper) = serde_json::from_str::<UnifiOsError>(&body)
            && let Some(err) = wrapper.error
        {
            let msg = err.message.unwrap_or_default();
            return Err(if err.code == 401 {
                Error::Authentication { message: msg }
            } else {
                Error::LegacyApi {
                    message: format!("UniFi OS error {}: {msg}", err.code),
                }
            });
        }

        let envelope: LegacyResponse<T> = serde_json::from_str(&body).map_err(|e| {
            let preview = &body[..body.len().min(200)];
            Error::Deserialization {
                message: format!("{e} (body preview: {preview:?})"),
                body: body.clone(),
            }
        })?;

        match envelope.meta.rc.as_str() {
            "ok" => Ok(envelope.data),
            _ => Err(Error::LegacyApi {
                message: envelope
                    .meta
                    .msg
                    .unwrap_or_else(|| format!("rc={}", envelope.meta.rc)),
            }),
        }
    }
}