Skip to main content

vifu_server/
lib.rs

1pub mod api;
2pub mod auth;
3pub mod comparisons;
4pub mod config;
5pub mod console;
6pub mod db;
7pub mod error;
8mod gateway_identity;
9pub mod models;
10pub mod monitor;
11mod openclaw_device;
12pub mod relay;
13pub mod runtime_extensions;
14mod telemetry;
15mod trace_redaction;
16pub mod websocket;
17
18use std::future::Future;
19use std::sync::Arc;
20use std::time::Duration;
21
22use axum::extract::DefaultBodyLimit;
23use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
24use axum::http::{HeaderName, Method};
25use axum::routing::{get, patch, post, put};
26use axum::Router;
27use base64::Engine;
28use config::Config;
29use error::ApiError;
30use relay::RelayHub;
31use sha2::Digest;
32use sqlx::PgPool;
33use tokio::net::TcpListener;
34use tower_http::catch_panic::CatchPanicLayer;
35use tower_http::cors::{Any, CorsLayer};
36use tower_http::limit::RequestBodyLimitLayer;
37use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
38use tower_http::trace::TraceLayer;
39use tracing::info;
40
41#[derive(Clone)]
42pub struct AppState {
43    pub config: Arc<Config>,
44    pub auth: auth::ApplicationAuth,
45    pub pool: db::Storage,
46    pub relay: RelayHub,
47    pub monitor: monitor::ServerMonitorHub,
48    pub server_endpoint: Option<Arc<ServerEndpointIdentity>>,
49}
50
51#[derive(Debug)]
52pub struct LocalBootstrapApp {
53    pub project_id: uuid::Uuid,
54    pub app_id: String,
55    pub project_slug: String,
56    pub project_name: String,
57    pub deployment_id: uuid::Uuid,
58    pub deployment: String,
59    pub created: bool,
60}
61
62#[derive(Clone, Debug)]
63pub struct ServerEndpointIdentity {
64    pub server_url: String,
65    pub certificate_der_base64: Option<String>,
66    pub certificate_sha256: Option<String>,
67}
68
69impl ServerEndpointIdentity {
70    pub fn certificate_der(&self) -> Result<Option<Vec<u8>>, String> {
71        self.certificate_der_base64
72            .as_deref()
73            .map(|encoded| {
74                base64::engine::general_purpose::STANDARD
75                    .decode(encoded)
76                    .map_err(|error| format!("server certificate DER is invalid: {error}"))
77            })
78            .transpose()
79    }
80
81    pub fn gateway_pairing_uri(&self, authorization_token: &str) -> Result<String, String> {
82        let authorization_token = authorization_token.trim();
83        if !authorization_token.starts_with("vifu_ge_")
84            || authorization_token.len() != "vifu_ge_".len() + 64
85            || !authorization_token["vifu_ge_".len()..]
86                .chars()
87                .all(|character| character.is_ascii_hexdigit())
88        {
89            return Err("Gateway authorization token is invalid".to_string());
90        }
91        let mut pairing = reqwest::Url::parse("vifu://gateway/enroll")
92            .map_err(|error| format!("Gateway pairing URI is invalid: {error}"))?;
93        {
94            let mut query = pairing.query_pairs_mut();
95            query
96                .append_pair("server", &self.server_url)
97                .append_pair("token", authorization_token);
98            if let (Some(certificate), Some(fingerprint)) = (
99                self.certificate_der_base64.as_deref(),
100                self.certificate_sha256.as_deref(),
101            ) {
102                query
103                    .append_pair("certificate", certificate)
104                    .append_pair("fingerprint", fingerprint);
105            }
106        }
107        Ok(pairing.to_string())
108    }
109
110    pub fn gateway_pairing_terminal_qr(&self, authorization_token: &str) -> Result<String, String> {
111        let uri = self.gateway_pairing_web_uri(authorization_token)?;
112        self.terminal_qr(&uri)
113    }
114
115    pub fn gateway_pairing_direct_terminal_qr(
116        &self,
117        authorization_token: &str,
118    ) -> Result<String, String> {
119        let uri = self.gateway_pairing_compact_uri(authorization_token)?;
120        self.terminal_qr(&uri)
121    }
122
123    fn gateway_pairing_compact_uri(&self, authorization_token: &str) -> Result<String, String> {
124        let full_uri = self.gateway_pairing_uri(authorization_token)?;
125        let mut uri = reqwest::Url::parse(&full_uri)
126            .map_err(|error| format!("Gateway pairing URI is invalid: {error}"))?;
127        if self.certificate_der_base64.is_some() && self.certificate_sha256.is_some() {
128            let pairs = uri
129                .query_pairs()
130                .filter(|(key, _)| key != "certificate")
131                .map(|(key, value)| (key.into_owned(), value.into_owned()))
132                .collect::<Vec<_>>();
133            uri.query_pairs_mut().clear().extend_pairs(pairs);
134        }
135        Ok(uri.to_string())
136    }
137
138    fn terminal_qr(&self, uri: &str) -> Result<String, String> {
139        let code = qrcode::QrCode::with_error_correction_level(uri.as_bytes(), qrcode::EcLevel::L)
140            .map_err(|error| format!("Gateway pairing QR code could not be generated: {error}"))?;
141        Ok(compact_terminal_qr(&code))
142    }
143
144    pub fn gateway_pairing_web_uri(&self, authorization_token: &str) -> Result<String, String> {
145        let compact_uri = self.gateway_pairing_compact_uri(authorization_token)?;
146        let uri = reqwest::Url::parse(&compact_uri)
147            .map_err(|error| format!("Gateway pairing URI is invalid: {error}"))?;
148        let query = uri
149            .query()
150            .ok_or_else(|| "Gateway pairing URI has no payload".to_string())?;
151        Ok(format!("https://vifu.ai/pair#{query}"))
152    }
153}
154
155fn compact_terminal_qr(code: &qrcode::QrCode) -> String {
156    const QUIET_ZONE: usize = 4;
157    let width = code.width();
158    let padded_width = width + QUIET_ZONE * 2;
159    let padded_height = width + QUIET_ZONE * 2;
160    let is_dark = |x: usize, y: usize| {
161        x >= QUIET_ZONE
162            && y >= QUIET_ZONE
163            && x < width + QUIET_ZONE
164            && y < width + QUIET_ZONE
165            && code[(x - QUIET_ZONE, y - QUIET_ZONE)] == qrcode::types::Color::Dark
166    };
167    let mut output = String::new();
168    for y in (0..padded_height).step_by(2) {
169        for x in 0..padded_width {
170            output.push(match (is_dark(x, y), is_dark(x, y + 1)) {
171                (false, false) => ' ',
172                (true, false) => '▀',
173                (false, true) => '▄',
174                (true, true) => '█',
175            });
176        }
177        output.push('\n');
178    }
179    output
180}
181
182pub async fn connect(config: Config) -> Result<AppState, ApiError> {
183    let pool = db::connect(&config.database_url, config.database_max_connections)
184        .await
185        .map_err(|error| diagnose_startup_error("connect", error))?;
186    db::migrate(&pool)
187        .await
188        .map_err(|error| diagnose_startup_error("migrate", error))?;
189    db::protect_sqlite_files(&config.database_url)?;
190    db::mark_agent_gateway_sessions_disconnected(&pool)
191        .await
192        .map_err(|error| diagnose_startup_error("mark gateway sessions disconnected", error))?;
193    let mut state = state_with_storage(config, pool);
194    state.server_endpoint = load_server_endpoint_identity(&state.config)?.map(Arc::new);
195    Ok(state)
196}
197
198/// Ensures that a local Vifu installation has an App for its initial UI state.
199///
200/// An App is created only when the Server has no Apps. The preferred App is
201/// used solely to migrate an App created by the older Guest bootstrap flow;
202/// otherwise existing Apps are returned without changing them.
203pub async fn ensure_local_bootstrap_app(
204    state: &AppState,
205    preferred_app_id: Option<&str>,
206) -> Result<LocalBootstrapApp, ApiError> {
207    let projects = db::list_projects(&state.pool).await?;
208    let preferred_project_id = preferred_app_id
209        .and_then(|app_id| {
210            projects
211                .iter()
212                .find(|project| project.project.app_id == app_id)
213        })
214        .map(|project| project.project.id);
215    let selected_id = preferred_project_id
216        .or_else(|| {
217            projects
218                .iter()
219                .find(|project| project.project.name == "Local app")
220                .map(|project| project.project.id)
221        })
222        .or_else(|| projects.first().map(|project| project.project.id));
223    let (project, created) = match selected_id {
224        Some(project_id) => {
225            if preferred_project_id == Some(project_id) {
226                db::promote_guest_project(&state.pool, project_id).await?;
227            }
228            (db::get_project(&state.pool, project_id).await?, false)
229        }
230        None => (
231            db::create_project(
232                &state.pool,
233                db::NewProject {
234                    id: uuid::Uuid::new_v4(),
235                    owner_user_id: None,
236                    slug: "local-app",
237                    name: "Local app",
238                    description: Some("Default App for this Vifu installation"),
239                    gateway_id: "",
240                    binding_ids: &[],
241                },
242            )
243            .await?,
244            true,
245        ),
246    };
247    let deployment = db::list_runtime_deployments(&state.pool, project.project.id)
248        .await?
249        .into_iter()
250        .find(|deployment| deployment.is_primary)
251        .ok_or_else(|| ApiError::Conflict("the local App has no primary deployment".to_string()))?;
252    Ok(LocalBootstrapApp {
253        project_id: project.project.id,
254        app_id: project.project.app_id,
255        project_slug: project.project.slug,
256        project_name: project.project.name,
257        deployment_id: deployment.id,
258        deployment: deployment.name,
259        created,
260    })
261}
262
263fn diagnose_startup_error(stage: &str, error: ApiError) -> ApiError {
264    if std::env::var_os("VIFU_SERVER_DIAGNOSTICS").is_some() {
265        eprintln!("vifu server startup failed during {stage}: {error:?}");
266    }
267    error
268}
269
270pub async fn serve<F>(config: Config, shutdown: F) -> Result<(), String>
271where
272    F: Future<Output = ()> + Send + 'static,
273{
274    let state = connect(config).await.map_err(|error| error.to_string())?;
275    serve_state(state, shutdown).await
276}
277
278pub async fn serve_state<F>(state: AppState, shutdown: F) -> Result<(), String>
279where
280    F: Future<Output = ()> + Send + 'static,
281{
282    let addr = state.config.addr;
283    let Some(server_tls) = state.config.tls.clone() else {
284        let listener = TcpListener::bind(addr)
285            .await
286            .map_err(|error| format!("could not bind {addr}: {error}"))?;
287        info!(%addr, "vifu server listening");
288        return axum::serve(
289            listener,
290            app(state).into_make_service_with_connect_info::<std::net::SocketAddr>(),
291        )
292        .with_graceful_shutdown(shutdown)
293        .await
294        .map_err(|error| format!("http server failed: {error}"));
295    };
296    let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(
297        &server_tls.certificate_path,
298        &server_tls.private_key_path,
299    )
300    .await
301    .map_err(|error| format!("server TLS certificate could not be loaded: {error}"))?;
302    let handle = axum_server::Handle::new();
303    let mut server = Box::pin(
304        axum_server::bind_rustls(addr, tls)
305            .handle(handle.clone())
306            .serve(app(state).into_make_service_with_connect_info::<std::net::SocketAddr>()),
307    );
308    info!(%addr, "vifu server listening with TLS");
309    tokio::select! {
310        result = &mut server => result.map_err(|error| format!("HTTPS server failed: {error}")),
311        () = shutdown => {
312            handle.graceful_shutdown(Some(Duration::from_secs(5)));
313            server
314                .await
315                .map_err(|error| format!("HTTPS server failed during shutdown: {error}"))
316        }
317    }
318}
319
320pub fn state(config: Config, pool: PgPool) -> AppState {
321    state_with_storage(config, db::Storage::postgres(pool))
322}
323
324pub fn state_with_storage(config: Config, pool: db::Storage) -> AppState {
325    let auth = auth::ApplicationAuth::from_config(&config);
326    state_with_storage_and_auth(config, pool, auth)
327}
328
329pub fn state_with_storage_and_auth(
330    config: Config,
331    pool: db::Storage,
332    auth: auth::ApplicationAuth,
333) -> AppState {
334    let queue_capacity = config.queue_capacity;
335    let server_endpoint = config.server_url.as_ref().map(|server_url| {
336        Arc::new(ServerEndpointIdentity {
337            server_url: server_url.clone(),
338            certificate_der_base64: None,
339            certificate_sha256: None,
340        })
341    });
342    AppState {
343        config: Arc::new(config),
344        auth,
345        pool,
346        relay: RelayHub::new(queue_capacity),
347        monitor: monitor::ServerMonitorHub::new(queue_capacity),
348        server_endpoint,
349    }
350}
351
352fn load_server_endpoint_identity(
353    config: &Config,
354) -> Result<Option<ServerEndpointIdentity>, ApiError> {
355    let Some(server_url) = config.server_url.as_ref() else {
356        return Ok(None);
357    };
358    let Some(server_tls) = config.tls.as_ref() else {
359        return Ok(Some(ServerEndpointIdentity {
360            server_url: server_url.clone(),
361            certificate_der_base64: None,
362            certificate_sha256: None,
363        }));
364    };
365    let der = if server_tls.certificate_path.is_file() && server_tls.private_key_path.is_file() {
366        use rustls_pki_types::pem::PemObject;
367
368        let certificate =
369            rustls_pki_types::CertificateDer::from_pem_file(&server_tls.certificate_path).map_err(
370                |error| ApiError::Invalid(format!("server certificate could not be read: {error}")),
371            )?;
372        let der = certificate.as_ref().to_vec();
373        let encoded = base64::engine::general_purpose::STANDARD.encode(&der);
374        let sidecar_matches = std::fs::read_to_string(&server_tls.certificate_der_path)
375            .is_ok_and(|stored| stored.trim() == encoded);
376        if !sidecar_matches {
377            vifu_gateway::config::write_private_file(&server_tls.certificate_der_path, &encoded)
378                .map_err(ApiError::Invalid)?;
379        }
380        der
381    } else {
382        let url = reqwest::Url::parse(server_url)
383            .map_err(|error| ApiError::Invalid(format!("server URL is invalid: {error}")))?;
384        let host = url
385            .host_str()
386            .ok_or_else(|| ApiError::Invalid("server URL needs a host".to_string()))?;
387        let rcgen::CertifiedKey { cert, signing_key } =
388            rcgen::generate_simple_self_signed(vec![host.to_string()]).map_err(|error| {
389                ApiError::Invalid(format!(
390                    "server certificate could not be generated: {error}"
391                ))
392            })?;
393        vifu_gateway::config::write_private_file(&server_tls.certificate_path, &cert.pem())
394            .map_err(ApiError::Invalid)?;
395        vifu_gateway::config::write_private_file(
396            &server_tls.private_key_path,
397            &signing_key.serialize_pem(),
398        )
399        .map_err(ApiError::Invalid)?;
400        let der = cert.der().to_vec();
401        vifu_gateway::config::write_private_file(
402            &server_tls.certificate_der_path,
403            &base64::engine::general_purpose::STANDARD.encode(&der),
404        )
405        .map_err(ApiError::Invalid)?;
406        der
407    };
408    let digest = sha2::Sha256::digest(&der);
409    Ok(Some(ServerEndpointIdentity {
410        server_url: server_url.clone(),
411        certificate_der_base64: Some(base64::engine::general_purpose::STANDARD.encode(&der)),
412        certificate_sha256: Some(format!("sha256:{}", hex_digest(&digest))),
413    }))
414}
415
416fn hex_digest(bytes: &[u8]) -> String {
417    use std::fmt::Write;
418    let mut output = String::with_capacity(bytes.len() * 2);
419    for byte in bytes {
420        let _ = write!(&mut output, "{byte:02x}");
421    }
422    output
423}
424
425pub fn app(state: AppState) -> Router {
426    let request_id_header = HeaderName::from_static("x-request-id");
427    let cors = CorsLayer::new()
428        .allow_origin(Any)
429        .allow_headers([
430            AUTHORIZATION,
431            CONTENT_TYPE,
432            HeaderName::from_static("last-event-id"),
433        ])
434        .expose_headers([HeaderName::from_static("x-vifu-invocation-id")])
435        .allow_methods([
436            Method::GET,
437            Method::POST,
438            Method::PUT,
439            Method::PATCH,
440            Method::DELETE,
441            Method::OPTIONS,
442        ]);
443
444    Router::new()
445        .route("/health", get(api::health))
446        .route(
447            "/api/runtime/{*path}",
448            get(console::proxy_runtime_request)
449                .post(console::proxy_runtime_request)
450                .put(console::proxy_runtime_request)
451                .patch(console::proxy_runtime_request)
452                .delete(console::proxy_runtime_request),
453        )
454        .route("/", get(console::serve_console_asset))
455        .route("/project", get(console::serve_console_asset))
456        .route("/project/", get(console::serve_console_asset))
457        .route("/project/{*path}", get(console::serve_console_asset))
458        .route("/apps", get(console::serve_console_asset))
459        .route("/apps/", get(console::serve_console_asset))
460        .route("/apps/{*path}", get(console::serve_console_asset))
461        .route("/assets/{*path}", get(console::serve_console_asset))
462        .route("/brand/{*path}", get(console::serve_console_asset))
463        .route("/v1/status", get(api::status))
464        .route("/v1/local/apps/open", post(api::open_local_app))
465        .route(
466            "/v1/auth/exchange",
467            post(api::exchange_deployment_credential),
468        )
469        .route("/v1/guest/bootstrap", post(api::bootstrap_guest_project))
470        .route(
471            "/v1/guest/agent-gateway-enrollments",
472            post(api::create_guest_agent_gateway_enrollment),
473        )
474        .route(
475            "/v1/agent-gateway/deployments/{deployment_id}/enrollments",
476            post(api::create_agent_gateway_peer_enrollment),
477        )
478        .route("/v1/guest/claim", post(api::claim_guest_project))
479        .route("/v1/admin/verify", get(api::verify_admin))
480        .route("/v1/admin/app-ownership", get(api::list_project_ownership))
481        .route(
482            "/v1/admin/app-ownership/{project_id}",
483            axum::routing::patch(api::assign_project_owner),
484        )
485        .route(
486            "/v1/apps",
487            get(api::list_projects).post(api::create_project),
488        )
489        .route(
490            "/v1/apps/{id}",
491            get(api::get_project)
492                .patch(api::update_project)
493                .delete(api::delete_project),
494        )
495        .route(
496            "/v1/apps/{slug}/deployments",
497            get(api::list_project_runtime_deployments).post(api::create_project_runtime_deployment),
498        )
499        .route(
500            "/v1/apps/{slug}/deployments/{deployment}",
501            patch(api::update_project_runtime_deployment)
502                .delete(api::delete_project_runtime_deployment),
503        )
504        .route(
505            "/v1/apps/{slug}/deployments/{deployment}/promote",
506            post(api::promote_project_runtime_deployment),
507        )
508        .route(
509            "/v1/apps/{slug}/deployments/{deployment}/agent-gateway-enrollments",
510            post(api::create_runtime_deployment_agent_gateway_enrollment),
511        )
512        .route(
513            "/v1/apps/{slug}/deployments/{deployment}/agent-gateways/{gateway_id}",
514            post(api::assign_runtime_deployment_agent_gateway)
515                .delete(api::unassign_runtime_deployment_agent_gateway),
516        )
517        .route(
518            "/v1/apps/{slug}/runtime-releases",
519            get(api::list_project_runtime_releases).post(api::publish_project_runtime_release),
520        )
521        .route(
522            "/v1/apps/{slug}/runtime-releases/{version}",
523            get(api::get_project_runtime_release),
524        )
525        .route(
526            "/v1/apps/{slug}/deployments/{deployment}/runtime-releases/{version}/activate",
527            post(api::activate_project_runtime_release),
528        )
529        .route(
530            "/v1/runtime-extensions",
531            get(runtime_extensions::list_runtime_extensions),
532        )
533        .route(
534            "/v1/runtime-extensions/{extension_id}/projects/{project_id}/invoke",
535            post(runtime_extensions::invoke_project_profile_for_extension),
536        )
537        .route(
538            "/v1/apps/{slug}/extensions/runtime",
539            get(runtime_extensions::get_project_runtime_extension)
540                .put(runtime_extensions::set_project_runtime_extension)
541                .delete(runtime_extensions::delete_project_runtime_extension),
542        )
543        .route(
544            "/v1/apps/{slug}/runtime-channels",
545            get(runtime_extensions::list_project_runtime_channels)
546                .post(runtime_extensions::create_project_runtime_channel),
547        )
548        .route(
549            "/v1/apps/{slug}/runtime-channels/{channel_id}",
550            axum::routing::delete(runtime_extensions::delete_project_runtime_channel),
551        )
552        .route("/v1/provider-adapters", get(api::list_provider_adapters))
553        .route("/v1/provider-catalog", get(api::list_provider_catalog))
554        .route(
555            "/v1/apps/{slug}/provider-catalog",
556            get(api::list_project_provider_catalog),
557        )
558        .route(
559            "/v1/apps/{slug}/providers",
560            get(api::list_project_providers).post(api::create_project_provider),
561        )
562        .route(
563            "/v1/apps/{slug}/providers/import",
564            post(api::import_project_provider),
565        )
566        .route(
567            "/v1/apps/{slug}/providers/{provider_key}",
568            patch(api::update_project_provider).delete(api::delete_project_provider),
569        )
570        .route(
571            "/v1/apps/{slug}/providers/{provider_key}/test",
572            post(api::test_project_provider),
573        )
574        .route(
575            "/v1/apps/{slug}/provider-adapters",
576            get(api::list_project_provider_adapters),
577        )
578        .route(
579            "/v1/apps/{slug}/agent-candidates",
580            get(api::list_project_agent_candidates),
581        )
582        .route(
583            "/v1/apps/{slug}/agents/import",
584            post(api::import_project_agent),
585        )
586        .route(
587            "/v1/apps/{slug}/agents/{profile_id}/restore",
588            post(api::restore_project_agent),
589        )
590        .route(
591            "/v1/profiles",
592            get(api::list_profiles).post(api::create_profile),
593        )
594        .route(
595            "/v1/profiles/{id}",
596            get(api::get_profile)
597                .patch(api::update_profile)
598                .delete(api::delete_profile),
599        )
600        .route(
601            "/v1/apps/{slug}/profiles",
602            get(api::list_project_profiles).post(api::create_project_profile),
603        )
604        .route(
605            "/v1/apps/{slug}/profiles/import",
606            post(api::import_project_profile),
607        )
608        .route(
609            "/v1/apps/{slug}/profiles/{id}",
610            get(api::get_project_profile)
611                .patch(api::update_project_profile)
612                .delete(api::archive_project_profile),
613        )
614        .route(
615            "/v1/apps/{slug}/profiles/{id}/versions",
616            post(api::create_project_profile_version),
617        )
618        .route(
619            "/v1/apps/{slug}/profiles/{id}/source/sync",
620            post(api::sync_project_profile_source),
621        )
622        .route(
623            "/v1/apps/{slug}/profiles/{id}/versions/{version_id}/activate",
624            post(api::activate_project_profile_version),
625        )
626        .route(
627            "/v1/apps/{slug}/profiles/{id}/versions/{version_id}/archive",
628            post(api::archive_project_profile_version),
629        )
630        .route(
631            "/v1/apps/{slug}/profiles/{id}/rollout",
632            put(api::set_project_profile_rollout),
633        )
634        .route(
635            "/v1/apps/{slug}/profiles/{id}/test",
636            post(api::test_project_profile),
637        )
638        .route(
639            "/v1/apps/{slug}/bindings",
640            get(api::list_project_bindings).post(api::create_project_binding),
641        )
642        .route(
643            "/v1/apps/{slug}/bindings/{id}",
644            get(api::get_project_binding)
645                .patch(api::update_project_binding)
646                .delete(api::delete_project_binding),
647        )
648        .route(
649            "/v1/apps/{slug}/endpoints",
650            get(api::list_project_endpoints).post(api::create_project_endpoint),
651        )
652        .route(
653            "/v1/apps/{slug}/endpoints/{id}",
654            get(api::get_project_endpoint)
655                .patch(api::update_project_endpoint)
656                .delete(api::delete_project_endpoint),
657        )
658        .route(
659            "/v1/apps/{slug}/api-keys",
660            get(api::list_project_api_keys).post(api::create_project_api_key),
661        )
662        .route(
663            "/v1/apps/{slug}/api-keys/{id}",
664            patch(api::update_project_api_key).delete(api::delete_project_api_key),
665        )
666        .route(
667            "/v1/apps/{slug}/api-keys/{id}/revoke",
668            post(api::revoke_project_api_key),
669        )
670        .route(
671            "/v1/apps/{slug}/agent-gateways",
672            get(api::list_project_agent_gateways),
673        )
674        .route(
675            "/v1/apps/{slug}/comparisons",
676            get(comparisons::list_project_runtime_comparisons),
677        )
678        .route(
679            "/v1/apps/{slug}/agents",
680            get(api::list_project_available_agents),
681        )
682        .route("/v1/apps/{slug}/traces", get(api::list_project_traces))
683        .route(
684            "/v1/apps/{slug}/traces/{id}/spans",
685            get(api::list_project_trace_spans),
686        )
687        .route(
688            "/v1/apps/{slug}/traces/{id}/scores",
689            get(api::list_project_trace_scores),
690        )
691        .route(
692            "/v1/bindings",
693            get(api::list_bindings).post(api::create_binding),
694        )
695        .route(
696            "/v1/bindings/{id}",
697            get(api::get_binding)
698                .patch(api::update_binding)
699                .delete(api::delete_binding),
700        )
701        .route(
702            "/v1/endpoints",
703            get(api::list_endpoints).post(api::create_endpoint),
704        )
705        .route(
706            "/v1/endpoints/{id}",
707            get(api::get_endpoint)
708                .patch(api::update_endpoint)
709                .delete(api::delete_endpoint),
710        )
711        .route(
712            "/{project_slug}/v1/models",
713            get(api::list_project_openai_models),
714        )
715        .route(
716            "/{project_slug}/v1/chat/completions",
717            post(api::create_project_chat_completion),
718        )
719        .route(
720            "/{project_slug}/v1/embeddings",
721            post(api::create_project_embeddings),
722        )
723        .route(
724            "/{project_slug}/v1/traces/{invocation_id}/feedback",
725            post(api::create_app_feedback).layer(DefaultBodyLimit::max(16 * 1024)),
726        )
727        .route("/{project_slug}/v1/agents", get(api::list_project_agents))
728        .route(
729            "/{project_slug}/v1/audio/speech",
730            post(api::create_project_speech),
731        )
732        .route(
733            "/{project_slug}/v1/audio/transcriptions",
734            post(api::create_project_transcription),
735        )
736        .route(
737            "/{project_slug}/v1/realtime/sessions",
738            post(api::create_realtime_session),
739        )
740        .route(
741            "/{project_slug}/v1/rpc",
742            get(runtime_extensions::connect_project_runtime)
743                .post(runtime_extensions::invoke_project_runtime),
744        )
745        .route(
746            "/{project_slug}/v1/runtime/launch",
747            post(runtime_extensions::create_runtime_launch_session),
748        )
749        .route("/{project_slug}/v1/realtime", get(api::connect_realtime))
750        .route("/v1/models", get(api::list_openai_models))
751        .route("/v1/chat/completions", post(api::create_chat_completion))
752        .route(
753            "/v1/api-keys",
754            get(api::list_api_keys).post(api::create_api_key),
755        )
756        .route("/v1/api-keys/{id}/revoke", post(api::revoke_api_key))
757        .route(
758            "/v1/api-keys/{id}",
759            patch(api::update_api_key).delete(api::delete_api_key),
760        )
761        .route("/v1/agents", get(api::list_available_agents))
762        .route("/v1/agent-gateways", get(api::list_agent_gateways))
763        .route(
764            "/v1/agent-gateway-pairings",
765            get(api::list_agent_gateway_pairings),
766        )
767        .route(
768            "/v1/agent-gateway-pairings/{id}",
769            get(api::get_agent_gateway_pairing),
770        )
771        .route(
772            "/v1/agent-gateway-pairings/{id}/approve",
773            post(api::approve_agent_gateway_pairing),
774        )
775        .route(
776            "/v1/agent-gateway-pairings/{id}/reject",
777            post(api::reject_agent_gateway_pairing),
778        )
779        .route(
780            "/v1/agent-gateway/runtime-config",
781            get(api::get_agent_gateway_runtime_config),
782        )
783        .route(
784            "/v1/agent-gateway/runtime-agents",
785            get(api::list_agent_gateway_runtime_agents),
786        )
787        .route(
788            "/v1/agent-gateway/runtime-traces",
789            post(api::upload_agent_gateway_runtime_traces),
790        )
791        .route(
792            "/v1/agent-gateway/runtime-trace-observations",
793            post(api::upload_agent_gateway_runtime_trace_observations)
794                .layer(DefaultBodyLimit::max(128 * 1024)),
795        )
796        .route(
797            "/v1/agent-gateway/runtime-comparisons",
798            post(comparisons::upload_runtime_comparison).layer(DefaultBodyLimit::max(
799                vifu_gateway::optimization::MAX_COMPARISON_UPLOAD_BYTES,
800            )),
801        )
802        .route("/v1/runtime-monitor/connect", get(monitor::upgrade))
803        .route(
804            "/v1/agent-gateway/runtime-releases/bootstrap",
805            post(api::bootstrap_agent_gateway_runtime_release),
806        )
807        .route(
808            "/v1/agent-gateway/runtime-releases/applied",
809            post(api::report_agent_gateway_runtime_release_applied),
810        )
811        .route(
812            "/v1/apps/{slug}/agent-gateway-enrollments",
813            post(api::create_project_agent_gateway_enrollment),
814        )
815        .route(
816            "/v1/apps/{slug}/runtime-distributions",
817            get(api::list_project_runtime_distributions)
818                .post(api::create_project_runtime_distribution),
819        )
820        .route(
821            "/v1/apps/{slug}/runtime-distributions/{distribution_id}/revoke",
822            post(api::revoke_project_runtime_distribution),
823        )
824        .route(
825            "/v1/agent-gateways/{gateway_id}/revoke",
826            post(api::revoke_agent_gateway),
827        )
828        .route("/v1/traces", get(api::list_traces))
829        .route("/v1/traces/{id}/spans", get(api::list_trace_spans))
830        .route("/v1/traces/{id}/scores", get(api::list_trace_scores))
831        .route("/v1/agent-gateway/connect", get(websocket::upgrade))
832        .fallback(console::proxy_dashboard_request)
833        .layer(PropagateRequestIdLayer::new(request_id_header.clone()))
834        .layer(TraceLayer::new_for_http())
835        .layer(SetRequestIdLayer::new(request_id_header, MakeRequestUuid))
836        .layer(DefaultBodyLimit::max(32 * 1024 * 1024))
837        .layer(RequestBodyLimitLayer::new(32 * 1024 * 1024))
838        .layer(cors)
839        .layer(CatchPanicLayer::new())
840        .with_state(state)
841}
842
843#[cfg(test)]
844mod tests {
845    use std::path::PathBuf;
846    use std::sync::Arc;
847
848    use axum::body::{to_bytes, Body};
849    use axum::http::{header::CONTENT_TYPE, Request, StatusCode};
850    use axum::response::Response;
851    use axum::routing::get;
852    use serde_json::{json, Value};
853    use sqlx::postgres::PgPoolOptions;
854    use tokio::task::JoinHandle;
855    use tower::ServiceExt;
856
857    use super::{
858        app, ensure_local_bootstrap_app, load_server_endpoint_identity, state, state_with_storage,
859        state_with_storage_and_auth, AppState, ServerEndpointIdentity,
860    };
861    use crate::auth::{
862        AccessTokenAuth, AccessTokenAuthFuture, ApplicationAuth, Identity, Operation,
863    };
864    use crate::config::{Config, DeploymentMode};
865    use crate::db::Storage;
866    use crate::error::ApiError;
867
868    async fn local_bootstrap_test_state(prefix: &str) -> (PathBuf, Storage, AppState) {
869        let path = std::env::temp_dir().join(format!("{prefix}-{}.sqlite", uuid::Uuid::new_v4()));
870        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
871            .await
872            .unwrap();
873        crate::db::migrate(&storage).await.unwrap();
874        let state = state_with_storage(Config::from_env().unwrap(), storage.clone());
875        (path, storage, state)
876    }
877
878    async fn close_local_bootstrap_test_storage(path: PathBuf, storage: Storage) {
879        match storage {
880            Storage::Postgres(pool) => pool.close().await,
881            Storage::Sqlite(pool) => pool.close().await,
882        }
883        std::fs::remove_file(path).unwrap();
884    }
885
886    #[tokio::test]
887    async fn local_bootstrap_app_is_created_once_and_reused() {
888        let (path, storage, state) = local_bootstrap_test_state("vifu-local-bootstrap-app").await;
889
890        let created = ensure_local_bootstrap_app(&state, None).await.unwrap();
891        let reused = ensure_local_bootstrap_app(&state, None).await.unwrap();
892
893        assert_eq!(
894            (
895                reused.project_id,
896                reused.app_id.as_str(),
897                reused.project_slug.as_str(),
898                reused.project_name.as_str(),
899                reused.deployment_id,
900                reused.deployment.as_str(),
901                reused.created,
902            ),
903            (
904                created.project_id,
905                created.app_id.as_str(),
906                "local-app",
907                "Local app",
908                created.deployment_id,
909                "development",
910                false,
911            )
912        );
913        assert!(created.created);
914        close_local_bootstrap_test_storage(path, storage).await;
915    }
916
917    #[tokio::test]
918    async fn local_bootstrap_promotes_the_preferred_legacy_guest_in_place() {
919        let (path, storage, state) = local_bootstrap_test_state("vifu-local-bootstrap-guest").await;
920        let project_id = uuid::Uuid::new_v4();
921        let guest = crate::db::create_project(
922            &storage,
923            crate::db::NewProject {
924                id: project_id,
925                owner_user_id: None,
926                slug: "guest-existing",
927                name: "Guest app",
928                description: None,
929                gateway_id: "gateway-existing",
930                binding_ids: &[],
931            },
932        )
933        .await
934        .unwrap();
935        crate::db::create_guest_project(
936            &storage,
937            crate::db::NewGuestProject {
938                project_id,
939                gateway_id: "gateway-existing",
940                claim_token_hash: b"synthetic-claim-token-hash",
941                expires_at: chrono::Utc::now() + chrono::Duration::days(7),
942            },
943        )
944        .await
945        .unwrap();
946
947        let promoted = ensure_local_bootstrap_app(&state, Some(&guest.project.app_id))
948            .await
949            .unwrap();
950
951        assert_eq!(
952            (
953                promoted.project_id,
954                promoted.app_id.as_str(),
955                promoted.project_name.as_str(),
956                crate::db::get_active_guest_project_by_project_id(&storage, project_id)
957                    .await
958                    .unwrap(),
959                promoted.created,
960            ),
961            (
962                project_id,
963                guest.project.app_id.as_str(),
964                "Local app",
965                None,
966                false,
967            )
968        );
969        close_local_bootstrap_test_storage(path, storage).await;
970    }
971
972    #[tokio::test]
973    async fn local_bootstrap_does_not_mutate_multiple_existing_apps() {
974        let (path, storage, state) =
975            local_bootstrap_test_state("vifu-local-bootstrap-multiple-apps").await;
976        for (slug, name) in [("alpha", "Alpha"), ("beta", "Beta")] {
977            crate::db::create_project(
978                &storage,
979                crate::db::NewProject {
980                    id: uuid::Uuid::new_v4(),
981                    owner_user_id: None,
982                    slug,
983                    name,
984                    description: None,
985                    gateway_id: "",
986                    binding_ids: &[],
987                },
988            )
989            .await
990            .unwrap();
991        }
992
993        let selected = ensure_local_bootstrap_app(&state, None).await.unwrap();
994        let projects = crate::db::list_projects(&storage).await.unwrap();
995        let mut names = projects
996            .iter()
997            .map(|project| project.project.name.as_str())
998            .collect::<Vec<_>>();
999        names.sort_unstable();
1000
1001        assert!(!selected.created);
1002        assert_eq!(names, ["Alpha", "Beta"]);
1003        assert!(projects
1004            .iter()
1005            .any(|project| project.project.id == selected.project_id));
1006        close_local_bootstrap_test_storage(path, storage).await;
1007    }
1008
1009    #[tokio::test]
1010    async fn local_sdk_opens_one_stable_app_without_admin_credentials() {
1011        let (path, storage, state) = local_bootstrap_test_state("vifu-local-sdk-app").await;
1012        let router = app(state);
1013        let created = router
1014            .clone()
1015            .oneshot(
1016                Request::post("/v1/local/apps/open")
1017                    .header("content-type", "application/json")
1018                    .body(Body::from(r#"{"name":"Python Weather"}"#))
1019                    .unwrap(),
1020            )
1021            .await
1022            .unwrap();
1023        assert_eq!(created.status(), StatusCode::CREATED);
1024        let created = response_json(created).await;
1025        let app_id = created["app"]["appId"].as_str().unwrap();
1026
1027        let reopened = router
1028            .oneshot(
1029                Request::post("/v1/local/apps/open")
1030                    .header("content-type", "application/json")
1031                    .body(Body::from(
1032                        json!({"name": "Python Weather", "appId": app_id}).to_string(),
1033                    ))
1034                    .unwrap(),
1035            )
1036            .await
1037            .unwrap();
1038        assert_eq!(reopened.status(), StatusCode::OK);
1039        let reopened = response_json(reopened).await;
1040        assert_eq!(reopened["app"]["appId"], app_id);
1041        assert_eq!(crate::db::list_projects(&storage).await.unwrap().len(), 1);
1042        close_local_bootstrap_test_storage(path, storage).await;
1043    }
1044
1045    #[tokio::test]
1046    async fn local_sdk_reopens_an_existing_named_app_without_a_manifest() {
1047        let (path, storage, state) = local_bootstrap_test_state("vifu-local-sdk-name").await;
1048        let router = app(state);
1049        let request = || {
1050            Request::post("/v1/local/apps/open")
1051                .header("content-type", "application/json")
1052                .body(Body::from(r#"{"name":"Web Research"}"#))
1053                .unwrap()
1054        };
1055        let created = router.clone().oneshot(request()).await.unwrap();
1056        assert_eq!(created.status(), StatusCode::CREATED);
1057        let created = response_json(created).await;
1058
1059        let reopened = router.oneshot(request()).await.unwrap();
1060        assert_eq!(reopened.status(), StatusCode::OK);
1061        let reopened = response_json(reopened).await;
1062
1063        assert_eq!(reopened["app"]["appId"], created["app"]["appId"]);
1064        close_local_bootstrap_test_storage(path, storage).await;
1065    }
1066
1067    #[test]
1068    fn gateway_pairing_uri_contains_the_endpoint_token_and_pinned_certificate() {
1069        let endpoint = ServerEndpointIdentity {
1070            server_url: "https://192.168.1.20:6790".to_string(),
1071            certificate_der_base64: Some("certificate+/=".to_string()),
1072            certificate_sha256: Some("sha256:abcdef".to_string()),
1073        };
1074        let pairing = endpoint
1075            .gateway_pairing_uri(
1076                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1077            )
1078            .unwrap();
1079        let parsed = reqwest::Url::parse(&pairing).unwrap();
1080        let query = parsed
1081            .query_pairs()
1082            .collect::<std::collections::HashMap<_, _>>();
1083
1084        assert_eq!(query.get("server").unwrap(), "https://192.168.1.20:6790");
1085        assert!(query.get("token").unwrap().starts_with("vifu_ge_"));
1086        assert_eq!(query.get("certificate").unwrap(), "certificate+/=");
1087        assert_eq!(query.get("fingerprint").unwrap(), "sha256:abcdef");
1088    }
1089
1090    #[test]
1091    fn server_endpoint_identity_exposes_the_pinned_certificate_der() {
1092        let endpoint = ServerEndpointIdentity {
1093            server_url: "https://192.0.2.20:6790".to_string(),
1094            certificate_der_base64: Some("AQID".to_string()),
1095            certificate_sha256: Some("sha256:synthetic".to_string()),
1096        };
1097
1098        assert_eq!(endpoint.certificate_der().unwrap(), Some(vec![1, 2, 3]));
1099    }
1100
1101    #[test]
1102    fn gateway_pairing_terminal_qr_is_compact() {
1103        let endpoint = ServerEndpointIdentity {
1104            server_url: "https://192.0.2.20:6790".to_string(),
1105            certificate_der_base64: Some("synthetic-certificate".repeat(12)),
1106            certificate_sha256: Some("sha256:synthetic-fingerprint".to_string()),
1107        };
1108        let terminal_qr = endpoint
1109            .gateway_pairing_terminal_qr(
1110                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1111            )
1112            .unwrap();
1113        let compact_uri = endpoint
1114            .gateway_pairing_web_uri(
1115                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1116            )
1117            .unwrap();
1118
1119        assert!(terminal_qr.lines().count() > 10);
1120        assert!(terminal_qr.lines().count() <= 40);
1121        let qr_height = terminal_qr.lines().count();
1122        let qr_width = terminal_qr
1123            .lines()
1124            .map(|line| line.chars().count())
1125            .max()
1126            .unwrap();
1127        assert!(qr_width.abs_diff(qr_height.saturating_mul(2)) <= 1);
1128        let bridge = reqwest::Url::parse(&compact_uri).unwrap();
1129        assert_eq!(
1130            bridge.as_str().split('#').next(),
1131            Some("https://vifu.ai/pair")
1132        );
1133        assert!(bridge.query().is_none());
1134        assert!(bridge.fragment().is_some());
1135        assert!(compact_uri.contains("fingerprint="));
1136        assert!(!compact_uri.contains("certificate="));
1137        assert!(terminal_qr.lines().all(|line| {
1138            line.chars()
1139                .all(|character| matches!(character, ' ' | '\u{2580}' | '\u{2584}' | '\u{2588}'))
1140        }));
1141    }
1142
1143    #[test]
1144    fn direct_gateway_pairing_qr_contains_the_native_enrollment_uri() {
1145        let endpoint = ServerEndpointIdentity {
1146            server_url: "https://api.vifu.ai".to_string(),
1147            certificate_der_base64: None,
1148            certificate_sha256: None,
1149        };
1150        let terminal_qr = endpoint
1151            .gateway_pairing_direct_terminal_qr(
1152                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1153            )
1154            .unwrap();
1155
1156        assert!(!terminal_qr.is_empty());
1157        assert!(terminal_qr.lines().count() <= 40);
1158    }
1159
1160    #[test]
1161    fn compact_native_pairing_keeps_the_certificate_fingerprint_without_the_der() {
1162        let endpoint = ServerEndpointIdentity {
1163            server_url: "https://192.0.2.20:6790".to_string(),
1164            certificate_der_base64: Some("synthetic-certificate".repeat(32)),
1165            certificate_sha256: Some(format!("sha256:{}", "a".repeat(64))),
1166        };
1167
1168        let uri = endpoint
1169            .gateway_pairing_compact_uri(
1170                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1171            )
1172            .unwrap();
1173        let terminal_qr = endpoint
1174            .gateway_pairing_direct_terminal_qr(
1175                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1176            )
1177            .unwrap();
1178
1179        assert!(uri.starts_with("vifu://gateway/enroll?"));
1180        assert!(uri.contains("fingerprint="));
1181        assert!(!uri.contains("certificate="));
1182        assert!(terminal_qr.lines().count() <= 40);
1183    }
1184
1185    #[tokio::test]
1186    async fn health_is_public_and_does_not_require_database_readiness() {
1187        let config = Config::from_env().unwrap();
1188        let pool = PgPoolOptions::new()
1189            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
1190            .unwrap();
1191        let response = app(state(config, pool))
1192            .oneshot(Request::get("/health").body(Body::empty()).unwrap())
1193            .await
1194            .unwrap();
1195        assert_eq!(response.status(), StatusCode::OK);
1196        let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
1197        let payload: Value = serde_json::from_slice(&body).unwrap();
1198        assert_eq!(payload["service"], "vifu-server");
1199    }
1200
1201    #[tokio::test]
1202    async fn status_reports_the_configured_service_version() {
1203        let mut config = Config::from_env().unwrap();
1204        config.apply_service_version("0.1.7").unwrap();
1205        config
1206            .apply_public_dashboard_url("https://dashboard.example.com")
1207            .unwrap();
1208        let (storage, path) = temp_sqlite_storage("status-version").await;
1209        let response = app(state_with_storage(config, storage.clone()))
1210            .oneshot(Request::get("/v1/status").body(Body::empty()).unwrap())
1211            .await
1212            .unwrap();
1213        let payload = response_json(response).await;
1214        close_temp_storage(storage, path).await;
1215
1216        assert_eq!(payload["version"], "0.1.7");
1217        assert_eq!(payload["dashboardUrl"], "https://dashboard.example.com");
1218    }
1219
1220    #[test]
1221    fn generated_tls_pairing_identity_is_rebuilt_from_the_served_certificate() {
1222        let directory =
1223            std::env::temp_dir().join(format!("vifu-server-tls-{}", uuid::Uuid::new_v4().simple()));
1224        std::fs::create_dir_all(&directory).unwrap();
1225        let mut config = Config::from_env().unwrap();
1226        config.provider_home_dir.clone_from(&directory);
1227        config
1228            .apply_server_url("https://macbook.local:6790")
1229            .unwrap();
1230        config.apply_generated_tls().unwrap();
1231
1232        let first = load_server_endpoint_identity(&config).unwrap().unwrap();
1233        let sidecar = config.tls.as_ref().unwrap().certificate_der_path.clone();
1234        std::fs::remove_file(&sidecar).unwrap();
1235        let restored = load_server_endpoint_identity(&config).unwrap().unwrap();
1236
1237        assert_eq!(
1238            restored.certificate_der_base64,
1239            first.certificate_der_base64
1240        );
1241        assert_eq!(restored.certificate_sha256, first.certificate_sha256);
1242        assert!(sidecar.is_file());
1243        let qr = restored
1244            .gateway_pairing_terminal_qr(
1245                "vifu_ge_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
1246            )
1247            .unwrap();
1248        let qr_width = qr.lines().map(|line| line.chars().count()).max().unwrap();
1249        let qr_height = qr.lines().count();
1250        assert!(
1251            qr_width <= 64
1252                && qr_height <= 32
1253                && qr_width.abs_diff(qr_height.saturating_mul(2)) <= 1,
1254            "generated LAN pairing QR is too large for a normal terminal: {qr_width}x{qr_height}"
1255        );
1256        std::fs::remove_dir_all(directory).unwrap();
1257    }
1258
1259    #[tokio::test]
1260    async fn local_embedded_console_mounts_at_server_root() {
1261        let mut config = Config::from_env().unwrap();
1262        config.deployment_mode = DeploymentMode::Local;
1263        config.addr = "127.0.0.1:6790".parse().unwrap();
1264        let pool = PgPoolOptions::new()
1265            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
1266            .unwrap();
1267        let router = app(state(config, pool));
1268
1269        let root = router
1270            .clone()
1271            .oneshot(Request::get("/").body(Body::empty()).unwrap())
1272            .await
1273            .unwrap();
1274        assert_eq!(root.status(), StatusCode::OK);
1275        assert!(root
1276            .headers()
1277            .get(CONTENT_TYPE)
1278            .and_then(|value| value.to_str().ok())
1279            .is_some_and(|value| value.starts_with("text/html")));
1280
1281        let project_route = router
1282            .clone()
1283            .oneshot(
1284                Request::get("/project/demo/agents")
1285                    .body(Body::empty())
1286                    .unwrap(),
1287            )
1288            .await
1289            .unwrap();
1290        assert_eq!(project_route.status(), StatusCode::OK);
1291
1292        let console_route = router
1293            .oneshot(Request::get("/console").body(Body::empty()).unwrap())
1294            .await
1295            .unwrap();
1296        assert_eq!(console_route.status(), StatusCode::NOT_FOUND);
1297    }
1298
1299    #[tokio::test]
1300    async fn admin_verification_requires_the_configured_key() {
1301        let config = Config::from_env().unwrap();
1302        let admin_key = config.admin_key.clone();
1303        let pool = PgPoolOptions::new()
1304            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
1305            .unwrap();
1306
1307        let denied = app(state(config.clone(), pool.clone()))
1308            .oneshot(
1309                Request::get("/v1/admin/verify")
1310                    .body(Body::empty())
1311                    .unwrap(),
1312            )
1313            .await
1314            .unwrap();
1315        assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
1316
1317        let verified = app(state(config, pool))
1318            .oneshot(
1319                Request::get("/v1/admin/verify")
1320                    .header("authorization", format!("Bearer {admin_key}"))
1321                    .body(Body::empty())
1322                    .unwrap(),
1323            )
1324            .await
1325            .unwrap();
1326        assert_eq!(verified.status(), StatusCode::OK);
1327        let body = to_bytes(verified.into_body(), 64 * 1024).await.unwrap();
1328        let payload: Value = serde_json::from_slice(&body).unwrap();
1329        assert_eq!(payload["valid"], true);
1330    }
1331
1332    #[tokio::test]
1333    async fn resource_routes_reject_unexchanged_account_access_tokens() {
1334        let config = Config::from_env().unwrap();
1335        let pool = PgPoolOptions::new()
1336            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
1337            .unwrap();
1338
1339        let (state, _) =
1340            state_with_access_token_auth(config, pool, vec![Operation::ProjectRead]).await;
1341        let response = app(state)
1342            .oneshot(
1343                Request::get("/v1/admin/verify")
1344                    .header("authorization", "Vifu account-access-token")
1345                    .body(Body::empty())
1346                    .unwrap(),
1347            )
1348            .await
1349            .unwrap();
1350
1351        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
1352    }
1353
1354    #[tokio::test]
1355    async fn account_access_tokens_are_exchanged_for_deployment_credentials() {
1356        let config = Config::from_env().unwrap();
1357        let pool = PgPoolOptions::new()
1358            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
1359            .unwrap();
1360        let auth = ApplicationAuth::with_deployment_credential_auth(
1361            config.admin_key.clone(),
1362            "dep_01JTESTDEPLOYMENT",
1363            Arc::new(StaticAccessTokenAuth {
1364                subject: "user-123".to_string(),
1365                operations: vec![Operation::ProjectRead, Operation::ProjectWrite],
1366            }),
1367        );
1368        let response = app(state_with_storage_and_auth(
1369            config,
1370            Storage::postgres(pool),
1371            auth,
1372        ))
1373        .oneshot(
1374            Request::post("/v1/auth/exchange")
1375                .header("authorization", "Bearer account-access-token")
1376                .body(Body::empty())
1377                .unwrap(),
1378        )
1379        .await
1380        .unwrap();
1381
1382        assert_eq!(response.status(), StatusCode::OK);
1383        let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
1384        let payload: Value = serde_json::from_slice(&body).unwrap();
1385        assert!(payload["credential"]
1386            .as_str()
1387            .is_some_and(|value| value.starts_with("vifu_dc1.")));
1388        assert!(payload["expiresAt"].as_u64().is_some());
1389    }
1390
1391    #[tokio::test]
1392    async fn read_only_access_tokens_cannot_mutate_a_deployment() {
1393        let config = Config::from_env().unwrap();
1394        let pool = PgPoolOptions::new()
1395            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
1396            .unwrap();
1397
1398        let (state, credential) =
1399            state_with_access_token_auth(config, pool, vec![Operation::ProjectRead]).await;
1400        let response = app(state)
1401            .oneshot(
1402                Request::post("/v1/apps")
1403                    .header("authorization", format!("Vifu {credential}"))
1404                    .header("content-type", "application/json")
1405                    .body(Body::from(r#"{"name":"Denied project"}"#))
1406                    .unwrap(),
1407            )
1408            .await
1409            .unwrap();
1410
1411        assert_eq!(response.status(), StatusCode::FORBIDDEN);
1412    }
1413
1414    #[tokio::test]
1415    async fn account_projects_are_created_and_listed_under_the_canonical_user() {
1416        let path = std::env::temp_dir().join(format!(
1417            "vifu-account-projects-{}.sqlite",
1418            uuid::Uuid::new_v4()
1419        ));
1420        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
1421            .await
1422            .unwrap();
1423        crate::db::migrate(&storage).await.unwrap();
1424        let config = Config::from_env().unwrap();
1425        let (owner_state, owner_credential) = state_with_storage_access_token_auth(
1426            config.clone(),
1427            storage.clone(),
1428            "user-123",
1429            vec![Operation::ProjectRead, Operation::ProjectWrite],
1430        )
1431        .await;
1432        let owner_app = app(owner_state);
1433
1434        let created = owner_app
1435            .clone()
1436            .oneshot(
1437                Request::post("/v1/apps")
1438                    .header("authorization", format!("Vifu {owner_credential}"))
1439                    .header("content-type", "application/json")
1440                    .body(Body::from(r#"{"name":"Owned project"}"#))
1441                    .unwrap(),
1442            )
1443            .await
1444            .unwrap();
1445        assert_eq!(created.status(), StatusCode::CREATED);
1446        let body = to_bytes(created.into_body(), 64 * 1024).await.unwrap();
1447        let payload: Value = serde_json::from_slice(&body).unwrap();
1448        let project_id = payload["app"]["id"].as_str().unwrap();
1449        assert!(payload["app"].get("ownerUserId").is_none());
1450
1451        let owner_list = owner_app
1452            .oneshot(
1453                Request::get("/v1/apps")
1454                    .header("authorization", format!("Vifu {owner_credential}"))
1455                    .body(Body::empty())
1456                    .unwrap(),
1457            )
1458            .await
1459            .unwrap();
1460        let body = to_bytes(owner_list.into_body(), 64 * 1024).await.unwrap();
1461        let payload: Value = serde_json::from_slice(&body).unwrap();
1462        assert_eq!(payload["apps"].as_array().unwrap().len(), 1);
1463
1464        let (other_state, other_credential) = state_with_storage_access_token_auth(
1465            config,
1466            storage.clone(),
1467            "user-456",
1468            vec![Operation::ProjectRead, Operation::ProjectWrite],
1469        )
1470        .await;
1471        let other_app = app(other_state);
1472        let other_list = other_app
1473            .clone()
1474            .oneshot(
1475                Request::get("/v1/apps")
1476                    .header("authorization", format!("Vifu {other_credential}"))
1477                    .body(Body::empty())
1478                    .unwrap(),
1479            )
1480            .await
1481            .unwrap();
1482        let body = to_bytes(other_list.into_body(), 64 * 1024).await.unwrap();
1483        let payload: Value = serde_json::from_slice(&body).unwrap();
1484        assert!(payload["apps"].as_array().unwrap().is_empty());
1485        let forbidden = other_app
1486            .oneshot(
1487                Request::get(format!("/v1/apps/{project_id}"))
1488                    .header("authorization", format!("Vifu {other_credential}"))
1489                    .body(Body::empty())
1490                    .unwrap(),
1491            )
1492            .await
1493            .unwrap();
1494        assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
1495
1496        match storage {
1497            Storage::Postgres(pool) => pool.close().await,
1498            Storage::Sqlite(pool) => pool.close().await,
1499        }
1500        std::fs::remove_file(path).unwrap();
1501    }
1502
1503    #[tokio::test]
1504    async fn account_project_enrollment_registers_one_gateway_once() {
1505        let path = std::env::temp_dir().join(format!(
1506            "vifu-gateway-enrollment-{}.sqlite",
1507            uuid::Uuid::new_v4()
1508        ));
1509        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
1510            .await
1511            .unwrap();
1512        crate::db::migrate(&storage).await.unwrap();
1513        let config = Config::from_env().unwrap();
1514        let api_key_pepper = config.api_key_pepper.clone();
1515        let (owner_state, owner_credential) = state_with_storage_access_token_auth(
1516            config,
1517            storage.clone(),
1518            "user-123",
1519            vec![Operation::ProjectRead, Operation::ProjectWrite],
1520        )
1521        .await;
1522        let owner_app = app(owner_state);
1523        let created = owner_app
1524            .clone()
1525            .oneshot(
1526                Request::post("/v1/apps")
1527                    .header("authorization", format!("Vifu {owner_credential}"))
1528                    .header("content-type", "application/json")
1529                    .body(Body::from(r#"{"name":"Gateway project"}"#))
1530                    .unwrap(),
1531            )
1532            .await
1533            .unwrap();
1534        let body = to_bytes(created.into_body(), 64 * 1024).await.unwrap();
1535        let project: Value = serde_json::from_slice(&body).unwrap();
1536        let slug = project["app"]["slug"].as_str().unwrap();
1537
1538        let enrollment = owner_app
1539            .clone()
1540            .oneshot(
1541                Request::post(format!("/v1/apps/{slug}/agent-gateway-enrollments"))
1542                    .header("authorization", format!("Vifu {owner_credential}"))
1543                    .body(Body::empty())
1544                    .unwrap(),
1545            )
1546            .await
1547            .unwrap();
1548        assert_eq!(enrollment.status(), StatusCode::CREATED);
1549        let body = to_bytes(enrollment.into_body(), 64 * 1024).await.unwrap();
1550        let enrollment: Value = serde_json::from_slice(&body).unwrap();
1551        let enrollment_id =
1552            uuid::Uuid::parse_str(enrollment["enrollmentId"].as_str().unwrap()).unwrap();
1553        let token = enrollment["enrollmentToken"].as_str().unwrap();
1554
1555        let machine = vifu_gateway::identity::MachineIdentity::generate().unwrap();
1556        crate::db::upsert_agent_gateway_machine(&storage, &machine.machine_id, &machine.public_key)
1557            .await
1558            .unwrap();
1559        let enrollment_hash = crate::auth::hash_agent_gateway_enrollment(token, &api_key_pepper);
1560        let assignment = crate::db::consume_agent_gateway_machine_enrollment(
1561            &storage,
1562            &enrollment_hash,
1563            "gateway-account",
1564        )
1565        .await
1566        .unwrap();
1567        assert_eq!(assignment.enrollment_id, enrollment_id);
1568        let device_token =
1569            "vifu_gw_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1570        let device_token_hash =
1571            crate::auth::hash_agent_gateway_credential(device_token, &api_key_pepper);
1572        crate::db::create_agent_gateway_authorization(
1573            &storage,
1574            crate::db::NewAgentGatewayAuthorization {
1575                gateway_id: "gateway-account",
1576                machine_id: &machine.machine_id,
1577                owner_user_id: Some(&assignment.owner_user_id),
1578                token_prefix: &device_token.chars().take(20).collect::<String>(),
1579                token_hash: &device_token_hash,
1580                token_expires_at: chrono::Utc::now() + chrono::Duration::days(180),
1581            },
1582        )
1583        .await
1584        .unwrap();
1585        assert_eq!(
1586            crate::db::get_project_by_slug(&storage, slug)
1587                .await
1588                .unwrap()
1589                .project
1590                .gateway_id,
1591            "gateway-account"
1592        );
1593
1594        let runtime_config = owner_app
1595            .clone()
1596            .oneshot(
1597                Request::get("/v1/agent-gateway/runtime-config")
1598                    .header(
1599                        "authorization",
1600                        "Bearer vifu_gw_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1601                    )
1602                    .body(Body::empty())
1603                    .unwrap(),
1604            )
1605            .await
1606            .unwrap();
1607        assert_eq!(runtime_config.status(), StatusCode::OK);
1608        let body = to_bytes(runtime_config.into_body(), 64 * 1024)
1609            .await
1610            .unwrap();
1611        let runtime_config: Value = serde_json::from_slice(&body).unwrap();
1612        assert_eq!(runtime_config["gatewayId"], "gateway-account");
1613        assert_eq!(runtime_config["deployments"].as_array().unwrap().len(), 1);
1614        let deployment_id = runtime_config["deployments"][0]["deploymentId"]
1615            .as_str()
1616            .unwrap();
1617        let project_id = crate::db::get_project_by_slug(&storage, slug)
1618            .await
1619            .unwrap()
1620            .project
1621            .id;
1622        assert!(!crate::db::runtime_deployment_allows_remote_invocation(
1623            &storage,
1624            project_id,
1625            "gateway-account",
1626        )
1627        .await
1628        .unwrap());
1629
1630        let enabled_remote_invocation = owner_app
1631            .clone()
1632            .oneshot(
1633                Request::patch(format!("/v1/apps/{slug}/deployments/development"))
1634                    .header("authorization", format!("Vifu {owner_credential}"))
1635                    .header("content-type", "application/json")
1636                    .body(Body::from(r#"{"remoteInvocationEnabled":true}"#))
1637                    .unwrap(),
1638            )
1639            .await
1640            .unwrap();
1641        assert_eq!(enabled_remote_invocation.status(), StatusCode::OK);
1642        assert!(crate::db::runtime_deployment_allows_remote_invocation(
1643            &storage,
1644            project_id,
1645            "gateway-account",
1646        )
1647        .await
1648        .unwrap());
1649
1650        let release = owner_app
1651            .clone()
1652            .oneshot(
1653                Request::post("/v1/agent-gateway/runtime-releases/bootstrap")
1654                    .header(
1655                        "authorization",
1656                        "Bearer vifu_gw_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1657                    )
1658                    .header("content-type", "application/json")
1659                    .body(Body::from(format!(
1660                        r#"{{
1661                            "deploymentId":"{deployment_id}",
1662                            "manifest":{{
1663                                "schemaVersion":1,
1664                                "projectId":"{slug}",
1665                                "providers":[{{
1666                                    "id":"local-model",
1667                                    "providerType":"native",
1668                                    "capabilities":["chat"]
1669                                }}],
1670                                "agents":[{{
1671                                    "id":"guide",
1672                                    "name":"Guide",
1673                                    "provider":"local-model",
1674                                    "capabilities":["chat"]
1675                                }}],
1676                                "endpoints":[{{
1677                                    "name":"guide",
1678                                    "agent":"guide",
1679                                    "capability":"chat",
1680                                    "timeoutMs":30000
1681                                }}],
1682                                "metadata":{{}}
1683                            }}
1684                        }}"#
1685                    )))
1686                    .unwrap(),
1687            )
1688            .await
1689            .unwrap();
1690        assert_eq!(release.status(), StatusCode::CREATED);
1691
1692        let runtime_config = owner_app
1693            .clone()
1694            .oneshot(
1695                Request::get("/v1/agent-gateway/runtime-config")
1696                    .header(
1697                        "authorization",
1698                        "Bearer vifu_gw_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1699                    )
1700                    .body(Body::empty())
1701                    .unwrap(),
1702            )
1703            .await
1704            .unwrap();
1705        let body = to_bytes(runtime_config.into_body(), 64 * 1024)
1706            .await
1707            .unwrap();
1708        let runtime_config: Value = serde_json::from_slice(&body).unwrap();
1709        assert_eq!(runtime_config["deployments"][0]["release"]["version"], 1);
1710
1711        let uploaded = owner_app
1712            .clone()
1713            .oneshot(
1714                Request::post("/v1/agent-gateway/runtime-traces")
1715                    .header(
1716                        "authorization",
1717                        "Bearer vifu_gw_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1718                    )
1719                    .header("content-type", "application/json")
1720                    .body(Body::from(format!(
1721                        r#"{{
1722                            "deploymentId":"{deployment_id}",
1723                            "traces":[{{
1724                                "id":"trace-embedded-1",
1725                                "projectId":"{slug}",
1726                                "invocationId":"invoke-embedded-1",
1727                                "endpoint":"guide",
1728                                "agent":"guide",
1729                                "provider":"local-model",
1730                                "capability":"chat",
1731                                "status":"completed",
1732                                "durationMs":12,
1733                                "createdAtMs":1
1734                            }}]
1735                        }}"#
1736                    )))
1737                    .unwrap(),
1738            )
1739            .await
1740            .unwrap();
1741        assert_eq!(uploaded.status(), StatusCode::OK);
1742        assert_eq!(
1743            crate::db::list_traces(
1744                &storage,
1745                crate::db::TraceListOptions {
1746                    endpoint_id: None,
1747                    project_id: Some(
1748                        crate::db::get_project_by_slug(&storage, slug)
1749                            .await
1750                            .unwrap()
1751                            .project
1752                            .id,
1753                    ),
1754                    request_id: None,
1755                    trace_id: None,
1756                    allowed_profile_ids: None,
1757                    created_from: None,
1758                    created_before: None,
1759                    cursor: None,
1760                    limit: 10,
1761                },
1762            )
1763            .await
1764            .unwrap()
1765            .len(),
1766            1
1767        );
1768        crate::db::open_agent_gateway_session(
1769            &storage,
1770            "gateway-account",
1771            None,
1772            &serde_json::json!([{
1773                "id": "guide",
1774                "name": "Guide",
1775                "metadata": {
1776                    "providerKey": "openclaw-local",
1777                    "providerType": "openclaw"
1778                }
1779            }]),
1780            &serde_json::json!({}),
1781        )
1782        .await
1783        .unwrap();
1784
1785        let candidates = owner_app
1786            .clone()
1787            .oneshot(
1788                Request::get(format!("/v1/apps/{slug}/agent-candidates"))
1789                    .header("authorization", format!("Vifu {owner_credential}"))
1790                    .body(Body::empty())
1791                    .unwrap(),
1792            )
1793            .await
1794            .unwrap();
1795        assert_eq!(candidates.status(), StatusCode::OK);
1796        let body = to_bytes(candidates.into_body(), 64 * 1024).await.unwrap();
1797        let candidates: Value = serde_json::from_slice(&body).unwrap();
1798        assert_eq!(candidates["candidates"].as_array().unwrap().len(), 1);
1799        let provider_key =
1800            crate::gateway_identity::scoped_provider_key("gateway-account", "openclaw-local");
1801        assert_eq!(candidates["candidates"][0]["providerKey"], provider_key);
1802
1803        let imported = owner_app
1804            .clone()
1805            .oneshot(
1806                Request::post(format!("/v1/apps/{slug}/agents/import"))
1807                    .header("authorization", format!("Vifu {owner_credential}"))
1808                    .header("content-type", "application/json")
1809                    .body(Body::from(
1810                        serde_json::json!({
1811                            "gatewayId": "gateway-account",
1812                            "agentId": "guide",
1813                            "providerKey": provider_key,
1814                        })
1815                        .to_string(),
1816                    ))
1817                    .unwrap(),
1818            )
1819            .await
1820            .unwrap();
1821        assert_eq!(imported.status(), StatusCode::CREATED);
1822
1823        let retried = crate::db::consume_agent_gateway_machine_enrollment(
1824            &storage,
1825            &enrollment_hash,
1826            "gateway-account",
1827        )
1828        .await
1829        .unwrap();
1830        assert_eq!(retried.project_id, project_id);
1831
1832        let staging = owner_app
1833            .clone()
1834            .oneshot(
1835                Request::post(format!("/v1/apps/{slug}/deployments"))
1836                    .header("authorization", format!("Vifu {owner_credential}"))
1837                    .header("content-type", "application/json")
1838                    .body(Body::from(r#"{"name":"staging"}"#))
1839                    .unwrap(),
1840            )
1841            .await
1842            .unwrap();
1843        assert_eq!(staging.status(), StatusCode::CREATED);
1844        let staging_enrollment = owner_app
1845            .clone()
1846            .oneshot(
1847                Request::post(format!(
1848                    "/v1/apps/{slug}/deployments/staging/agent-gateway-enrollments"
1849                ))
1850                .header("authorization", format!("Vifu {owner_credential}"))
1851                .body(Body::empty())
1852                .unwrap(),
1853            )
1854            .await
1855            .unwrap();
1856        let body = to_bytes(staging_enrollment.into_body(), 64 * 1024)
1857            .await
1858            .unwrap();
1859        let staging_enrollment: Value = serde_json::from_slice(&body).unwrap();
1860        let staging_token = staging_enrollment["enrollmentToken"].as_str().unwrap();
1861        let staging_hash =
1862            crate::auth::hash_agent_gateway_enrollment(staging_token, &api_key_pepper);
1863        crate::db::consume_agent_gateway_machine_enrollment(
1864            &storage,
1865            &staging_hash,
1866            "gateway-account",
1867        )
1868        .await
1869        .unwrap();
1870        let runtime_config = owner_app
1871            .clone()
1872            .oneshot(
1873                Request::get("/v1/agent-gateway/runtime-config")
1874                    .header(
1875                        "authorization",
1876                        "Bearer vifu_gw_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1877                    )
1878                    .body(Body::empty())
1879                    .unwrap(),
1880            )
1881            .await
1882            .unwrap();
1883        let body = to_bytes(runtime_config.into_body(), 64 * 1024)
1884            .await
1885            .unwrap();
1886        let runtime_config: Value = serde_json::from_slice(&body).unwrap();
1887        assert_eq!(runtime_config["deployments"].as_array().unwrap().len(), 1);
1888        assert_eq!(runtime_config["deployments"][0]["deployment"], "staging");
1889        let project_gateways = owner_app
1890            .clone()
1891            .oneshot(
1892                Request::get(format!("/v1/apps/{slug}/agent-gateways"))
1893                    .header("authorization", format!("Vifu {owner_credential}"))
1894                    .body(Body::empty())
1895                    .unwrap(),
1896            )
1897            .await
1898            .unwrap();
1899        assert_eq!(project_gateways.status(), StatusCode::OK);
1900        let body = to_bytes(project_gateways.into_body(), 64 * 1024)
1901            .await
1902            .unwrap();
1903        let project_gateways: Value = serde_json::from_slice(&body).unwrap();
1904        assert_eq!(
1905            project_gateways["agentGateways"].as_array().unwrap().len(),
1906            1
1907        );
1908        assert_eq!(
1909            project_gateways["agentGateways"][0]["gatewayId"],
1910            "gateway-account"
1911        );
1912
1913        let project_agents = owner_app
1914            .clone()
1915            .oneshot(
1916                Request::get(format!("/v1/apps/{slug}/agents"))
1917                    .header("authorization", format!("Vifu {owner_credential}"))
1918                    .body(Body::empty())
1919                    .unwrap(),
1920            )
1921            .await
1922            .unwrap();
1923        assert_eq!(project_agents.status(), StatusCode::OK);
1924        let body = to_bytes(project_agents.into_body(), 64 * 1024)
1925            .await
1926            .unwrap();
1927        let project_agents: Value = serde_json::from_slice(&body).unwrap();
1928        assert_eq!(project_agents["agents"].as_array().unwrap().len(), 1);
1929        assert_eq!(project_agents["agents"][0]["gatewayId"], "gateway-account");
1930        assert!(!crate::db::runtime_deployment_allows_remote_invocation(
1931            &storage,
1932            project_id,
1933            "gateway-account",
1934        )
1935        .await
1936        .unwrap());
1937
1938        assert!(matches!(
1939            crate::db::consume_agent_gateway_machine_enrollment(
1940                &storage,
1941                &enrollment_hash,
1942                "gateway-replay",
1943            )
1944            .await,
1945            Err(ApiError::Unauthorized)
1946        ));
1947
1948        match storage {
1949            Storage::Postgres(pool) => pool.close().await,
1950            Storage::Sqlite(pool) => pool.close().await,
1951        }
1952        std::fs::remove_file(path).unwrap();
1953    }
1954
1955    #[tokio::test]
1956    async fn guest_gateway_bootstrap_is_idempotent_and_claimable() {
1957        let path = std::env::temp_dir().join(format!(
1958            "vifu-guest-project-{}.sqlite",
1959            uuid::Uuid::new_v4()
1960        ));
1961        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
1962            .await
1963            .unwrap();
1964        crate::db::migrate(&storage).await.unwrap();
1965        let mut config = Config::from_env().unwrap();
1966        config
1967            .apply_guest_bootstrap(true, std::time::Duration::from_secs(7 * 24 * 60 * 60), 10)
1968            .unwrap();
1969        let api_key_pepper = config.api_key_pepper.clone();
1970        let (owner_state, owner_credential) = state_with_storage_access_token_auth(
1971            config,
1972            storage.clone(),
1973            "user-guest-owner",
1974            vec![Operation::ProjectRead, Operation::ProjectWrite],
1975        )
1976        .await;
1977        let guest_app = app(owner_state);
1978        let gateway_credential =
1979            "vifu_gw_cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
1980        let machine = vifu_gateway::identity::MachineIdentity::generate().unwrap();
1981        crate::db::upsert_agent_gateway_machine(&storage, &machine.machine_id, &machine.public_key)
1982            .await
1983            .unwrap();
1984        let credential_hash =
1985            crate::auth::hash_agent_gateway_credential(gateway_credential, &api_key_pepper);
1986        crate::db::create_agent_gateway_authorization(
1987            &storage,
1988            crate::db::NewAgentGatewayAuthorization {
1989                gateway_id: "gateway-guest",
1990                machine_id: &machine.machine_id,
1991                owner_user_id: None,
1992                token_prefix: &gateway_credential.chars().take(20).collect::<String>(),
1993                token_hash: &credential_hash,
1994                token_expires_at: chrono::Utc::now() + chrono::Duration::days(180),
1995            },
1996        )
1997        .await
1998        .unwrap();
1999
2000        let created = guest_app
2001            .clone()
2002            .oneshot(
2003                Request::post("/v1/guest/bootstrap")
2004                    .header("authorization", format!("Bearer {gateway_credential}"))
2005                    .body(Body::empty())
2006                    .unwrap(),
2007            )
2008            .await
2009            .unwrap();
2010        assert_eq!(created.status(), StatusCode::CREATED);
2011        let body = to_bytes(created.into_body(), 64 * 1024).await.unwrap();
2012        let created: Value = serde_json::from_slice(&body).unwrap();
2013        let project_id = created["app"]["id"].as_str().unwrap();
2014        let project_slug = created["app"]["slug"].as_str().unwrap();
2015        let deployment_id = created["deployment"]["id"].as_str().unwrap();
2016        let api_key = created["apiKey"].as_str().unwrap();
2017        let claim_token = created["claimToken"].as_str().unwrap();
2018        assert!(api_key.starts_with("vifu_pk_"));
2019        assert!(claim_token.starts_with("vifu_gc_"));
2020        let guest_key_hash = crate::auth::hash_api_key(api_key, &api_key_pepper);
2021        let guest_key = crate::db::active_api_key_by_hash(&storage, &guest_key_hash)
2022            .await
2023            .unwrap();
2024        assert_eq!(
2025            guest_key.permissions.project,
2026            crate::models::ResourcePermission::Read
2027        );
2028        assert_eq!(created["app"].as_object().unwrap().len(), 3);
2029        assert_eq!(created["deployment"].as_object().unwrap().len(), 2);
2030        assert_eq!(created["deployment"]["name"], "development");
2031
2032        let repeated = guest_app
2033            .clone()
2034            .oneshot(
2035                Request::post("/v1/guest/bootstrap")
2036                    .header("authorization", format!("Bearer {gateway_credential}"))
2037                    .body(Body::empty())
2038                    .unwrap(),
2039            )
2040            .await
2041            .unwrap();
2042        assert_eq!(repeated.status(), StatusCode::OK);
2043        let body = to_bytes(repeated.into_body(), 64 * 1024).await.unwrap();
2044        let repeated: Value = serde_json::from_slice(&body).unwrap();
2045        assert_eq!(repeated["app"]["id"], project_id);
2046        assert_eq!(repeated["apiKey"], api_key);
2047        assert_eq!(repeated["claimToken"], claim_token);
2048
2049        let enrollment = guest_app
2050            .clone()
2051            .oneshot(
2052                Request::post("/v1/guest/agent-gateway-enrollments")
2053                    .header("authorization", format!("Bearer {api_key}"))
2054                    .body(Body::empty())
2055                    .unwrap(),
2056            )
2057            .await
2058            .unwrap();
2059        assert_eq!(enrollment.status(), StatusCode::CREATED);
2060        let body = to_bytes(enrollment.into_body(), 64 * 1024).await.unwrap();
2061        let enrollment: Value = serde_json::from_slice(&body).unwrap();
2062        let guest_enrollment_token = enrollment["enrollmentToken"].as_str().unwrap();
2063        assert!(guest_enrollment_token.starts_with("vifu_ge_"));
2064        assert_eq!(enrollment["deployment"], "development");
2065        let phone_gateway_credential =
2066            "vifu_gw_dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
2067        let guest_enrollment_hash =
2068            crate::auth::hash_agent_gateway_enrollment(guest_enrollment_token, &api_key_pepper);
2069        let phone_credential_hash =
2070            crate::auth::hash_agent_gateway_credential(phone_gateway_credential, &api_key_pepper);
2071        crate::db::consume_agent_gateway_enrollment(
2072            &storage,
2073            &guest_enrollment_hash,
2074            "gateway-phone",
2075            &phone_gateway_credential
2076                .chars()
2077                .take(20)
2078                .collect::<String>(),
2079            &phone_credential_hash,
2080        )
2081        .await
2082        .unwrap();
2083
2084        let runtime_config = guest_app
2085            .clone()
2086            .oneshot(
2087                Request::get("/v1/agent-gateway/runtime-config")
2088                    .header(
2089                        "authorization",
2090                        "Bearer vifu_gw_cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
2091                    )
2092                    .body(Body::empty())
2093                    .unwrap(),
2094            )
2095            .await
2096            .unwrap();
2097        assert_eq!(runtime_config.status(), StatusCode::OK);
2098        let body = to_bytes(runtime_config.into_body(), 64 * 1024)
2099            .await
2100            .unwrap();
2101        let runtime_config: Value = serde_json::from_slice(&body).unwrap();
2102        assert_eq!(
2103            runtime_config["deployments"][0]["projectSlug"],
2104            project_slug
2105        );
2106        assert_eq!(
2107            runtime_config["deployments"][0]["policies"]["remoteInvocation"],
2108            true
2109        );
2110
2111        let claimed = guest_app
2112            .clone()
2113            .oneshot(
2114                Request::post("/v1/guest/claim")
2115                    .header("authorization", format!("Vifu {owner_credential}"))
2116                    .header("content-type", "application/json")
2117                    .body(Body::from(format!(r#"{{"claimToken":"{claim_token}"}}"#)))
2118                    .unwrap(),
2119            )
2120            .await
2121            .unwrap();
2122        assert_eq!(claimed.status(), StatusCode::OK);
2123
2124        let expired_guest_access = guest_app
2125            .clone()
2126            .oneshot(
2127                Request::post("/v1/guest/agent-gateway-enrollments")
2128                    .header("authorization", format!("Bearer {api_key}"))
2129                    .body(Body::empty())
2130                    .unwrap(),
2131            )
2132            .await
2133            .unwrap();
2134        assert_eq!(expired_guest_access.status(), StatusCode::FORBIDDEN);
2135
2136        // Projects claimed before ownership migration shipped can still have
2137        // unowned desktop authorization metadata and guest-owned phone
2138        // credentials. Creating a peer enrollment must repair that state
2139        // without requiring the user to replay the claim URL.
2140        let project_uuid = uuid::Uuid::parse_str(project_id).unwrap();
2141        let legacy_guest_owner = format!("guest:{project_uuid}");
2142        match &storage {
2143            Storage::Postgres(pool) => {
2144                sqlx::query(
2145                    "UPDATE agent_gateway_authorizations SET owner_user_id = NULL
2146                     WHERE gateway_id = $1",
2147                )
2148                .bind("gateway-guest")
2149                .execute(pool)
2150                .await
2151                .unwrap();
2152                sqlx::query(
2153                    "UPDATE agent_gateway_credentials SET owner_user_id = $2
2154                     WHERE gateway_id = $1",
2155                )
2156                .bind("gateway-phone")
2157                .bind(&legacy_guest_owner)
2158                .execute(pool)
2159                .await
2160                .unwrap();
2161            }
2162            Storage::Sqlite(pool) => {
2163                sqlx::query(
2164                    "UPDATE agent_gateway_authorizations SET owner_user_id = NULL
2165                     WHERE gateway_id = $1",
2166                )
2167                .bind("gateway-guest")
2168                .execute(pool)
2169                .await
2170                .unwrap();
2171                sqlx::query(
2172                    "UPDATE agent_gateway_credentials SET owner_user_id = $2
2173                     WHERE gateway_id = $1",
2174                )
2175                .bind("gateway-phone")
2176                .bind(&legacy_guest_owner)
2177                .execute(pool)
2178                .await
2179                .unwrap();
2180            }
2181        }
2182
2183        let owned_enrollment = guest_app
2184            .clone()
2185            .oneshot(
2186                Request::post(format!(
2187                    "/v1/agent-gateway/deployments/{deployment_id}/enrollments"
2188                ))
2189                .header("authorization", format!("Bearer {gateway_credential}"))
2190                .body(Body::empty())
2191                .unwrap(),
2192            )
2193            .await
2194            .unwrap();
2195        assert_eq!(owned_enrollment.status(), StatusCode::CREATED);
2196        let body = to_bytes(owned_enrollment.into_body(), 64 * 1024)
2197            .await
2198            .unwrap();
2199        let owned_enrollment: Value = serde_json::from_slice(&body).unwrap();
2200        let owned_enrollment_hash = crate::auth::hash_agent_gateway_enrollment(
2201            owned_enrollment["enrollmentToken"].as_str().unwrap(),
2202            &api_key_pepper,
2203        );
2204        assert_eq!(
2205            crate::db::consume_agent_gateway_enrollment(
2206                &storage,
2207                &owned_enrollment_hash,
2208                "gateway-phone",
2209                &phone_gateway_credential
2210                    .chars()
2211                    .take(20)
2212                    .collect::<String>(),
2213                &phone_credential_hash,
2214            )
2215            .await
2216            .unwrap(),
2217            crate::db::AgentGatewayRegistration::Existing,
2218        );
2219
2220        let projects = guest_app
2221            .clone()
2222            .oneshot(
2223                Request::get("/v1/apps")
2224                    .header("authorization", format!("Vifu {owner_credential}"))
2225                    .body(Body::empty())
2226                    .unwrap(),
2227            )
2228            .await
2229            .unwrap();
2230        let body = to_bytes(projects.into_body(), 64 * 1024).await.unwrap();
2231        let projects: Value = serde_json::from_slice(&body).unwrap();
2232        assert_eq!(projects["apps"].as_array().unwrap().len(), 1);
2233        assert_eq!(projects["apps"][0]["id"], project_id);
2234
2235        match &storage {
2236            Storage::Postgres(pool) => {
2237                sqlx::query(
2238                    "UPDATE agent_gateway_credentials SET owner_user_id = $2
2239                     WHERE gateway_id = $1",
2240                )
2241                .bind("gateway-phone")
2242                .bind(&legacy_guest_owner)
2243                .execute(pool)
2244                .await
2245                .unwrap();
2246            }
2247            Storage::Sqlite(pool) => {
2248                sqlx::query(
2249                    "UPDATE agent_gateway_credentials SET owner_user_id = $2
2250                     WHERE gateway_id = $1",
2251                )
2252                .bind("gateway-phone")
2253                .bind(&legacy_guest_owner)
2254                .execute(pool)
2255                .await
2256                .unwrap();
2257            }
2258        }
2259
2260        let replayed = guest_app
2261            .clone()
2262            .oneshot(
2263                Request::post("/v1/guest/claim")
2264                    .header("authorization", format!("Vifu {owner_credential}"))
2265                    .header("content-type", "application/json")
2266                    .body(Body::from(format!(r#"{{"claimToken":"{claim_token}"}}"#)))
2267                    .unwrap(),
2268            )
2269            .await
2270            .unwrap();
2271        assert_eq!(replayed.status(), StatusCode::OK);
2272        let repaired_owner = match &storage {
2273            Storage::Postgres(pool) => sqlx::query_scalar::<_, Option<String>>(
2274                "SELECT owner_user_id FROM agent_gateway_credentials WHERE gateway_id = $1",
2275            )
2276            .bind("gateway-phone")
2277            .fetch_one(pool)
2278            .await
2279            .unwrap(),
2280            Storage::Sqlite(pool) => sqlx::query_scalar::<_, Option<String>>(
2281                "SELECT owner_user_id FROM agent_gateway_credentials WHERE gateway_id = $1",
2282            )
2283            .bind("gateway-phone")
2284            .fetch_one(pool)
2285            .await
2286            .unwrap(),
2287        };
2288        assert_eq!(repaired_owner.as_deref(), Some("user-guest-owner"));
2289
2290        let claim_token_hash = crate::auth::hash_guest_claim_token(claim_token, &api_key_pepper);
2291        assert!(matches!(
2292            crate::db::claim_guest_project(&storage, &claim_token_hash, "different-owner").await,
2293            Err(ApiError::Unauthorized)
2294        ));
2295
2296        match storage {
2297            Storage::Postgres(pool) => pool.close().await,
2298            Storage::Sqlite(pool) => pool.close().await,
2299        }
2300        std::fs::remove_file(path).unwrap();
2301    }
2302
2303    #[tokio::test]
2304    async fn deployment_admin_can_assign_a_legacy_project_to_an_account() {
2305        let path = std::env::temp_dir().join(format!(
2306            "vifu-project-ownership-migration-{}.sqlite",
2307            uuid::Uuid::new_v4()
2308        ));
2309        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
2310            .await
2311            .unwrap();
2312        crate::db::migrate(&storage).await.unwrap();
2313        let project_id = uuid::Uuid::new_v4();
2314        crate::db::create_project(
2315            &storage,
2316            crate::db::NewProject {
2317                id: project_id,
2318                owner_user_id: None,
2319                slug: "legacy-project",
2320                name: "Legacy project",
2321                description: None,
2322                gateway_id: "project-legacy-project",
2323                binding_ids: &[],
2324            },
2325        )
2326        .await
2327        .unwrap();
2328
2329        let config = Config::from_env().unwrap();
2330        let admin_key = config.admin_key.clone();
2331        let (account_state, account_credential) = state_with_storage_access_token_auth(
2332            config.clone(),
2333            storage.clone(),
2334            "user-123",
2335            vec![Operation::ProjectRead, Operation::ProjectWrite],
2336        )
2337        .await;
2338        let account_app = app(account_state);
2339        let denied = account_app
2340            .clone()
2341            .oneshot(
2342                Request::patch(format!("/v1/admin/app-ownership/{project_id}"))
2343                    .header("authorization", format!("Vifu {account_credential}"))
2344                    .header("content-type", "application/json")
2345                    .body(Body::from(r#"{"ownerUserId":"user-123"}"#))
2346                    .unwrap(),
2347            )
2348            .await
2349            .unwrap();
2350        assert_eq!(denied.status(), StatusCode::FORBIDDEN);
2351
2352        let admin_app = app(state_with_storage(config, storage.clone()));
2353        let ownership = admin_app
2354            .clone()
2355            .oneshot(
2356                Request::get("/v1/admin/app-ownership")
2357                    .header("authorization", format!("Bearer {admin_key}"))
2358                    .body(Body::empty())
2359                    .unwrap(),
2360            )
2361            .await
2362            .unwrap();
2363        assert_eq!(ownership.status(), StatusCode::OK);
2364        let body = to_bytes(ownership.into_body(), 64 * 1024).await.unwrap();
2365        let payload: Value = serde_json::from_slice(&body).unwrap();
2366        assert_eq!(payload["apps"][0]["ownerUserId"], Value::Null);
2367
2368        let assigned = admin_app
2369            .oneshot(
2370                Request::patch(format!("/v1/admin/app-ownership/{project_id}"))
2371                    .header("authorization", format!("Bearer {admin_key}"))
2372                    .header("content-type", "application/json")
2373                    .body(Body::from(r#"{"ownerUserId":"user-123"}"#))
2374                    .unwrap(),
2375            )
2376            .await
2377            .unwrap();
2378        assert_eq!(assigned.status(), StatusCode::OK);
2379
2380        let visible = account_app
2381            .oneshot(
2382                Request::get("/v1/apps")
2383                    .header("authorization", format!("Vifu {account_credential}"))
2384                    .body(Body::empty())
2385                    .unwrap(),
2386            )
2387            .await
2388            .unwrap();
2389        let body = to_bytes(visible.into_body(), 64 * 1024).await.unwrap();
2390        let payload: Value = serde_json::from_slice(&body).unwrap();
2391        assert_eq!(payload["apps"].as_array().unwrap().len(), 1);
2392        assert_eq!(payload["apps"][0]["slug"], "legacy-project");
2393        assert!(payload["apps"][0].get("ownerUserId").is_none());
2394
2395        match storage {
2396            Storage::Postgres(pool) => pool.close().await,
2397            Storage::Sqlite(pool) => pool.close().await,
2398        }
2399        std::fs::remove_file(path).unwrap();
2400    }
2401
2402    #[tokio::test]
2403    async fn unknown_routes_use_the_json_error_contract() {
2404        let config = Config::from_env().unwrap();
2405        let pool = PgPoolOptions::new()
2406            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2407            .unwrap();
2408        let response = app(state(config, pool))
2409            .oneshot(Request::get("/missing").body(Body::empty()).unwrap())
2410            .await
2411            .unwrap();
2412        assert_eq!(response.status(), StatusCode::NOT_FOUND);
2413    }
2414
2415    #[tokio::test]
2416    async fn api_key_mutation_routes_require_admin_authority() {
2417        let config = Config::from_env().unwrap();
2418        let pool = PgPoolOptions::new()
2419            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2420            .unwrap();
2421        let key_id = uuid::Uuid::new_v4();
2422
2423        let revoke = app(state(config.clone(), pool.clone()))
2424            .oneshot(
2425                Request::post(format!("/v1/api-keys/{key_id}/revoke"))
2426                    .body(Body::empty())
2427                    .unwrap(),
2428            )
2429            .await
2430            .unwrap();
2431        assert_eq!(revoke.status(), StatusCode::UNAUTHORIZED);
2432
2433        let update = app(state(config.clone(), pool.clone()))
2434            .oneshot(
2435                Request::patch(format!("/v1/api-keys/{key_id}"))
2436                    .header("content-type", "application/json")
2437                    .body(Body::from(r#"{"agentScope":{"mode":"all"}}"#))
2438                    .unwrap(),
2439            )
2440            .await
2441            .unwrap();
2442        assert_eq!(update.status(), StatusCode::UNAUTHORIZED);
2443
2444        let delete = app(state(config, pool))
2445            .oneshot(
2446                Request::delete(format!("/v1/api-keys/{key_id}"))
2447                    .body(Body::empty())
2448                    .unwrap(),
2449            )
2450            .await
2451            .unwrap();
2452        assert_eq!(delete.status(), StatusCode::UNAUTHORIZED);
2453    }
2454
2455    #[tokio::test]
2456    async fn project_api_key_creation_preserves_selected_agent_scope() {
2457        let (storage, path) = temp_sqlite_storage("selected-api-key-scope").await;
2458        let project_id = uuid::Uuid::new_v4();
2459        let profile_id = uuid::Uuid::new_v4();
2460        crate::db::create_project(
2461            &storage,
2462            crate::db::NewProject {
2463                id: project_id,
2464                owner_user_id: None,
2465                slug: "selected-scope",
2466                name: "Selected scope",
2467                description: None,
2468                gateway_id: "project-selected-scope",
2469                binding_ids: &[],
2470            },
2471        )
2472        .await
2473        .unwrap();
2474        crate::db::create_profile(
2475            &storage,
2476            profile_id,
2477            project_id,
2478            "selected-agent",
2479            "Selected agent",
2480            None,
2481        )
2482        .await
2483        .unwrap();
2484
2485        let config = Config::from_env().unwrap();
2486        let admin_key = config.admin_key.clone();
2487        let router = app(state_with_storage(config, storage.clone()));
2488        let created = router
2489            .clone()
2490            .oneshot(
2491                Request::post("/v1/apps/selected-scope/api-keys")
2492                    .header("authorization", format!("Bearer {admin_key}"))
2493                    .header("content-type", "application/json")
2494                    .body(Body::from(
2495                        json!({
2496                            "projectId": project_id,
2497                            "name": "Selected key",
2498                            "agentScope": {
2499                                "mode": "selected",
2500                                "profileIds": [profile_id],
2501                            },
2502                        })
2503                        .to_string(),
2504                    ))
2505                    .unwrap(),
2506            )
2507            .await
2508            .unwrap();
2509        assert_eq!(created.status(), StatusCode::CREATED);
2510        let created = response_json(created).await;
2511        assert_eq!(created["apiKey"]["agentScope"]["mode"], "selected");
2512        assert_eq!(
2513            created["apiKey"]["agentScope"]["profileIds"][0],
2514            profile_id.to_string()
2515        );
2516
2517        let listed = router
2518            .oneshot(
2519                Request::get("/v1/apps/selected-scope/api-keys")
2520                    .header("authorization", format!("Bearer {admin_key}"))
2521                    .body(Body::empty())
2522                    .unwrap(),
2523            )
2524            .await
2525            .unwrap();
2526        assert_eq!(listed.status(), StatusCode::OK);
2527        let listed = response_json(listed).await;
2528        assert_eq!(listed["apiKeys"][0]["agentScope"]["mode"], "selected");
2529        assert_eq!(
2530            listed["apiKeys"][0]["agentScope"]["profileIds"][0],
2531            profile_id.to_string()
2532        );
2533
2534        close_temp_storage(storage, path).await;
2535    }
2536
2537    #[tokio::test]
2538    async fn project_profile_delete_route_is_registered() {
2539        let config = Config::from_env().unwrap();
2540        let pool = PgPoolOptions::new()
2541            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2542            .unwrap();
2543        let profile_id = uuid::Uuid::new_v4();
2544        let response = app(state(config, pool))
2545            .oneshot(
2546                Request::delete(format!("/v1/apps/test/profiles/{profile_id}"))
2547                    .body(Body::empty())
2548                    .unwrap(),
2549            )
2550            .await
2551            .unwrap();
2552
2553        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
2554    }
2555
2556    #[tokio::test]
2557    async fn project_embeddings_route_is_registered() {
2558        let config = Config::from_env().unwrap();
2559        let pool = PgPoolOptions::new()
2560            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2561            .unwrap();
2562        let response = app(state(config, pool))
2563            .oneshot(
2564                Request::post("/test/v1/embeddings")
2565                    .header("content-type", "application/json")
2566                    .body(Body::from(r#"{"model":"guide","input":"hello"}"#))
2567                    .unwrap(),
2568            )
2569            .await
2570            .unwrap();
2571
2572        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
2573    }
2574
2575    #[tokio::test]
2576    async fn project_trace_feedback_route_is_registered_and_authenticated() {
2577        let config = Config::from_env().unwrap();
2578        let pool = PgPoolOptions::new()
2579            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2580            .unwrap();
2581        let invocation_id = uuid::Uuid::new_v4();
2582        let response = app(state(config, pool))
2583            .oneshot(
2584                Request::post(format!("/test/v1/traces/{invocation_id}/feedback"))
2585                    .header("content-type", "application/json")
2586                    .body(Body::from(
2587                        r#"{"event":"OUTPUT_ACCEPTED","outcome":"fail","path":"$.action"}"#,
2588                    ))
2589                    .unwrap(),
2590            )
2591            .await
2592            .unwrap();
2593
2594        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
2595    }
2596
2597    #[tokio::test]
2598    async fn project_trace_feedback_rejects_oversized_body_before_authentication() {
2599        let config = Config::from_env().unwrap();
2600        let pool = PgPoolOptions::new()
2601            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2602            .unwrap();
2603        let invocation_id = uuid::Uuid::new_v4();
2604        let response = app(state(config, pool))
2605            .oneshot(
2606                Request::post(format!("/test/v1/traces/{invocation_id}/feedback"))
2607                    .header("content-type", "application/json")
2608                    .body(Body::from("x".repeat(16 * 1024 + 1)))
2609                    .unwrap(),
2610            )
2611            .await
2612            .unwrap();
2613
2614        assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
2615    }
2616
2617    #[tokio::test]
2618    async fn selected_project_key_only_observes_its_profile_traces() {
2619        let (storage, path) = temp_sqlite_storage("selected-trace-scope").await;
2620        let config = Config::from_env().unwrap();
2621        let project_id = create_test_project(&storage, "trace-auth", "gateway-trace-auth").await;
2622        let allowed_profile_id = uuid::Uuid::new_v4();
2623        let other_profile_id = uuid::Uuid::new_v4();
2624        crate::db::create_profile(
2625            &storage,
2626            allowed_profile_id,
2627            project_id,
2628            "allowed-agent",
2629            "Allowed agent",
2630            None,
2631        )
2632        .await
2633        .unwrap();
2634        crate::db::create_profile(
2635            &storage,
2636            other_profile_id,
2637            project_id,
2638            "other-agent",
2639            "Other agent",
2640            None,
2641        )
2642        .await
2643        .unwrap();
2644
2645        let mut trace_ids = Vec::new();
2646        for profile_id in [Some(allowed_profile_id), Some(other_profile_id), None] {
2647            let request_id = uuid::Uuid::new_v4();
2648            let trace_id = crate::db::create_trace(
2649                &storage,
2650                crate::db::NewTrace {
2651                    request_id,
2652                    endpoint_id: None,
2653                    project_id: Some(project_id),
2654                    gateway_session_id: None,
2655                    profile_id,
2656                    profile_version_id: None,
2657                    operation: "runtime.invoke",
2658                    provider_key: None,
2659                    capability_kind: Some("chat"),
2660                    selection_key: None,
2661                    request: &json!({}),
2662                },
2663            )
2664            .await
2665            .unwrap();
2666            trace_ids.push((trace_id, request_id));
2667        }
2668
2669        let raw_key = "vifu_pk_selected_trace_scope_test";
2670        let key_hash = crate::auth::hash_api_key(raw_key, &config.api_key_pepper);
2671        let permissions = crate::models::ApiKeyPermissions {
2672            project: crate::models::ResourcePermission::Read,
2673            ..Default::default()
2674        };
2675        crate::db::create_api_key(
2676            &storage,
2677            crate::db::NewApiKey {
2678                id: uuid::Uuid::new_v4(),
2679                project_id,
2680                name: "Selected trace reader",
2681                agent_scope: &crate::models::ApiKeyAgentScope::Selected {
2682                    profile_ids: vec![allowed_profile_id],
2683                },
2684                permissions: &permissions,
2685                key_prefix: "vifu_pk_selected_t",
2686                key_hash: &key_hash,
2687            },
2688        )
2689        .await
2690        .unwrap();
2691
2692        let no_endpoint_raw_key = "vifu_pk_selected_trace_no_endpoint_access";
2693        let no_endpoint_key_hash =
2694            crate::auth::hash_api_key(no_endpoint_raw_key, &config.api_key_pepper);
2695        let no_endpoint_permissions = crate::models::ApiKeyPermissions {
2696            chat_completions: crate::models::EndpointPermission::None,
2697            embeddings: crate::models::EndpointPermission::None,
2698            speech: crate::models::EndpointPermission::None,
2699            transcriptions: crate::models::EndpointPermission::None,
2700            realtime: crate::models::EndpointPermission::None,
2701            runtime: crate::models::EndpointPermission::None,
2702            agents: crate::models::ResourcePermission::None,
2703            project: crate::models::ResourcePermission::Read,
2704        };
2705        crate::db::create_api_key(
2706            &storage,
2707            crate::db::NewApiKey {
2708                id: uuid::Uuid::new_v4(),
2709                project_id,
2710                name: "Trace reader without endpoint access",
2711                agent_scope: &crate::models::ApiKeyAgentScope::Selected {
2712                    profile_ids: vec![allowed_profile_id],
2713                },
2714                permissions: &no_endpoint_permissions,
2715                key_prefix: "vifu_pk_selected_n",
2716                key_hash: &no_endpoint_key_hash,
2717            },
2718        )
2719        .await
2720        .unwrap();
2721
2722        let runtime_app = app(state_with_storage(config.clone(), storage.clone()));
2723        let selected_list = runtime_app
2724            .clone()
2725            .oneshot(
2726                Request::get("/v1/apps/trace-auth/traces")
2727                    .header("authorization", format!("Bearer {raw_key}"))
2728                    .body(Body::empty())
2729                    .unwrap(),
2730            )
2731            .await
2732            .unwrap();
2733        assert_eq!(selected_list.status(), StatusCode::OK);
2734        let selected_list = response_json(selected_list).await;
2735        let traces = selected_list["traces"].as_array().unwrap();
2736        assert_eq!(traces.len(), 1);
2737        assert_eq!(traces[0]["id"], trace_ids[0].0.to_string());
2738
2739        let exact_allowed = runtime_app
2740            .clone()
2741            .oneshot(
2742                Request::get(format!(
2743                    "/v1/apps/trace-auth/traces?requestId={}&limit=1",
2744                    trace_ids[0].1
2745                ))
2746                .header("authorization", format!("Bearer {raw_key}"))
2747                .body(Body::empty())
2748                .unwrap(),
2749            )
2750            .await
2751            .unwrap();
2752        assert_eq!(exact_allowed.status(), StatusCode::OK);
2753        assert_eq!(
2754            response_json(exact_allowed).await["traces"]
2755                .as_array()
2756                .unwrap()
2757                .len(),
2758            1
2759        );
2760        let exact_hidden = runtime_app
2761            .clone()
2762            .oneshot(
2763                Request::get(format!(
2764                    "/v1/apps/trace-auth/traces?requestId={}&limit=1",
2765                    trace_ids[1].1
2766                ))
2767                .header("authorization", format!("Bearer {raw_key}"))
2768                .body(Body::empty())
2769                .unwrap(),
2770            )
2771            .await
2772            .unwrap();
2773        assert_eq!(exact_hidden.status(), StatusCode::OK);
2774        assert!(response_json(exact_hidden).await["traces"]
2775            .as_array()
2776            .unwrap()
2777            .is_empty());
2778
2779        let exact_trace_allowed = runtime_app
2780            .clone()
2781            .oneshot(
2782                Request::get(format!(
2783                    "/v1/apps/trace-auth/traces?traceId={}&limit=1",
2784                    trace_ids[0].0
2785                ))
2786                .header("authorization", format!("Bearer {raw_key}"))
2787                .body(Body::empty())
2788                .unwrap(),
2789            )
2790            .await
2791            .unwrap();
2792        assert_eq!(exact_trace_allowed.status(), StatusCode::OK);
2793        assert_eq!(
2794            response_json(exact_trace_allowed).await["traces"][0]["id"],
2795            trace_ids[0].0.to_string()
2796        );
2797        let exact_trace_hidden = runtime_app
2798            .clone()
2799            .oneshot(
2800                Request::get(format!(
2801                    "/v1/apps/trace-auth/traces?traceId={}&limit=1",
2802                    trace_ids[1].0
2803                ))
2804                .header("authorization", format!("Bearer {raw_key}"))
2805                .body(Body::empty())
2806                .unwrap(),
2807            )
2808            .await
2809            .unwrap();
2810        assert_eq!(exact_trace_hidden.status(), StatusCode::OK);
2811        assert!(response_json(exact_trace_hidden).await["traces"]
2812            .as_array()
2813            .unwrap()
2814            .is_empty());
2815
2816        for suffix in ["spans", "scores"] {
2817            let allowed = runtime_app
2818                .clone()
2819                .oneshot(
2820                    Request::get(format!(
2821                        "/v1/apps/trace-auth/traces/{}/{suffix}",
2822                        trace_ids[0].0
2823                    ))
2824                    .header("authorization", format!("Bearer {raw_key}"))
2825                    .body(Body::empty())
2826                    .unwrap(),
2827                )
2828                .await
2829                .unwrap();
2830            assert_eq!(allowed.status(), StatusCode::OK);
2831            for (trace_id, _) in &trace_ids[1..] {
2832                let hidden = runtime_app
2833                    .clone()
2834                    .oneshot(
2835                        Request::get(format!("/v1/apps/trace-auth/traces/{trace_id}/{suffix}"))
2836                            .header("authorization", format!("Bearer {raw_key}"))
2837                            .body(Body::empty())
2838                            .unwrap(),
2839                    )
2840                    .await
2841                    .unwrap();
2842                assert_eq!(hidden.status(), StatusCode::NOT_FOUND);
2843            }
2844        }
2845
2846        for (_, request_id) in &trace_ids[1..] {
2847            let denied_feedback = runtime_app
2848                .clone()
2849                .oneshot(
2850                    Request::post(format!("/trace-auth/v1/traces/{request_id}/feedback"))
2851                        .header("authorization", format!("Bearer {raw_key}"))
2852                        .header("content-type", "application/json")
2853                        .body(Body::from(
2854                            r#"{"event":"OUTPUT_ACCEPTED","outcome":"pass"}"#,
2855                        ))
2856                        .unwrap(),
2857                )
2858                .await
2859                .unwrap();
2860            assert_eq!(denied_feedback.status(), StatusCode::FORBIDDEN);
2861        }
2862
2863        let denied_without_endpoint_access = runtime_app
2864            .clone()
2865            .oneshot(
2866                Request::post(format!("/trace-auth/v1/traces/{}/feedback", trace_ids[0].1))
2867                    .header("authorization", format!("Bearer {no_endpoint_raw_key}"))
2868                    .header("content-type", "application/json")
2869                    .body(Body::from(
2870                        r#"{"event":"OUTPUT_ACCEPTED","outcome":"pass"}"#,
2871                    ))
2872                    .unwrap(),
2873            )
2874            .await
2875            .unwrap();
2876        assert_eq!(
2877            denied_without_endpoint_access.status(),
2878            StatusCode::FORBIDDEN
2879        );
2880
2881        let admin_list = runtime_app
2882            .clone()
2883            .oneshot(
2884                Request::get("/v1/apps/trace-auth/traces")
2885                    .header("authorization", admin_authorization(&config))
2886                    .body(Body::empty())
2887                    .unwrap(),
2888            )
2889            .await
2890            .unwrap();
2891        assert_eq!(admin_list.status(), StatusCode::OK);
2892        assert_eq!(
2893            response_json(admin_list).await["traces"]
2894                .as_array()
2895                .unwrap()
2896                .len(),
2897            3
2898        );
2899
2900        drop(runtime_app);
2901        close_temp_storage(storage, path).await;
2902    }
2903
2904    #[tokio::test]
2905    async fn project_agent_and_provider_routes_require_admin_authority() {
2906        let config = Config::from_env().unwrap();
2907        let pool = PgPoolOptions::new()
2908            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
2909            .unwrap();
2910        let requests = [
2911            Request::get("/v1/provider-catalog")
2912                .body(Body::empty())
2913                .unwrap(),
2914            Request::get("/v1/apps/test/providers")
2915                .body(Body::empty())
2916                .unwrap(),
2917            Request::post("/v1/apps/test/providers/import")
2918                .header("content-type", "application/json")
2919                .body(Body::from(
2920                    r#"{
2921                        "providerKey":"demo-openai",
2922                        "name":"Demo provider",
2923                        "providerType":"openai-compatible",
2924                        "baseUrl":"http://127.0.0.1:9999/v1"
2925                    }"#,
2926                ))
2927                .unwrap(),
2928            Request::get("/v1/apps/test/agent-candidates")
2929                .body(Body::empty())
2930                .unwrap(),
2931            Request::post("/v1/apps/test/agents/import")
2932                .header("content-type", "application/json")
2933                .body(Body::from(
2934                    r#"{"gatewayId":"gateway","agentId":"guide","providerKey":"openclaw"}"#,
2935                ))
2936                .unwrap(),
2937            Request::post(format!(
2938                "/v1/apps/test/agents/{}/restore",
2939                uuid::Uuid::new_v4()
2940            ))
2941            .header("content-type", "application/json")
2942            .body(Body::from("{}"))
2943            .unwrap(),
2944            Request::post("/v1/apps/test/profiles/import")
2945                .header("content-type", "application/json")
2946                .body(Body::from(
2947                    r#"{
2948                        "archiveId":"profile-1",
2949                        "name":"Guide",
2950                        "activeVersionId":"version-1",
2951                        "versions":[{"archiveId":"version-1"}]
2952                    }"#,
2953                ))
2954                .unwrap(),
2955        ];
2956
2957        for request in requests {
2958            let response = app(state(config.clone(), pool.clone()))
2959                .oneshot(request)
2960                .await
2961                .unwrap();
2962            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
2963        }
2964    }
2965
2966    #[tokio::test]
2967    async fn project_provider_catalog_reports_only_its_gateway_available_providers() {
2968        let (storage, path) = temp_sqlite_storage("provider-catalog").await;
2969        let config = Config::from_env().unwrap();
2970        let admin = admin_authorization(&config);
2971        create_test_project(&storage, "provider-catalog-project", "gateway-project").await;
2972        open_provider_gateway_session(&storage, "gateway-project").await;
2973        crate::db::open_agent_gateway_session(
2974            &storage,
2975            "gateway-other",
2976            None,
2977            &json!([{
2978                "id": "other-agent",
2979                "name": "Other Agent",
2980                "metadata": {
2981                    "providerKey": "other-openai",
2982                    "providerType": "vifu-runtime",
2983                    "localProviderType": "openai-compatible",
2984                    "capabilities": ["chat"]
2985                }
2986            }]),
2987            &json!({
2988                "providers": [{"id": "other-openai", "type": "vifu-runtime"}]
2989            }),
2990        )
2991        .await
2992        .unwrap();
2993
2994        let runtime_app = app(state_with_storage(config, storage.clone()));
2995        let response = runtime_app
2996            .oneshot(
2997                Request::get("/v1/apps/provider-catalog-project/provider-catalog")
2998                    .header("authorization", admin)
2999                    .body(Body::empty())
3000                    .unwrap(),
3001            )
3002            .await
3003            .unwrap();
3004        assert_eq!(response.status(), StatusCode::OK);
3005        let payload = response_json(response).await;
3006        let providers = payload["custom"].as_array().unwrap();
3007        let local_openai =
3008            crate::gateway_identity::scoped_provider_key("gateway-project", "local-openai");
3009        let local_llama =
3010            crate::gateway_identity::scoped_provider_key("gateway-project", "local-llama");
3011        let local_whisper =
3012            crate::gateway_identity::scoped_provider_key("gateway-project", "local-whisper");
3013        let other_openai =
3014            crate::gateway_identity::scoped_provider_key("gateway-other", "other-openai");
3015        let keys = providers
3016            .iter()
3017            .map(|provider| provider["providerKey"].as_str().unwrap())
3018            .collect::<Vec<_>>();
3019        assert!(keys.contains(&local_openai.as_str()));
3020        assert!(keys.contains(&local_llama.as_str()));
3021        assert!(keys.contains(&local_whisper.as_str()));
3022        assert!(!keys.contains(&other_openai.as_str()));
3023        let openai = providers
3024            .iter()
3025            .find(|provider| provider["providerKey"] == local_openai)
3026            .unwrap();
3027        assert_eq!(openai["providerType"], "vifu-runtime");
3028        assert_eq!(openai["status"], "online");
3029        assert_eq!(openai["config"]["gatewayId"], "gateway-project");
3030        assert_eq!(openai["config"]["runtimeProviderKey"], "local-openai");
3031        assert_eq!(openai["config"]["localProviderType"], "openai-compatible");
3032        assert_eq!(
3033            openai["config"]["capabilities"],
3034            json!(["chat", "embedding"])
3035        );
3036
3037        close_temp_storage(storage, path).await;
3038    }
3039
3040    #[tokio::test]
3041    async fn available_gateway_provider_assignment_stores_only_project_binding() {
3042        let (storage, path) = temp_sqlite_storage("provider-assign").await;
3043        let config = Config::from_env().unwrap();
3044        let admin = admin_authorization(&config);
3045        create_test_project(&storage, "provider-assign-project", "gateway-project").await;
3046        open_provider_gateway_session(&storage, "gateway-project").await;
3047        let runtime_app = app(state_with_storage(config, storage.clone()));
3048        let provider_key =
3049            crate::gateway_identity::scoped_provider_key("gateway-project", "local-openai");
3050
3051        let response = runtime_app
3052            .clone()
3053            .oneshot(
3054                Request::post("/v1/apps/provider-assign-project/providers")
3055                    .header("authorization", admin.clone())
3056                    .header("content-type", "application/json")
3057                    .body(Body::from(
3058                        json!({
3059                            "source": {"kind": "custom", "key": provider_key.clone()},
3060                            "name": "Local OpenAI"
3061                        })
3062                        .to_string(),
3063                    ))
3064                    .unwrap(),
3065            )
3066            .await
3067            .unwrap();
3068        assert_eq!(response.status(), StatusCode::CREATED);
3069        let payload = response_json(response).await;
3070        assert_eq!(payload["provider"]["providerKey"], provider_key);
3071        assert_eq!(payload["provider"]["sourceKind"], "custom");
3072        assert_eq!(payload["provider"]["sourceKey"], provider_key);
3073        assert_eq!(payload["provider"]["status"], "online");
3074        assert_eq!(payload["provider"]["baseUrl"], "");
3075        assert_eq!(payload["addedAgents"], 1);
3076
3077        let stored = crate::db::get_provider_connection_secret_by_key(
3078            &storage,
3079            "provider-assign-project",
3080            &provider_key,
3081        )
3082        .await
3083        .unwrap();
3084        assert_eq!(stored.source_kind, "custom");
3085        assert_eq!(stored.source_key, provider_key);
3086        assert!(stored.base_url.is_empty());
3087        assert_eq!(stored.config, json!({}));
3088        assert!(stored.secret_keys.is_empty());
3089        assert_eq!(custom_provider_row_count(&storage).await, 0);
3090
3091        close_temp_storage(storage, path).await;
3092    }
3093
3094    #[tokio::test]
3095    async fn runtime_provider_settings_activate_a_new_primary_release() {
3096        let (storage, path) = temp_sqlite_storage("provider-runtime-sync").await;
3097        let config = Config::from_env().unwrap();
3098        let admin = admin_authorization(&config);
3099        create_test_project(&storage, "provider-runtime-sync", "gateway-runtime-sync").await;
3100        open_provider_gateway_session(&storage, "gateway-runtime-sync").await;
3101        let runtime_app = app(state_with_storage(config, storage.clone()));
3102        let provider_key =
3103            crate::gateway_identity::scoped_provider_key("gateway-runtime-sync", "local-llama");
3104
3105        let assigned = runtime_app
3106            .clone()
3107            .oneshot(
3108                Request::post("/v1/apps/provider-runtime-sync/providers")
3109                    .header("authorization", admin.clone())
3110                    .header("content-type", "application/json")
3111                    .body(Body::from(
3112                        json!({"source":{"kind":"custom","key": provider_key.clone()}}).to_string(),
3113                    ))
3114                    .unwrap(),
3115            )
3116            .await
3117            .unwrap();
3118        assert_eq!(assigned.status(), StatusCode::CREATED);
3119
3120        let published = runtime_app
3121            .clone()
3122            .oneshot(
3123                Request::post("/v1/apps/provider-runtime-sync/runtime-releases")
3124                    .header("authorization", admin.clone())
3125                    .header("content-type", "application/json")
3126                    .body(Body::from(
3127                        r#"{
3128                            "settings": {
3129                                "schemaVersion": 1,
3130                                "projectId": "provider-runtime-sync",
3131                                "providers": [{
3132                                    "id": "local-llama",
3133                                    "providerType": "llama",
3134                                    "capabilities": ["chat"]
3135                                }],
3136                                "agents": [{
3137                                    "id": "guide",
3138                                    "name": "Guide",
3139                                    "provider": "local-llama",
3140                                    "capabilities": ["chat"]
3141                                }],
3142                                "endpoints": [{
3143                                    "name": "guide",
3144                                    "agent": "guide",
3145                                    "capability": "chat",
3146                                    "timeoutMs": 30000
3147                                }],
3148                                "metadata": {}
3149                            }
3150                        }"#,
3151                    ))
3152                    .unwrap(),
3153            )
3154            .await
3155            .unwrap();
3156        assert_eq!(published.status(), StatusCode::CREATED);
3157        let activated = runtime_app
3158            .clone()
3159            .oneshot(
3160                Request::post(
3161                    "/v1/apps/provider-runtime-sync/deployments/development/runtime-releases/1/activate",
3162                )
3163                .header("authorization", admin.clone())
3164                .body(Body::empty())
3165                .unwrap(),
3166            )
3167            .await
3168            .unwrap();
3169        assert_eq!(activated.status(), StatusCode::OK);
3170
3171        let updated = runtime_app
3172            .oneshot(
3173                Request::patch(format!(
3174                    "/v1/apps/provider-runtime-sync/providers/{provider_key}"
3175                ))
3176                .header("authorization", admin)
3177                .header("content-type", "application/json")
3178                .body(Body::from(
3179                    r#"{
3180                        "config": {
3181                            "settings": {
3182                                "generation": {"maxTokens": 96, "temperature": 0.3}
3183                            },
3184                            "resources": {}
3185                        }
3186                    }"#,
3187                ))
3188                .unwrap(),
3189            )
3190            .await
3191            .unwrap();
3192        let updated_status = updated.status();
3193        let payload = response_json(updated).await;
3194        assert_eq!(updated_status, StatusCode::OK, "{payload}");
3195        assert_eq!(payload["runtimeSync"]["runtimeRelease"]["version"], 2);
3196        assert_eq!(
3197            payload["runtimeSync"]["deployment"]["activeReleaseVersion"],
3198            2
3199        );
3200        assert_eq!(
3201            payload["runtimeSync"]["runtimeRelease"]["manifest"]["providers"][0]["settings"]
3202                ["generation"]["maxTokens"],
3203            96
3204        );
3205        assert_eq!(
3206            payload["runtimeSync"]["runtimeRelease"]["manifest"]["agents"][0]["metadata"]
3207                ["generation"]["temperature"],
3208            0.3
3209        );
3210
3211        close_temp_storage(storage, path).await;
3212    }
3213
3214    #[tokio::test]
3215    async fn project_local_openai_provider_stores_project_settings_and_probes_live() {
3216        let (storage, path) = temp_sqlite_storage("project-local-openai").await;
3217        let config = Config::from_env().unwrap();
3218        let admin = admin_authorization(&config);
3219        create_test_project(&storage, "project-local-openai", "gateway-project").await;
3220        let (base_url, server) = openai_probe_mock().await;
3221        let runtime_app = app(state_with_storage(config, storage.clone()));
3222
3223        let response = runtime_app
3224            .oneshot(
3225                Request::post("/v1/apps/project-local-openai/providers")
3226                    .header("authorization", admin)
3227                    .header("content-type", "application/json")
3228                    .body(Body::from(format!(
3229                        r#"{{
3230                            "source": {{"kind": "registry", "key": "openai-compatible"}},
3231                            "name": "Project OpenAI",
3232                            "baseUrl": "{base_url}",
3233                            "config": {{"organization": "test-org"}},
3234                            "secrets": {{"token": "local-test-token"}}
3235                        }}"#
3236                    )))
3237                    .unwrap(),
3238            )
3239            .await
3240            .unwrap();
3241        assert_eq!(response.status(), StatusCode::CREATED);
3242        let payload = response_json(response).await;
3243        assert_eq!(payload["provider"]["providerKey"], "openai-compatible");
3244        assert_eq!(payload["provider"]["sourceKind"], "registry");
3245        assert_eq!(payload["provider"]["sourceKey"], "openai-compatible");
3246        assert_eq!(payload["provider"]["status"], "online");
3247
3248        let stored = crate::db::get_provider_connection_secret_by_key(
3249            &storage,
3250            "project-local-openai",
3251            "openai-compatible",
3252        )
3253        .await
3254        .unwrap();
3255        assert_eq!(stored.source_kind, "registry");
3256        assert_eq!(stored.source_key, "openai-compatible");
3257        assert_eq!(stored.provider_type, "openai-compatible");
3258        assert_eq!(stored.base_url, base_url);
3259        assert_eq!(stored.config, json!({"organization": "test-org"}));
3260        assert_eq!(stored.secret_keys, vec!["token".to_string()]);
3261        assert_eq!(stored.display_secret.as_deref(), Some("****oken"));
3262        assert_eq!(custom_provider_row_count(&storage).await, 0);
3263
3264        server.abort();
3265        close_temp_storage(storage, path).await;
3266    }
3267
3268    #[tokio::test]
3269    async fn assigned_gateway_provider_test_reports_offline_when_gateway_disconnects() {
3270        let (storage, path) = temp_sqlite_storage("provider-offline").await;
3271        let config = Config::from_env().unwrap();
3272        let admin = admin_authorization(&config);
3273        create_test_project(&storage, "provider-offline-project", "gateway-project").await;
3274        let session_id = open_provider_gateway_session(&storage, "gateway-project").await;
3275        let runtime_app = app(state_with_storage(config, storage.clone()));
3276        let provider_key =
3277            crate::gateway_identity::scoped_provider_key("gateway-project", "local-openai");
3278
3279        let assigned = runtime_app
3280            .clone()
3281            .oneshot(
3282                Request::post("/v1/apps/provider-offline-project/providers")
3283                    .header("authorization", admin.clone())
3284                    .header("content-type", "application/json")
3285                    .body(Body::from(
3286                        json!({
3287                            "source": {"kind": "custom", "key": provider_key.clone()},
3288                            "name": "Local OpenAI"
3289                        })
3290                        .to_string(),
3291                    ))
3292                    .unwrap(),
3293            )
3294            .await
3295            .unwrap();
3296        assert_eq!(assigned.status(), StatusCode::CREATED);
3297
3298        crate::db::close_agent_gateway_session(&storage, session_id)
3299            .await
3300            .unwrap();
3301        let tested = runtime_app
3302            .oneshot(
3303                Request::post(format!(
3304                    "/v1/apps/provider-offline-project/providers/{provider_key}/test"
3305                ))
3306                .header("authorization", admin)
3307                .header("content-type", "application/json")
3308                .body(Body::from("{}"))
3309                .unwrap(),
3310            )
3311            .await
3312            .unwrap();
3313        assert_eq!(tested.status(), StatusCode::OK);
3314        let payload = response_json(tested).await;
3315        assert_eq!(payload["provider"]["status"], "offline");
3316        assert!(payload["message"]
3317            .as_str()
3318            .unwrap()
3319            .contains("not reported by gateway gateway-project"));
3320
3321        close_temp_storage(storage, path).await;
3322    }
3323
3324    #[tokio::test]
3325    async fn legacy_provider_connection_routes_are_not_registered() {
3326        let config = Config::from_env().unwrap();
3327        let pool = PgPoolOptions::new()
3328            .connect_lazy("postgres://vifu@127.0.0.1:1/vifu")
3329            .unwrap();
3330        let response = app(state(config, pool))
3331            .oneshot(
3332                Request::get("/v1/apps/test/provider-connections")
3333                    .body(Body::empty())
3334                    .unwrap(),
3335            )
3336            .await
3337            .unwrap();
3338
3339        assert_eq!(response.status(), StatusCode::NOT_FOUND);
3340    }
3341
3342    #[tokio::test]
3343    async fn agent_gateway_runtime_agents_include_assigned_project_profiles() {
3344        let path = std::env::temp_dir().join(format!(
3345            "vifu-runtime-agents-{}.sqlite",
3346            uuid::Uuid::new_v4()
3347        ));
3348        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
3349            .await
3350            .unwrap();
3351        crate::db::migrate(&storage).await.unwrap();
3352        let project_id = uuid::Uuid::new_v4();
3353        let profile_id = uuid::Uuid::new_v4();
3354        crate::db::create_project(
3355            &storage,
3356            crate::db::NewProject {
3357                id: project_id,
3358                owner_user_id: None,
3359                slug: "stardew-valley",
3360                name: "Stardew Valley",
3361                description: None,
3362                gateway_id: "gateway-stardew",
3363                binding_ids: &[],
3364            },
3365        )
3366        .await
3367        .unwrap();
3368        crate::db::upsert_agent_gateway_machine(&storage, "machine-stardew", "test-public-key")
3369            .await
3370            .unwrap();
3371        let config = Config::from_env().unwrap();
3372        let device_token = format!("vifu_gw_{}", "b".repeat(64));
3373        let token_hash =
3374            crate::auth::hash_agent_gateway_credential(&device_token, &config.api_key_pepper);
3375        crate::db::create_agent_gateway_authorization(
3376            &storage,
3377            crate::db::NewAgentGatewayAuthorization {
3378                gateway_id: "gateway-stardew",
3379                machine_id: "machine-stardew",
3380                owner_user_id: None,
3381                token_prefix: &device_token.chars().take(20).collect::<String>(),
3382                token_hash: &token_hash,
3383                token_expires_at: chrono::Utc::now() + chrono::Duration::days(30),
3384            },
3385        )
3386        .await
3387        .unwrap();
3388        crate::db::create_profile(
3389            &storage,
3390            profile_id,
3391            project_id,
3392            "stardew-valley-farming-0",
3393            "Farming 0",
3394            None,
3395        )
3396        .await
3397        .unwrap();
3398        let capabilities = vec![crate::models::ProfileCapabilityDraft {
3399            kind: "chat".to_string(),
3400            provider_type: "openai-compatible".to_string(),
3401            provider_key: "local-qwen".to_string(),
3402            resource_id: Some("qwen".to_string()),
3403            config: json!({}),
3404            input_schema: json!({}),
3405            output_schema: json!({}),
3406        }];
3407        let empty = json!({});
3408        crate::db::create_profile_version(
3409            &storage,
3410            profile_id,
3411            crate::db::NewProfileVersion {
3412                persona: &empty,
3413                runtime: &empty,
3414                presentation: &empty,
3415                source: &empty,
3416                capabilities: &capabilities,
3417                change_summary: None,
3418            },
3419        )
3420        .await
3421        .unwrap();
3422
3423        let response = app(state_with_storage(config, storage.clone()))
3424            .oneshot(
3425                Request::get("/v1/agent-gateway/runtime-agents")
3426                    .header("authorization", format!("Bearer {device_token}"))
3427                    .body(Body::empty())
3428                    .unwrap(),
3429            )
3430            .await
3431            .unwrap();
3432
3433        assert_eq!(response.status(), StatusCode::OK);
3434        let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
3435        let payload: Value = serde_json::from_slice(&body).unwrap();
3436        assert_eq!(
3437            payload["deployments"][0]["agents"][0]["slug"],
3438            "stardew-valley-farming-0"
3439        );
3440
3441        close_temp_storage(storage, path).await;
3442    }
3443
3444    async fn state_with_access_token_auth(
3445        config: Config,
3446        pool: sqlx::PgPool,
3447        operations: Vec<Operation>,
3448    ) -> (AppState, String) {
3449        state_with_storage_access_token_auth(
3450            config,
3451            Storage::postgres(pool),
3452            "user-123",
3453            operations,
3454        )
3455        .await
3456    }
3457
3458    async fn state_with_storage_access_token_auth(
3459        config: Config,
3460        storage: Storage,
3461        subject: &str,
3462        operations: Vec<Operation>,
3463    ) -> (AppState, String) {
3464        let auth = ApplicationAuth::with_deployment_credential_auth(
3465            config.admin_key.clone(),
3466            "dep_01JTESTDEPLOYMENT",
3467            Arc::new(StaticAccessTokenAuth {
3468                subject: subject.to_string(),
3469                operations,
3470            }),
3471        );
3472        let credential = auth
3473            .exchange_access_token("account-access-token")
3474            .await
3475            .unwrap()
3476            .credential;
3477        (
3478            state_with_storage_and_auth(config, storage, auth),
3479            credential,
3480        )
3481    }
3482
3483    async fn temp_sqlite_storage(prefix: &str) -> (Storage, PathBuf) {
3484        let path =
3485            std::env::temp_dir().join(format!("vifu-{prefix}-{}.sqlite", uuid::Uuid::new_v4()));
3486        let storage = crate::db::connect(&format!("sqlite://{}", path.display()), 5)
3487            .await
3488            .unwrap();
3489        crate::db::migrate(&storage).await.unwrap();
3490        (storage, path)
3491    }
3492
3493    async fn close_temp_storage(storage: Storage, path: PathBuf) {
3494        match storage {
3495            Storage::Postgres(pool) => pool.close().await,
3496            Storage::Sqlite(pool) => pool.close().await,
3497        }
3498        std::fs::remove_file(path).unwrap();
3499    }
3500
3501    fn admin_authorization(config: &Config) -> String {
3502        format!("Bearer {}", config.admin_key)
3503    }
3504
3505    async fn response_json(response: Response) -> Value {
3506        let body = to_bytes(response.into_body(), 256 * 1024).await.unwrap();
3507        serde_json::from_slice(&body).unwrap()
3508    }
3509
3510    async fn create_test_project(storage: &Storage, slug: &str, gateway_id: &str) -> uuid::Uuid {
3511        let project_id = uuid::Uuid::new_v4();
3512        crate::db::create_project(
3513            storage,
3514            crate::db::NewProject {
3515                id: project_id,
3516                owner_user_id: None,
3517                slug,
3518                name: "Provider Project",
3519                description: None,
3520                gateway_id,
3521                binding_ids: &[],
3522            },
3523        )
3524        .await
3525        .unwrap();
3526        project_id
3527    }
3528
3529    async fn open_provider_gateway_session(storage: &Storage, gateway_id: &str) -> uuid::Uuid {
3530        let (session_id, _resumed) = crate::db::open_agent_gateway_session(
3531            storage,
3532            gateway_id,
3533            None,
3534            &json!([
3535                {
3536                    "id": "openai-agent",
3537                    "name": "OpenAI Agent",
3538                    "metadata": {
3539                        "providerKey": "local-openai",
3540                        "providerType": "vifu-runtime",
3541                        "localProviderType": "openai-compatible",
3542                        "capabilities": ["chat", "embedding"]
3543                    }
3544                },
3545                {
3546                    "id": "llama-agent",
3547                    "name": "Llama Agent",
3548                    "metadata": {
3549                        "providerKey": "local-llama",
3550                        "providerType": "vifu-runtime",
3551                        "localProviderType": "llama",
3552                        "capabilities": ["chat", "embedding"]
3553                    }
3554                },
3555                {
3556                    "id": "whisper-agent",
3557                    "name": "Whisper Agent",
3558                    "metadata": {
3559                        "providerKey": "local-whisper",
3560                        "providerType": "vifu-runtime",
3561                        "localProviderType": "local-whisper",
3562                        "capabilities": ["transcription"]
3563                    }
3564                }
3565            ]),
3566            &json!({
3567                "providers": [
3568                    {"id": "local-openai", "type": "vifu-runtime"},
3569                    {"id": "local-llama", "type": "vifu-runtime"},
3570                    {"id": "local-whisper", "type": "vifu-runtime"}
3571                ]
3572            }),
3573        )
3574        .await
3575        .unwrap();
3576        session_id
3577    }
3578
3579    async fn custom_provider_row_count(storage: &Storage) -> i64 {
3580        match storage {
3581            Storage::Sqlite(pool) => {
3582                sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM custom_providers")
3583                    .fetch_one(pool)
3584                    .await
3585                    .unwrap()
3586            }
3587            Storage::Postgres(pool) => {
3588                sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM custom_providers")
3589                    .fetch_one(pool)
3590                    .await
3591                    .unwrap()
3592            }
3593        }
3594    }
3595
3596    async fn openai_probe_mock() -> (String, JoinHandle<()>) {
3597        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3598        let addr = listener.local_addr().unwrap();
3599        let server = tokio::spawn(async move {
3600            axum::serve(
3601                listener,
3602                axum::Router::new().route(
3603                    "/v1/models",
3604                    get(|| async { axum::Json(json!({ "data": [] })) }),
3605                ),
3606            )
3607            .await
3608            .unwrap();
3609        });
3610        (format!("http://{addr}/v1"), server)
3611    }
3612
3613    struct StaticAccessTokenAuth {
3614        subject: String,
3615        operations: Vec<Operation>,
3616    }
3617
3618    impl AccessTokenAuth for StaticAccessTokenAuth {
3619        fn is_authorized<'a>(
3620            &'a self,
3621            access_token: &'a str,
3622            _operation: Operation,
3623        ) -> AccessTokenAuthFuture<'a> {
3624            Box::pin(async move {
3625                if access_token != "account-access-token" {
3626                    return Err(ApiError::Forbidden);
3627                }
3628                Ok(Identity::ActingUser {
3629                    subject: self.subject.clone(),
3630                    issuer: "test-authority".to_string(),
3631                    operations: self.operations.clone(),
3632                })
3633            })
3634        }
3635    }
3636}