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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
#![allow(clippy::unwrap_used)]

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use secrecy::SecretString;
use serde_json::json;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{Mutex, Notify};
use tokio::time::timeout;
use url::Url;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use unifly_api::{AuthCredentials, Controller, ControllerConfig, CoreError, TlsVerification};

const LEGACY_SITE_ID: &str = "site-001";
const LEGACY_SITE_NAME: &str = "default";
const LEGACY_SITE_LABEL: &str = "Main Site";
const API_KEY_SITE_ID: &str = "550e8400-e29b-41d4-a716-446655440000";

fn base_config(
    url: Url,
    auth: AuthCredentials,
    site: &str,
    websocket_enabled: bool,
) -> ControllerConfig {
    ControllerConfig {
        url,
        auth,
        site: site.to_owned(),
        tls: TlsVerification::DangerAcceptInvalid,
        timeout: Duration::from_secs(5),
        refresh_interval_secs: 0,
        websocket_enabled,
        polling_interval_secs: 1,
        totp_token: None,
        profile_name: None,
        no_session_cache: true,
    }
}

fn secret(value: &str) -> SecretString {
    SecretString::from(value.to_owned())
}

fn empty_legacy_envelope() -> serde_json::Value {
    legacy_envelope(&json!([]))
}

fn legacy_envelope(data: &serde_json::Value) -> serde_json::Value {
    json!({
        "meta": { "rc": "ok" },
        "data": data,
    })
}

fn legacy_site_envelope() -> serde_json::Value {
    json!({
        "meta": { "rc": "ok" },
        "data": [{
            "_id": LEGACY_SITE_ID,
            "name": LEGACY_SITE_NAME,
            "desc": LEGACY_SITE_LABEL,
        }],
    })
}

fn empty_integration_page(limit: i32) -> serde_json::Value {
    json!({
        "offset": 0,
        "limit": limit,
        "count": 0,
        "totalCount": 0,
        "data": [],
    })
}

async fn mock_legacy_connect(server: &MockServer, site_envelope: serde_json::Value) {
    mock_legacy_connect_with_events(server, site_envelope, empty_legacy_envelope()).await;
}

async fn mock_legacy_connect_with_events(
    server: &MockServer,
    site_envelope: serde_json::Value,
    event_envelope: serde_json::Value,
) {
    Mock::given(method("GET"))
        .and(path("/api/auth/login"))
        .respond_with(ResponseTemplate::new(404))
        .mount(server)
        .await;

    Mock::given(method("POST"))
        .and(path("/api/login"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Set-Cookie", "unifly_session=legacy-cookie; Path=/")
                .set_body_json(json!({})),
        )
        .mount(server)
        .await;

    Mock::given(method("POST"))
        .and(path("/api/logout"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
        .mount(server)
        .await;

    for route in ["/api/s/default/stat/device", "/api/s/default/stat/sta"] {
        Mock::given(method("GET"))
            .and(path(route))
            .respond_with(ResponseTemplate::new(200).set_body_json(empty_legacy_envelope()))
            .mount(server)
            .await;
    }

    Mock::given(method("GET"))
        .and(path("/api/s/default/stat/event"))
        .respond_with(ResponseTemplate::new(200).set_body_json(event_envelope))
        .mount(server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/self/sites"))
        .respond_with(ResponseTemplate::new(200).set_body_json(site_envelope))
        .mount(server)
        .await;
}

async fn mock_api_key_connect(server: &MockServer, site_id: &str) {
    Mock::given(method("GET"))
        .and(path("/api/auth/login"))
        .respond_with(ResponseTemplate::new(404))
        .mount(server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/login"))
        .respond_with(ResponseTemplate::new(404))
        .mount(server)
        .await;

    for route in [
        format!("/integration/v1/sites/{site_id}/devices"),
        format!("/integration/v1/sites/{site_id}/clients"),
        format!("/integration/v1/sites/{site_id}/networks"),
        format!("/integration/v1/sites/{site_id}/wifi/broadcasts"),
        format!("/integration/v1/sites/{site_id}/firewall/policies"),
        format!("/integration/v1/sites/{site_id}/firewall/zones"),
        format!("/integration/v1/sites/{site_id}/acl-rules"),
        format!("/integration/v1/sites/{site_id}/dns/policies"),
        format!("/integration/v1/sites/{site_id}/vouchers"),
        format!("/integration/v1/sites/{site_id}/traffic-matching-lists"),
    ] {
        Mock::given(method("GET"))
            .and(path(route))
            .respond_with(ResponseTemplate::new(200).set_body_json(empty_integration_page(200)))
            .mount(server)
            .await;
    }

    Mock::given(method("GET"))
        .and(path("/integration/v1/sites"))
        .respond_with(ResponseTemplate::new(200).set_body_json(empty_integration_page(50)))
        .mount(server)
        .await;
}

#[tokio::test]
async fn legacy_only_site_listing_remains_available() {
    let server = MockServer::start().await;
    mock_legacy_connect(&server, legacy_site_envelope()).await;

    let controller = Controller::new(base_config(
        Url::parse(&server.uri()).unwrap(),
        AuthCredentials::Credentials {
            username: "admin".into(),
            password: secret("password"),
        },
        LEGACY_SITE_NAME,
        false,
    ));

    controller.connect().await.unwrap();

    assert!(controller.has_legacy_access().await);
    assert!(!controller.has_integration_access().await);
    assert!(controller.take_warnings().await.is_empty());

    let sites = controller.sites_snapshot();
    assert_eq!(sites.len(), 1);
    assert_eq!(sites[0].internal_name, LEGACY_SITE_NAME);
    assert_eq!(sites[0].name, LEGACY_SITE_LABEL);

    controller.disconnect().await;
}

#[tokio::test]
async fn legacy_mode_rejects_integration_only_surfaces_clearly() {
    let server = MockServer::start().await;
    mock_legacy_connect(&server, empty_legacy_envelope()).await;

    let controller = Controller::new(base_config(
        Url::parse(&server.uri()).unwrap(),
        AuthCredentials::Credentials {
            username: "admin".into(),
            password: secret("password"),
        },
        LEGACY_SITE_NAME,
        false,
    ));

    controller.connect().await.unwrap();

    let err = controller.list_countries().await.unwrap_err();
    match err {
        CoreError::Unsupported {
            operation,
            required,
        } => {
            assert_eq!(operation, "list_countries");
            assert_eq!(required, "Integration API");
        }
        other => panic!("expected Unsupported error, got {other:?}"),
    }

    controller.disconnect().await;
}

#[tokio::test]
async fn api_key_mode_has_legacy_and_integration_access() {
    let server = MockServer::start().await;
    mock_api_key_connect(&server, API_KEY_SITE_ID).await;

    let controller = Controller::new(base_config(
        Url::parse(&server.uri()).unwrap(),
        AuthCredentials::ApiKey(secret("api-key")),
        API_KEY_SITE_ID,
        false,
    ));

    controller.connect().await.unwrap();

    assert!(controller.has_legacy_access().await);
    assert!(controller.has_integration_access().await);

    controller.disconnect().await;
}

#[tokio::test]
async fn websocket_enabled_for_events_watch_path() {
    let server = spawn_ws_probe_server().await;
    let controller = Controller::new(base_config(
        server.base_url.clone(),
        AuthCredentials::Credentials {
            username: "admin".into(),
            password: secret("password"),
        },
        LEGACY_SITE_NAME,
        true,
    ));

    controller.connect().await.unwrap();

    timeout(Duration::from_secs(5), server.probe.notified())
        .await
        .expect("websocket handshake did not arrive in time");

    let path = server.handshake_path.lock().await.clone().unwrap();
    let cookie = server.cookie_header.lock().await.clone().unwrap();

    assert_eq!(path, "/wss/s/default/events");
    assert!(
        cookie.contains("unifly_session=legacy-cookie"),
        "expected websocket cookie header to carry the legacy session, got: {cookie}"
    );

    controller.disconnect().await;
}

#[tokio::test]
async fn full_refresh_does_not_rebroadcast_duplicate_legacy_events() {
    let server = MockServer::start().await;
    mock_legacy_connect_with_events(
        &server,
        legacy_site_envelope(),
        legacy_envelope(&json!([{
            "_id": "evt-1",
            "key": "EVT_TEST",
            "msg": "Switch lost contact",
            "datetime": "2025-01-01T00:00:00Z",
            "subsystem": "device",
            "site_id": LEGACY_SITE_ID,
        }])),
    )
    .await;

    let controller = Controller::new(base_config(
        Url::parse(&server.uri()).unwrap(),
        AuthCredentials::Credentials {
            username: "admin".into(),
            password: secret("password"),
        },
        LEGACY_SITE_NAME,
        false,
    ));
    let mut events = controller.events();

    controller.connect().await.unwrap();

    let first_event = timeout(Duration::from_secs(1), events.recv())
        .await
        .expect("initial refresh should broadcast legacy events")
        .expect("broadcast channel should stay open");
    assert_eq!(first_event.message, "Switch lost contact");
    assert_eq!(controller.events_snapshot().len(), 1);

    controller.full_refresh().await.unwrap();

    assert!(
        timeout(Duration::from_millis(250), events.recv())
            .await
            .is_err(),
        "refresh should not rebroadcast already-seen legacy events"
    );
    assert_eq!(controller.events_snapshot().len(), 1);

    controller.disconnect().await;
}

struct WsProbeServer {
    base_url: Url,
    probe: Arc<Notify>,
    handshake_path: Arc<Mutex<Option<String>>>,
    cookie_header: Arc<Mutex<Option<String>>>,
}

async fn spawn_ws_probe_server() -> WsProbeServer {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let base_url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
    let probe = Arc::new(Notify::new());
    let handshake_path = Arc::new(Mutex::new(None));
    let cookie_header = Arc::new(Mutex::new(None));

    let probe_task = Arc::clone(&probe);
    let path_task = Arc::clone(&handshake_path);
    let cookie_task = Arc::clone(&cookie_header);

    tokio::spawn(async move {
        while let Ok((stream, _)) = listener.accept().await {
            let probe = Arc::clone(&probe_task);
            let handshake_path = Arc::clone(&path_task);
            let cookie_header = Arc::clone(&cookie_task);

            tokio::spawn(async move {
                let _ = handle_connection(stream, probe, handshake_path, cookie_header).await;
            });
        }
    });

    WsProbeServer {
        base_url,
        probe,
        handshake_path,
        cookie_header,
    }
}

struct HttpRequest {
    method: String,
    path: String,
    headers: HashMap<String, String>,
}

#[allow(clippy::too_many_lines)]
async fn handle_connection(
    mut stream: TcpStream,
    probe: Arc<Notify>,
    handshake_path: Arc<Mutex<Option<String>>>,
    cookie_header: Arc<Mutex<Option<String>>>,
) -> std::io::Result<()> {
    let Ok(Some(request)) = read_request(&mut stream).await else {
        return Ok(());
    };

    if request.method == "GET" && request.path == "/api/auth/login" {
        write_http_response(&mut stream, 404, &[], b"not found").await?;
        return Ok(());
    }

    if request.method == "GET" && request.path == "/api/login" {
        write_http_response(&mut stream, 200, &[], b"{}").await?;
        return Ok(());
    }

    if request.method == "POST" && request.path == "/api/login" {
        write_http_response(
            &mut stream,
            200,
            &[("Set-Cookie", "unifly_session=legacy-cookie; Path=/")],
            b"{}",
        )
        .await?;
        return Ok(());
    }

    if request.method == "POST" && request.path == "/api/logout" {
        write_http_response(&mut stream, 200, &[], b"{}").await?;
        return Ok(());
    }

    if request.method == "GET" && request.path.starts_with("/api/s/default/stat/device") {
        write_http_response(
            &mut stream,
            200,
            &[("Content-Type", "application/json")],
            br#"{"meta":{"rc":"ok"},"data":[]}"#,
        )
        .await?;
        return Ok(());
    }

    if request.method == "GET" && request.path.starts_with("/api/s/default/stat/sta") {
        write_http_response(
            &mut stream,
            200,
            &[("Content-Type", "application/json")],
            br#"{"meta":{"rc":"ok"},"data":[]}"#,
        )
        .await?;
        return Ok(());
    }

    if request.method == "GET" && request.path.starts_with("/api/s/default/stat/event") {
        write_http_response(
            &mut stream,
            200,
            &[("Content-Type", "application/json")],
            br#"{"meta":{"rc":"ok"},"data":[]}"#,
        )
        .await?;
        return Ok(());
    }

    if request.method == "GET" && request.path == "/api/self/sites" {
        write_http_response(
            &mut stream,
            200,
            &[("Content-Type", "application/json")],
            br#"{"meta":{"rc":"ok"},"data":[]}"#,
        )
        .await?;
        return Ok(());
    }

    if request.method == "GET"
        && request.path == "/wss/s/default/events"
        && request
            .headers
            .get("upgrade")
            .is_some_and(|value| value.eq_ignore_ascii_case("websocket"))
        && let Some(key) = request.headers.get("sec-websocket-key")
    {
        let accept = tokio_tungstenite::tungstenite::handshake::derive_accept_key(key.as_bytes());
        let response = format!(
            "HTTP/1.1 101 Switching Protocols\r\n\
                 Connection: Upgrade\r\n\
                 Upgrade: websocket\r\n\
                 Sec-WebSocket-Accept: {accept}\r\n\r\n"
        );
        stream.write_all(response.as_bytes()).await?;
        stream.flush().await?;

        *handshake_path.lock().await = Some(request.path.clone());
        *cookie_header.lock().await = request.headers.get("cookie").cloned();
        probe.notify_one();

        let mut scratch = [0u8; 1024];
        loop {
            match stream.read(&mut scratch).await {
                Ok(0) | Err(_) => break,
                Ok(_) => {}
            }
        }
        return Ok(());
    }

    write_http_response(&mut stream, 404, &[], b"not found").await
}

async fn write_http_response(
    stream: &mut TcpStream,
    status: u16,
    headers: &[(&str, &str)],
    body: &[u8],
) -> std::io::Result<()> {
    let reason = match status {
        404 => "Not Found",
        101 => "Switching Protocols",
        _ => "OK",
    };

    let mut response = format!(
        "HTTP/1.1 {status} {reason}\r\nConnection: close\r\nContent-Length: {}\r\n",
        body.len()
    );
    for (name, value) in headers {
        response.push_str(name);
        response.push_str(": ");
        response.push_str(value);
        response.push_str("\r\n");
    }
    response.push_str("\r\n");

    stream.write_all(response.as_bytes()).await?;
    if !body.is_empty() {
        stream.write_all(body).await?;
    }
    stream.flush().await?;
    let _ = stream.shutdown().await;
    Ok(())
}

async fn read_request(stream: &mut TcpStream) -> std::io::Result<Option<HttpRequest>> {
    let mut buf = Vec::new();
    let mut scratch = [0u8; 1024];

    let header_end = loop {
        let read = stream.read(&mut scratch).await?;
        if read == 0 {
            return Ok(None);
        }
        buf.extend_from_slice(&scratch[..read]);
        if let Some(pos) = find_header_end(&buf) {
            break pos;
        }
    };

    let header_text = std::str::from_utf8(&buf[..header_end]).map_err(std::io::Error::other)?;
    let mut lines = header_text.split("\r\n");
    let request_line = lines
        .next()
        .ok_or_else(|| std::io::Error::other("missing request line"))?;
    let mut request_parts = request_line.split_whitespace();
    let method = request_parts
        .next()
        .ok_or_else(|| std::io::Error::other("missing request method"))?
        .to_owned();
    let path = request_parts
        .next()
        .ok_or_else(|| std::io::Error::other("missing request path"))?
        .to_owned();

    let mut headers = HashMap::new();
    for line in lines {
        if let Some((name, value)) = line.split_once(':') {
            headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_owned());
        }
    }

    let content_length = headers
        .get("content-length")
        .and_then(|value| value.parse::<usize>().ok())
        .unwrap_or(0);
    let body_start = header_end + 4;
    while buf.len() < body_start + content_length {
        let read = stream.read(&mut scratch).await?;
        if read == 0 {
            break;
        }
        buf.extend_from_slice(&scratch[..read]);
    }

    Ok(Some(HttpRequest {
        method,
        path,
        headers,
    }))
}

fn find_header_end(buf: &[u8]) -> Option<usize> {
    buf.windows(4).position(|window| window == b"\r\n\r\n")
}