Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-daemon/src/daemon/http/server.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! HTTP server for the daemon protocol.
3
//!
4
//! The listeners and the auth layer are `super-engine-daemon`'s; this names
5
//! Super STT's router, secrets and consent dialog to them.
6
//!
7
//! Binds `$XDG_RUNTIME_DIR/voice/super-voice-http.sock` (override via
8
//! `SUPER_VOICE_HTTP_SOCKET`). All endpoints are served under the `/v1`
9
//! URL prefix — route definitions in `build_router` are written as
10
//! bare paths (`/ping`, `/auth/request`, …) and the prefix is applied
11
//! via a single `Router::nest("/v1", …)` at the bottom of the file.
12
//!
13
//! v1 endpoint set (wire paths):
14
//!
15
//! - `POST /v1/auth/request`              — interactive consent → mints a session token
16
//! - `GET  /v1/auth/status`               — probe token validity (no consent UI)
17
//! - `GET  /v1/ping`                      — liveness (any authenticated token)
18
//! - `GET  /v1/status`                    — current model + device (`status` scope)
19
//! - `POST /v1/stt/transcribe`                — start a daemon-mic recording
20
//! - `POST /v1/stt/transcribe/stop`           — stop an in-flight daemon-mic recording
21
//! - `GET  /v1/events?topics=…`           — Server-Sent Events stream (per-topic scope)
22
//! - `GET  /v1/update`                    — last self-update check result (`settings` scope)
23
//! - `POST /v1/update/check`              — force an immediate self-update check (`settings` scope)
24
//! - `GET/POST /v1/update_check_enabled`  — periodic self-update check on/off (`settings` scope)
25
//! - `GET/POST /v1/update_beta_optin`     — self-update prerelease opt-in (`settings` scope)
26
//! - … plus the settings configuration surface (see [`build_router`])
27
//!
28
//! Authentication:
29
//! - The daemon uses `SO_PEERCRED` on each connection to get the peer PID
30
//!   and resolves `/proc/<pid>/exe`. That path is shown in the consent
31
//!   popup so the user knows which binary is asking.
32
//! - On Allow, the daemon mints a 32-byte hex session token and stores it
33
//!   keyed in an in-memory `TokenStore`. The token has a 30-day expiry.
34
//! - Every endpoint other than `/v1/auth/request` requires
35
//!   `Authorization: Bearer <token>`. Missing/invalid → 401 with
36
//!   `{ status: "error", message: "invalid_session", data: { reason } }`.
37
//! - The popup is the `super-voice-consent` helper binary, spawned as a
38
//!   subprocess. It writes "allow" / "deny" / "dismissed" to stdout.
39
//! - Set `SUPER_VOICE_AUTO_APPROVE=1` in the daemon environment to skip
40
//!   the popup entirely (intended for tests / CI).
41
42
use crate::daemon::http::state::AppState;
43
use crate::daemon::types::SuperSTTDaemon;
44
use anyhow::Result;
45
use std::sync::Arc;
46
use super_engine_daemon::auth::consent::ConsentDialog;
47
use super_engine_daemon::auth::{Auth, AuthConfig};
48
use super_engine_daemon::http::server::{Listeners, serve};
49
use super_engine_daemon::instance::InstanceLock;
50
use super_voice_shared::SUPER_VOICE;
51
use tokio::sync::broadcast;
52
53
/// Env var that, when set to "1", bypasses the consent popup entirely
54
/// and auto-approves every `auth_request`. Intended for tests / CI only.
55
pub const AUTO_APPROVE_ENV: &str = "SUPER_VOICE_AUTO_APPROVE";
56
57
/// Spawn the HTTP server on the Unix socket `instance` locks, and on the
58
/// loopback TCP port when `[http.tcp]` turns it on. Returns once the listeners
59
/// are bound; the actual accept loop runs in a background task, which holds
60
/// `instance` until it has removed the socket on shutdown.
61
///
62
/// Returns the [`JoinHandle`](tokio::task::JoinHandle) of the spawned
63
/// accept-loop task so the caller can supervise it: if the task ends before
64
/// `shutdown_tx` fires (panic, fatal `accept()` error, etc.), the caller should
65
/// treat the daemon as unreachable and exit. See
66
/// [`daemon_main::run`](crate::daemon_main::run) for the supervision
67
/// `tokio::select!`.
68
///
69
/// # Errors
70
/// Returns an error if the socket can't be created or bound.
71
200
pub async fn start_http_server(
72
200
    daemon: Arc<SuperSTTDaemon>,
73
200
    instance: InstanceLock,
74
200
    shutdown_tx: broadcast::Sender<()>,
75
200
) -> Result<tokio::task::JoinHandle<()>> {
76
200
    let tcp = daemon.config.read().await.http.tcp.clone();
77
200
    let resource_manager = Arc::clone(&daemon.resource_manager);
78
200
    let listeners = Listeners {
79
200
        instance,
80
200
        tcp: tcp.bind_addr(),
81
200
        allowed_origins: tcp.allowed_origins.clone(),
82
200
    };
83
200
    let config = AuthConfig {
84
200
        dialog: ConsentDialog {
85
200
            product: &SUPER_VOICE,
86
200
            describe_scopes: super_voice_shared::consent::permissions_for_scopes,
87
200
        },
88
200
        secrets: daemon.secrets.clone(),
89
200
        resource_manager: Arc::clone(&resource_manager),
90
200
        allowed_origins: tcp.allowed_origins,
91
200
    };
92
200
    serve(listeners, resource_manager, shutdown_tx, move || {
93
200
        let auth = Auth::load(config);
94
200
        Ok(crate::daemon::http::v1::router(AppState::new(daemon, auth)))
95
200
    })
96
200
    .await
97
200
}
98
99
#[cfg(test)]
100
mod tests {
101
    /// The variable the tests and CI set is the one the shared auth code
102
    /// reads.
103
    #[test]
104
1
    fn auto_approve_env_is_the_one_the_engine_reads() {
105
1
        assert_eq!(
106
1
            super::AUTO_APPROVE_ENV,
107
1
            super::SUPER_VOICE.env(super_engine_daemon::auth::AUTO_APPROVE)
108
        );
109
1
    }
110
}