Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       1301use std::{2    collections::BTreeMap, fmt::Display, future::Future, net::SocketAddr, pin::Pin, sync::Arc,3    time::Instant,4};56use actix_web::{7    App, Error, HttpResponse, HttpServer,8    body::{EitherBody, MessageBody},9    dev::{ServiceRequest, ServiceResponse},10    http::header::AUTHORIZATION,11    middleware::{self, Next},12    web,13};14use serde::{Deserialize, Serialize};15use subtle::ConstantTimeEq;16use tokio::sync::Mutex;1718use super::super::{19    cli::SettingsFlags,20    error::OnceError,21    model::{22        AppDetail, AppEnvironment, AppSummary, BackupSettings, ContainerResources,23        RegistrySettings, SmtpSettings,24    },25    namespace::Namespace,26    operations,27    settings::registry_host,28};2930type AppsFuture<'a> = Pin<Box<dyn Future<Output = Result<Vec<AppSummary>, OnceError>> + Send + 'a>>;31type DetailFuture<'a> = Pin<Box<dyn Future<Output = Result<AppDetail, OnceError>> + Send + 'a>>;32type DeployFuture<'a> = Pin<Box<dyn Future<Output = Result<AppSummary, OnceError>> + Send + 'a>>;33type UpdateFuture<'a> = Pin<Box<dyn Future<Output = Result<AppSummary, OnceError>> + Send + 'a>>;34type RemoveFuture<'a> = Pin<Box<dyn Future<Output = Result<(), OnceError>> + Send + 'a>>;35type EnvFuture<'a> = Pin<Box<dyn Future<Output = Result<AppEnvironment, OnceError>> + Send + 'a>>;36type ExecFuture<'a> = Pin<Box<dyn Future<Output = Result<ExecResponse, OnceError>> + Send + 'a>>;37type LogsFuture<'a> = Pin<Box<dyn Future<Output = Result<LogsResponse, OnceError>> + Send + 'a>>;3839pub const MAX_API_OUTPUT_BYTES: usize = 1_048_576;40const MAX_API_REQUEST_BYTES: usize = 131_072;41const MAX_EXEC_ARGS: usize = 128;42const MAX_EXEC_COMMAND_BYTES: usize = 65_536;43const DEFAULT_LOG_TAIL: u16 = 100;44const MAX_LOG_TAIL: u16 = 500;4546#[derive(Clone, Copy)]47enum LifecycleAction {48    Start,49    Stop,50    Restart,51}5253pub trait AppManager: Send + Sync {54    fn list_apps(&self) -> AppsFuture<'_>;55    fn detail(&self, host: String) -> DetailFuture<'_>;56    fn environment(&self, host: String) -> EnvFuture<'_>;57    fn set_environment(&self, host: String, env: BTreeMap<String, String>) -> EnvFuture<'_>;58    fn deploy(&self, image: String, flags: SettingsFlags) -> DeployFuture<'_>;59    fn update(&self, host: String, request: UpdateRequest) -> UpdateFuture<'_>;60    fn start(&self, host: String) -> DeployFuture<'_>;61    fn stop(&self, host: String) -> DeployFuture<'_>;62    fn restart(&self, host: String) -> DeployFuture<'_>;63    fn remove(&self, host: String, remove_data: bool) -> RemoveFuture<'_>;64    fn exec(&self, host: String, command: Vec<String>) -> ExecFuture<'_>;65    fn logs(&self, host: String, tail: u16, timestamps: bool) -> LogsFuture<'_>;66}6768pub struct NamespaceManager {69    namespace: Arc<Mutex<Namespace>>,70}7172impl NamespaceManager {73    pub fn new(namespace: Arc<Mutex<Namespace>>) -> Self {74        Self { namespace }75    }76}7778impl AppManager for NamespaceManager {79    fn list_apps(&self) -> AppsFuture<'_> {80        Box::pin(async move {81            let mut namespace = self.namespace.lock().await;82            namespace.refresh().await?;83            Ok(operations::app_summaries(&namespace))84        })85    }8687    fn detail(&self, host: String) -> DetailFuture<'_> {88        Box::pin(async move {89            let mut namespace = self.namespace.lock().await;90            namespace.refresh().await?;91            operations::app_detail(&namespace, &host)92        })93    }9495    fn environment(&self, host: String) -> EnvFuture<'_> {96        Box::pin(async move {97            let mut namespace = self.namespace.lock().await;98            namespace.refresh().await?;99            operations::app_environment(&namespace, &host)100        })101    }102103    fn set_environment(&self, host: String, env: BTreeMap<String, String>) -> EnvFuture<'_> {104        Box::pin(async move {105            let mut namespace = self.namespace.lock().await;106            namespace.refresh().await?;107            let result = operations::set_env_api(&mut namespace, &host, &env).await;108            refresh_after_mutation(&mut namespace, result).await?;109            operations::app_environment(&namespace, &host)110        })111    }112113    fn deploy(&self, image: String, flags: SettingsFlags) -> DeployFuture<'_> {114        Box::pin(async move {115            let host = flags.host.clone().unwrap_or_default();116            let mut namespace = self.namespace.lock().await;117            namespace.refresh().await?;118            let result = operations::deploy_api(&mut namespace, &image, &flags).await;119            refresh_after_mutation(&mut namespace, result).await?;120            operations::app_summaries(&namespace)121                .into_iter()122                .find(|app| app.host == host)123                .ok_or(OnceError::ApplicationNotFound(host))124        })125    }126127    fn update(&self, host: String, request: UpdateRequest) -> UpdateFuture<'_> {128        Box::pin(async move {129            let mut namespace = self.namespace.lock().await;130            namespace.refresh().await?;131            let previous = namespace132                .applications133                .iter()134                .find(|app| app.settings.host == host)135                .ok_or_else(|| OnceError::ApplicationNotFound(host.clone()))?;136            let image = request137                .image138                .as_deref()139                .unwrap_or(&previous.settings.image)140                .to_owned();141            let flags = request142                .settings143                .into_flags(&image)144                .map_err(|message| OnceError::Io(message.into()))?;145            let result_host = flags.host.clone().unwrap_or_else(|| host.clone());146            let args = super::super::cli::UpdateArgs {147                host: host.clone(),148                image: request.image,149                settings: flags,150            };151            let result = operations::update_api(&mut namespace, &host, &args).await;152            refresh_after_mutation(&mut namespace, result).await?;153            operations::app_summaries(&namespace)154                .into_iter()155                .find(|app| app.host == result_host)156                .ok_or(OnceError::ApplicationNotFound(result_host))157        })158    }159160    fn start(&self, host: String) -> DeployFuture<'_> {161        self.change_state(host, LifecycleAction::Start)162    }163164    fn stop(&self, host: String) -> DeployFuture<'_> {165        self.change_state(host, LifecycleAction::Stop)166    }167168    fn restart(&self, host: String) -> DeployFuture<'_> {169        self.change_state(host, LifecycleAction::Restart)170    }171172    fn remove(&self, host: String, remove_data: bool) -> RemoveFuture<'_> {173        Box::pin(async move {174            let mut namespace = self.namespace.lock().await;175            namespace.refresh().await?;176            if namespace177                .applications178                .iter()179                .any(|app| app.settings.host == host && app.is_server)180            {181                return Err(OnceError::ServerProtected);182            }183            let result = operations::remove_api(&mut namespace, &host, remove_data).await;184            refresh_after_mutation(&mut namespace, result).await185        })186    }187188    fn exec(&self, host: String, command: Vec<String>) -> ExecFuture<'_> {189        Box::pin(async move {190            let mut namespace = self.namespace.lock().await;191            namespace.refresh().await?;192            let output =193                operations::exec_capture_api(&namespace, &host, &command, MAX_API_OUTPUT_BYTES)194                    .await;195            let output = refresh_after_mutation(&mut namespace, output).await?;196            Ok(ExecResponse {197                exit_code: output.exit_code,198                stdout: output.stdout,199                stderr: output.stderr,200                truncated: output.truncated,201            })202        })203    }204205    fn logs(&self, host: String, tail: u16, timestamps: bool) -> LogsFuture<'_> {206        Box::pin(async move {207            let mut namespace = self.namespace.lock().await;208            namespace.refresh().await?;209            let output =210                operations::logs_api(&namespace, &host, tail, timestamps, MAX_API_OUTPUT_BYTES)211                    .await?;212            Ok(LogsResponse {213                output: output.output,214                truncated: output.truncated,215            })216        })217    }218}219220impl NamespaceManager {221    fn change_state(&self, host: String, action: LifecycleAction) -> DeployFuture<'_> {222        Box::pin(async move {223            let mut namespace = self.namespace.lock().await;224            namespace.refresh().await?;225            let app = namespace226                .applications227                .iter()228                .find(|app| app.settings.host == host)229                .cloned()230                .ok_or_else(|| OnceError::ApplicationNotFound(host.clone()))?;231            if app.is_server {232                return Err(OnceError::ServerProtected);233            }234            let result = match action {235                LifecycleAction::Start => operations::start_api(&namespace, &host).await,236                LifecycleAction::Stop => operations::stop_api(&namespace, &host).await,237                LifecycleAction::Restart => operations::restart_api(&namespace, &host).await,238            };239            refresh_after_mutation(&mut namespace, result).await?;240            operations::app_summaries(&namespace)241                .into_iter()242                .find(|summary| summary.host == host)243                .ok_or(OnceError::ApplicationNotFound(host))244        })245    }246}247248async fn refresh_after_mutation<T>(249    namespace: &mut Namespace,250    result: Result<T, OnceError>,251) -> Result<T, OnceError> {252    let refresh = namespace.refresh().await;253    match result {254        Err(error) => Err(error),255        Ok(value) => {256            refresh?;257            Ok(value)258        }259    }260}261262#[derive(Clone)]263pub struct ApiState {264    api_key: Arc<[u8]>,265    app_manager: Arc<dyn AppManager>,266}267268impl ApiState {269    pub fn new(api_key: String, app_manager: Arc<dyn AppManager>) -> Self {270        Self {271            api_key: Arc::from(api_key.into_bytes()),272            app_manager,273        }274    }275276    fn accepts(&self, supplied: &[u8]) -> bool {277        bool::from(self.api_key.as_ref().ct_eq(supplied))278    }279}280281#[derive(Deserialize)]282#[serde(rename_all = "camelCase")]283pub struct DeployRequest {284    pub image: String,285    pub settings: DeploySettings,286}287288#[derive(Deserialize)]289#[serde(rename_all = "camelCase")]290pub struct DeploySettings {291    pub host: String,292    #[serde(rename = "disableTLS")]293    pub disable_tls: Option<bool>,294    pub env: Option<std::collections::HashMap<String, String>>,295    pub smtp: Option<SmtpSettings>,296    pub resources: Option<ContainerResources>,297    pub auto_update: Option<bool>,298    pub backup: Option<BackupSettings>,299    pub registry: Option<RegistrySettings>,300}301302#[derive(Deserialize, Default)]303#[serde(rename_all = "camelCase")]304pub struct UpdateRequest {305    pub image: Option<String>,306    #[serde(default)]307    pub settings: SettingsPatch,308}309310#[derive(Deserialize, Default)]311#[serde(rename_all = "camelCase")]312pub struct SettingsPatch {313    pub host: Option<String>,314    #[serde(rename = "disableTLS")]315    pub disable_tls: Option<bool>,316    pub env: Option<std::collections::HashMap<String, String>>,317    pub smtp: Option<SmtpSettings>,318    pub resources: Option<ContainerResources>,319    pub auto_update: Option<bool>,320    pub backup: Option<BackupSettings>,321    pub registry: Option<RegistrySettings>,322}323324#[derive(Deserialize)]325pub struct ExecRequest {326    pub command: Vec<String>,327}328329#[derive(Deserialize)]330pub struct EnvRequest {331    pub env: BTreeMap<String, String>,332}333334#[derive(Serialize)]335#[serde(rename_all = "camelCase")]336pub struct ExecResponse {337    pub exit_code: i32,338    pub stdout: String,339    pub stderr: String,340    pub truncated: bool,341}342343#[derive(Serialize)]344#[serde(rename_all = "camelCase")]345pub struct LogsResponse {346    pub output: String,347    pub truncated: bool,348}349350#[derive(Deserialize, Default)]351struct LogsQuery {352    tail: Option<u16>,353    /// Prefixes each line of `output` with its RFC 3339 time.354    #[serde(default)]355    timestamps: bool,356}357358impl DeploySettings {359    fn into_flags(self, image: &str) -> Result<SettingsFlags, &'static str> {360        if self.host.is_empty() || super::validate_host(&self.host).is_err() {361            return Err("invalid hostname");362        }363        if let Some(env) = &self.env364            && env.iter().any(|(key, value)| {365                key.is_empty() || key.contains('=') || key.contains('\0') || value.contains('\0')366            })367        {368            return Err("invalid environment variable");369        }370        if let Some(registry) = &self.registry371            && !registry.host.is_empty()372            && registry.host != registry_host(image)373        {374            return Err("registry host must match the image reference");375        }376377        let env = self.env.map(|vars| {378            vars.into_iter()379                .map(|(key, value)| format!("{key}={value}"))380                .collect()381        });382        let smtp = self.smtp;383        let resources = self.resources;384        let backup = self.backup;385        let (registry_username, registry_password) =386            self.registry.map_or((None, None), |registry| {387                if registry.username.is_empty() && registry.password.is_empty() {388                    (None, None)389                } else {390                    (Some(registry.username), Some(registry.password))391                }392            });393394        Ok(SettingsFlags {395            host: Some(self.host),396            disable_tls: self.disable_tls,397            env,398            smtp_server: smtp.as_ref().map(|settings| settings.server.clone()),399            smtp_port: smtp.as_ref().map(|settings| settings.port.clone()),400            smtp_username: smtp.as_ref().map(|settings| settings.username.clone()),401            smtp_password: smtp.as_ref().map(|settings| settings.password.clone()),402            smtp_from: smtp.as_ref().map(|settings| settings.from.clone()),403            cpus: resources.as_ref().map(|settings| settings.cpus),404            memory: resources.as_ref().map(|settings| settings.memory_mb),405            auto_update: self.auto_update,406            backup_path: backup.as_ref().and_then(|settings| {407                (!settings.path.is_empty()).then(|| std::path::PathBuf::from(&settings.path))408            }),409            auto_backup: backup.map(|settings| settings.auto_backup),410            registry_username,411            registry_password,412            registry_password_stdin: false,413        })414    }415}416417impl SettingsPatch {418    fn into_flags(self, image: &str) -> Result<SettingsFlags, &'static str> {419        if let Some(host) = &self.host420            && (host.is_empty() || super::validate_host(host).is_err())421        {422            return Err("invalid hostname");423        }424        if let Some(env) = &self.env425            && env.iter().any(|(key, value)| {426                key.is_empty() || key.contains('=') || key.contains('\0') || value.contains('\0')427            })428        {429            return Err("invalid environment variable");430        }431        if let Some(registry) = &self.registry432            && !registry.host.is_empty()433            && registry.host != registry_host(image)434        {435            return Err("registry host must match the image reference");436        }437438        let env = self.env.map(|vars| {439            vars.into_iter()440                .map(|(key, value)| format!("{key}={value}"))441                .collect()442        });443        let smtp = self.smtp;444        let resources = self.resources;445        let backup = self.backup;446        let (registry_username, registry_password) =447            self.registry.map_or((None, None), |registry| {448                (Some(registry.username), Some(registry.password))449            });450451        Ok(SettingsFlags {452            host: self.host,453            disable_tls: self.disable_tls,454            env,455            smtp_server: smtp.as_ref().map(|settings| settings.server.clone()),456            smtp_port: smtp.as_ref().map(|settings| settings.port.clone()),457            smtp_username: smtp.as_ref().map(|settings| settings.username.clone()),458            smtp_password: smtp.as_ref().map(|settings| settings.password.clone()),459            smtp_from: smtp.as_ref().map(|settings| settings.from.clone()),460            cpus: resources.as_ref().map(|settings| settings.cpus),461            memory: resources.as_ref().map(|settings| settings.memory_mb),462            auto_update: self.auto_update,463            backup_path: backup464                .as_ref()465                .map(|settings| std::path::PathBuf::from(&settings.path)),466            auto_backup: backup.map(|settings| settings.auto_backup),467            registry_username,468            registry_password,469            registry_password_stdin: false,470        })471    }472}473474#[derive(Serialize)]475struct HealthResponse {476    status: &'static str,477}478479#[derive(Serialize)]480struct ErrorResponse {481    error: ErrorDetail,482}483484#[derive(Serialize)]485struct ErrorDetail {486    code: &'static str,487    message: &'static str,488}489490pub fn bind_http(491    address: SocketAddr,492    state: ApiState,493) -> Result<actix_web::dev::Server, std::io::Error> {494    Ok(HttpServer::new(move || {495        App::new()496            .app_data(web::Data::new(state.clone()))497            .route("/up", web::get().to(health))498            .configure(configure_app)499    })500    .bind(address)?501    .run())502}503504fn configure_app(config: &mut web::ServiceConfig) {505    config506        .app_data(507            web::JsonConfig::default()508                .limit(MAX_API_REQUEST_BYTES)509                .error_handler(|error, _request| {510                    let response = match &error {511                        actix_web::error::JsonPayloadError::OverflowKnownLength { .. }512                        | actix_web::error::JsonPayloadError::Overflow { .. } => {513                            HttpResponse::PayloadTooLarge().json(ErrorResponse {514                                error: ErrorDetail {515                                    code: "payload_too_large",516                                    message: "request body exceeds the size limit",517                                },518                            })519                        }520                        _ => bad_request("invalid JSON request body"),521                    };522                    actix_web::error::InternalError::from_response(error, response).into()523                }),524        )525        .app_data(526            web::QueryConfig::default().error_handler(|error, _request| {527                actix_web::error::InternalError::from_response(528                    error,529                    bad_request("invalid query parameters"),530                )531                .into()532            }),533        )534        .app_data(web::PathConfig::default().error_handler(|error, _request| {535            actix_web::error::InternalError::from_response(536                error,537                bad_request("invalid path parameters"),538            )539            .into()540        }));541    configure_api(config);542}543544fn configure_api(config: &mut web::ServiceConfig) {545    config.service(546        web::scope("/api/v1")547            .wrap(middleware::from_fn(authenticate))548            .route("/apps", web::get().to(list_apps))549            .route("/apps", web::post().to(deploy_app))550            .route("/apps/{host}", web::get().to(get_app))551            .route("/apps/{host}", web::patch().to(update_app))552            .route("/apps/{host}/env", web::get().to(get_env))553            .route("/apps/{host}/env", web::put().to(put_env))554            .route("/apps/{host}/start", web::post().to(start_app))555            .route("/apps/{host}/stop", web::post().to(stop_app))556            .route("/apps/{host}/restart", web::post().to(restart_app))557            .route("/apps/{host}", web::delete().to(remove_app))558            .route("/apps/{host}/exec", web::post().to(exec_app))559            .route("/apps/{host}/logs", web::get().to(logs_app)),560    );561}562563async fn health() -> web::Json<HealthResponse> {564    web::Json(HealthResponse { status: "ok" })565}566567async fn list_apps(state: web::Data<ApiState>) -> HttpResponse {568    match state.app_manager.list_apps().await {569        Ok(apps) => HttpResponse::Ok().json(apps),570        Err(_) => HttpResponse::BadGateway().json(ErrorResponse {571            error: ErrorDetail {572                code: "backend_unavailable",573                message: "unable to read applications from Docker",574            },575        }),576    }577}578579async fn get_app(state: web::Data<ApiState>, host: web::Path<String>) -> HttpResponse {580    match state.app_manager.detail(host.into_inner()).await {581        Ok(app) => HttpResponse::Ok().json(app),582        Err(error) => error_response(&error),583    }584}585586async fn get_env(state: web::Data<ApiState>, host: web::Path<String>) -> HttpResponse {587    match state.app_manager.environment(host.into_inner()).await {588        Ok(environment) => HttpResponse::Ok().json(environment),589        Err(error) => error_response(&error),590    }591}592593async fn put_env(594    state: web::Data<ApiState>,595    host: web::Path<String>,596    request: web::Json<EnvRequest>,597) -> HttpResponse {598    let host = host.into_inner();599    let request = request.into_inner();600    let deployment = Deployment::start("environment update", &host, "(current)");601    if let Err(message) = validate_env(&request.env) {602        deployment.failed(message);603        return bad_request(message);604    }605    match state.app_manager.set_environment(host, request.env).await {606        Ok(environment) => {607            deployment.succeeded();608            HttpResponse::Ok().json(environment)609        }610        Err(error) => {611            deployment.failed(&error);612            error_response(&error)613        }614    }615}616617async fn deploy_app(state: web::Data<ApiState>, request: web::Json<DeployRequest>) -> HttpResponse {618    let request = request.into_inner();619    let deployment = Deployment::start("deploy", &request.settings.host, &request.image);620    if request.image.trim().is_empty() {621        deployment.failed("image is required");622        return bad_request("image is required");623    }624    let flags = match request.settings.into_flags(&request.image) {625        Ok(flags) => flags,626        Err(message) => {627            deployment.failed(message);628            return bad_request(message);629        }630    };631632    match state.app_manager.deploy(request.image, flags).await {633        Ok(app) => {634            deployment.succeeded();635            HttpResponse::Created().json(app)636        }637        Err(error) => {638            deployment.failed(&error);639            error_response(&error)640        }641    }642}643644async fn update_app(645    state: web::Data<ApiState>,646    host: web::Path<String>,647    request: web::Json<UpdateRequest>,648) -> HttpResponse {649    let host = host.into_inner();650    let request = request.into_inner();651    let deployment = Deployment::start(652        "update",653        &host,654        request.image.as_deref().unwrap_or("(current)"),655    );656    if request657        .image658        .as_deref()659        .is_some_and(|image| image.trim().is_empty())660    {661        deployment.failed("image must not be empty");662        return bad_request("image must not be empty");663    }664    match state.app_manager.update(host, request).await {665        Ok(app) => {666            deployment.succeeded();667            HttpResponse::Ok().json(app)668        }669        Err(error) => {670            deployment.failed(&error);671            error_response(&error)672        }673    }674}675676async fn start_app(state: web::Data<ApiState>, host: web::Path<String>) -> HttpResponse {677    match state.app_manager.start(host.into_inner()).await {678        Ok(app) => HttpResponse::Ok().json(app),679        Err(error) => error_response(&error),680    }681}682683async fn stop_app(state: web::Data<ApiState>, host: web::Path<String>) -> HttpResponse {684    match state.app_manager.stop(host.into_inner()).await {685        Ok(app) => HttpResponse::Ok().json(app),686        Err(error) => error_response(&error),687    }688}689690async fn restart_app(state: web::Data<ApiState>, host: web::Path<String>) -> HttpResponse {691    match state.app_manager.restart(host.into_inner()).await {692        Ok(app) => HttpResponse::Ok().json(app),693        Err(error) => error_response(&error),694    }695}696697#[derive(Deserialize, Default)]698struct RemoveQuery {699    #[serde(default)]700    remove_data: bool,701}702703async fn remove_app(704    state: web::Data<ApiState>,705    host: web::Path<String>,706    query: web::Query<RemoveQuery>,707) -> HttpResponse {708    match state709        .app_manager710        .remove(host.into_inner(), query.remove_data)711        .await712    {713        Ok(()) => HttpResponse::NoContent().finish(),714        Err(error) => error_response(&error),715    }716}717718async fn exec_app(719    state: web::Data<ApiState>,720    host: web::Path<String>,721    request: web::Json<ExecRequest>,722) -> HttpResponse {723    let request = request.into_inner();724    let command_bytes = request.command.iter().map(String::len).sum::<usize>();725    if request.command.is_empty()726        || request.command[0].is_empty()727        || request.command.len() > MAX_EXEC_ARGS728        || command_bytes > MAX_EXEC_COMMAND_BYTES729        || request730            .command731            .iter()732            .any(|argument| argument.contains('\0'))733    {734        return bad_request("command is empty or exceeds the command limits");735    }736    match state737        .app_manager738        .exec(host.into_inner(), request.command)739        .await740    {741        Ok(output) => HttpResponse::Ok().json(output),742        Err(error) => error_response(&error),743    }744}745746async fn logs_app(747    state: web::Data<ApiState>,748    host: web::Path<String>,749    query: web::Query<LogsQuery>,750) -> HttpResponse {751    let tail = query752        .tail753        .unwrap_or(DEFAULT_LOG_TAIL)754        .clamp(1, MAX_LOG_TAIL);755    match state756        .app_manager757        .logs(host.into_inner(), tail, query.timestamps)758        .await759    {760        Ok(logs) => HttpResponse::Ok().json(logs),761        Err(error) => error_response(&error),762    }763}764765fn bad_request(message: &'static str) -> HttpResponse {766    HttpResponse::BadRequest().json(ErrorResponse {767        error: ErrorDetail {768            code: "invalid_request",769            message,770        },771    })772}773774/// One request that changes what runs on the server. Its outcome is written to775/// the server's output, which Docker keeps, so `ino once logs` and the console776/// show whether each deployment worked and why a failed one did not.777struct Deployment {778    action: &'static str,779    host: String,780    image: String,781    started: Instant,782}783784impl Deployment {785    fn start(action: &'static str, host: &str, image: &str) -> Self {786        Self {787            action,788            host: host.to_owned(),789            image: image.to_owned(),790            started: Instant::now(),791        }792    }793794    fn succeeded(&self) {795        println!(796            "ino: {} succeeded: host={} image={} in {:.2?}",797            self.action,798            self.host,799            self.image,800            self.started.elapsed()801        );802    }803804    fn failed(&self, reason: impl Display) {805        eprintln!(806            "ino: {} failed: host={} image={} in {:.2?}: {reason}",807            self.action,808            self.host,809            self.image,810            self.started.elapsed()811        );812    }813}814815/// Checks names and values before they reach Docker. Names follow the portable816/// shell rule, so every saved variable can be exported by a process manager.817fn validate_env(env: &BTreeMap<String, String>) -> Result<(), &'static str> {818    if env.keys().any(|name| !valid_env_name(name)) {819        return Err(820            "environment variable names must start with a letter or underscore and contain only letters, digits, and underscores",821        );822    }823    if env.values().any(|value| value.contains('\0')) {824        return Err("environment variable values must not contain NUL bytes");825    }826    Ok(())827}828829fn valid_env_name(name: &str) -> bool {830    name.len() <= 128831        && name832            .as_bytes()833            .first()834            .is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_')835        && name836            .bytes()837            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')838}839840fn error_response(error: &OnceError) -> HttpResponse {841    match error {842        OnceError::HostConflict(_) => HttpResponse::Conflict().json(ErrorResponse {843            error: ErrorDetail {844                code: "host_conflict",845                message: "an application already uses this hostname",846            },847        }),848        OnceError::ApplicationNotRunning(_) => HttpResponse::Conflict().json(ErrorResponse {849            error: ErrorDetail {850                code: "application_state_conflict",851                message: "the application is not in a state for this operation",852            },853        }),854        OnceError::ReservedEnvironment(_) => HttpResponse::BadRequest().json(ErrorResponse {855            error: ErrorDetail {856                code: "reserved_environment",857                message: "this environment variable is managed by Ino",858            },859        }),860        OnceError::ServerProtected => HttpResponse::Conflict().json(ErrorResponse {861            error: ErrorDetail {862                code: "server_protected",863                message: "the server app cannot be controlled through its own API",864            },865        }),866        OnceError::ApplicationNotFound(_) => HttpResponse::NotFound().json(ErrorResponse {867            error: ErrorDetail {868                code: "application_not_found",869                message: "application was not found",870            },871        }),872        OnceError::Docker(_) => HttpResponse::BadGateway().json(ErrorResponse {873            error: ErrorDetail {874                code: "backend_unavailable",875                message: "the Docker deployment operation failed",876            },877        }),878        _ => HttpResponse::BadRequest().json(ErrorResponse {879            error: ErrorDetail {880                code: "invalid_request",881                message: "the deployment request could not be applied",882            },883        }),884    }885}886887async fn authenticate<B>(888    request: ServiceRequest,889    next: Next<B>,890) -> Result<ServiceResponse<EitherBody<B>>, Error>891where892    B: MessageBody + 'static,893{894    let authorized = request895        .app_data::<web::Data<ApiState>>()896        .and_then(|state| {897            request898                .headers()899                .get(AUTHORIZATION)900                .and_then(|value| value.to_str().ok())901                .and_then(|value| value.strip_prefix("Bearer "))902                .map(|value| state.accepts(value.as_bytes()))903        })904        .unwrap_or(false);905906    if authorized {907        return Ok(next.call(request).await?.map_into_left_body());908    }909910    let response = HttpResponse::Unauthorized().json(ErrorResponse {911        error: ErrorDetail {912            code: "unauthorized",913            message: "a valid bearer token is required",914        },915    });916    Ok(request.into_response(response).map_into_right_body())917}918919#[cfg(test)]920mod tests {921    use std::{922        collections::BTreeMap,923        sync::{Arc, Mutex},924    };925926    use actix_web::{App, http::StatusCode, test as actix_test, web};927928    use super::{929        ApiState, AppManager, AppsFuture, DeployFuture, DeploySettings, DetailFuture, EnvFuture,930        ExecFuture, ExecResponse, LogsFuture, LogsResponse, RemoveFuture, SettingsPatch,931        UpdateFuture, UpdateRequest, configure_app, error_response, health, valid_env_name,932        validate_env,933    };934    use crate::commands::once::{935        cli::SettingsFlags,936        error::OnceError,937        model::{938            AppDetail, AppEnvironment, AppSummary, BackupSettings, ContainerResources,939            RegistrySettings, RegistrySummary, SmtpSettings, SmtpSummary,940        },941    };942943    type RemovedData = Arc<Mutex<Vec<bool>>>;944    type RequestedTails = Arc<Mutex<Vec<u16>>>;945946    struct MockAppManager {947        apps: Vec<AppSummary>,948        removed_data: RemovedData,949        requested_tails: RequestedTails,950    }951952    impl MockAppManager {953        fn summary(&self, host: &str, running: bool) -> AppSummary {954            self.apps955                .iter()956                .find(|app| app.host == host)957                .cloned()958                .map(|mut app| {959                    app.running = running;960                    app961                })962                .unwrap()963        }964    }965966    impl AppManager for MockAppManager {967        fn list_apps(&self) -> AppsFuture<'_> {968            Box::pin(async move { Ok(self.apps.clone()) })969        }970971        fn detail(&self, host: String) -> DetailFuture<'_> {972            let summary = self.summary(&host, true);973            Box::pin(async move {974                Ok(AppDetail {975                    summary,976                    disable_tls: false,977                    auto_update: true,978                    resources: ContainerResources {979                        cpus: 1,980                        memory_mb: 256,981                    },982                    backup: BackupSettings::default(),983                    smtp: SmtpSummary {984                        server: "smtp.example.test".into(),985                        port: "587".into(),986                        username: "mailer".into(),987                        from: "from@example.test".into(),988                    },989                    registry: RegistrySummary {990                        host: "docker.io".into(),991                        username: "registry-user".into(),992                    },993                })994            })995        }996997        fn environment(&self, _host: String) -> EnvFuture<'_> {998            Box::pin(async {999                Ok(AppEnvironment {1000                    env: BTreeMap::from([("MODE".into(), "test".into())]),1001                    reserved: vec!["SECRET_KEY_BASE", "PORT"],1002                })1003            })1004        }10051006        fn set_environment(&self, _host: String, env: BTreeMap<String, String>) -> EnvFuture<'_> {1007            Box::pin(async move {1008                if env.contains_key("PORT") {1009                    return Err(OnceError::ReservedEnvironment("PORT".into()));1010                }1011                Ok(AppEnvironment {1012                    env,1013                    reserved: vec!["SECRET_KEY_BASE", "PORT"],1014                })1015            })1016        }10171018        fn deploy(&self, image: String, flags: SettingsFlags) -> DeployFuture<'_> {1019            Box::pin(async move {1020                Ok(AppSummary {1021                    name: "new-app".into(),1022                    host: flags.host.unwrap_or_default(),1023                    image,1024                    running: true,1025                    url: Some("http://new.example.test".into()),1026                    is_server: false,1027                })1028            })1029        }10301031        fn update(&self, host: String, request: UpdateRequest) -> UpdateFuture<'_> {1032            Box::pin(async move {1033                Ok(AppSummary {1034                    name: "updated-app".into(),1035                    host: request.settings.host.unwrap_or(host),1036                    image: request1037                        .image1038                        .unwrap_or_else(|| "example.test/writer:v1".into()),1039                    running: true,1040                    url: Some("https://writer.example.test".into()),1041                    is_server: false,1042                })1043            })1044        }10451046        fn start(&self, host: String) -> DeployFuture<'_> {1047            let app = self.summary(&host, true);1048            Box::pin(async move { Ok(app) })1049        }10501051        fn stop(&self, host: String) -> DeployFuture<'_> {1052            let app = self.summary(&host, false);1053            Box::pin(async move { Ok(app) })1054        }10551056        fn restart(&self, host: String) -> DeployFuture<'_> {1057            let app = self.summary(&host, true);1058            Box::pin(async move { Ok(app) })1059        }10601061        fn remove(&self, _host: String, remove_data: bool) -> RemoveFuture<'_> {1062            self.removed_data.lock().unwrap().push(remove_data);1063            Box::pin(async { Ok(()) })1064        }10651066        fn exec(&self, _host: String, _command: Vec<String>) -> ExecFuture<'_> {1067            Box::pin(async {1068                Ok(ExecResponse {1069                    exit_code: 7,1070                    stdout: "stdout".into(),1071                    stderr: "stderr".into(),1072                    truncated: false,1073                })1074            })1075        }10761077        fn logs(&self, _host: String, tail: u16, timestamps: bool) -> LogsFuture<'_> {1078            self.requested_tails.lock().unwrap().push(tail);1079            let output = if timestamps {1080                "2026-11-21T14:03:04.123456789Z app log"1081            } else {1082                "app log"1083            };1084            Box::pin(async move {1085                Ok(LogsResponse {1086                    output: output.into(),1087                    truncated: false,1088                })1089            })1090        }1091    }10921093    fn api_state() -> (ApiState, RemovedData, RequestedTails) {1094        let removed_data = Arc::new(Mutex::new(Vec::new()));1095        let requested_tails = Arc::new(Mutex::new(Vec::new()));1096        let state = ApiState::new(1097            "test-secret".to_owned(),1098            Arc::new(MockAppManager {1099                apps: vec![AppSummary {1100                    name: "writer".into(),1101                    host: "writer.example.test".into(),1102                    image: "example.test/writer:v1".into(),1103                    running: true,1104                    url: Some("https://writer.example.test".into()),1105                    is_server: false,1106                }],1107                removed_data: removed_data.clone(),1108                requested_tails: requested_tails.clone(),1109            }),1110        );1111        (state, removed_data, requested_tails)1112    }11131114    #[test]1115    fn deploy_settings_convert_to_once_flags_and_validate_registry_host() {1116        let settings = DeploySettings {1117            host: "writer.example.test".into(),1118            disable_tls: Some(true),1119            env: Some(std::collections::HashMap::from([(1120                "MODE".into(),1121                "test".into(),1122            )])),1123            smtp: Some(SmtpSettings {1124                server: "smtp.example.test".into(),1125                password: "smtp-secret".into(),1126                ..Default::default()1127            }),1128            resources: Some(ContainerResources {1129                cpus: 2,1130                memory_mb: 512,1131            }),1132            auto_update: Some(false),1133            backup: Some(BackupSettings {1134                path: "/var/backups/writer".into(),1135                auto_backup: true,1136            }),1137            registry: Some(RegistrySettings {1138                host: "docker.io".into(),1139                username: "registry-user".into(),1140                password: "registry-secret".into(),1141            }),1142        };1143        let flags = settings.into_flags("docker.io/team/writer:v1").unwrap();11441145        assert_eq!(flags.host.as_deref(), Some("writer.example.test"));1146        assert_eq!(1147            flags.env.as_deref(),1148            Some(["MODE=test".to_owned()].as_slice())1149        );1150        assert_eq!(flags.smtp_password.as_deref(), Some("smtp-secret"));1151        assert_eq!(flags.cpus, Some(2));1152        assert_eq!(flags.memory, Some(512));1153        assert_eq!(flags.auto_update, Some(false));1154        assert_eq!(1155            flags.backup_path.as_deref(),1156            Some(std::path::Path::new("/var/backups/writer"))1157        );1158        assert_eq!(flags.registry_username.as_deref(), Some("registry-user"));11591160        let mismatched_registry = DeploySettings {1161            registry: Some(RegistrySettings {1162                host: "registry.attacker.test".into(),1163                ..Default::default()1164            }),1165            ..serde_json::from_value(serde_json::json!({"host":"writer.example.test"})).unwrap()1166        };1167        assert!(1168            mismatched_registry1169                .into_flags("docker.io/team/writer:v1")1170                .is_err()1171        );1172    }11731174    #[test]1175    fn update_settings_keep_omitted_fields_absent_and_allow_explicit_empty_env() {1176        let patch: SettingsPatch = serde_json::from_value(serde_json::json!({1177            "env": {},1178            "autoUpdate": false1179        }))1180        .unwrap();1181        let flags = patch.into_flags("docker.io/team/writer:v1").unwrap();1182        assert_eq!(flags.env, Some(Vec::new()));1183        assert_eq!(flags.auto_update, Some(false));1184        assert!(flags.host.is_none());1185        assert!(flags.smtp_server.is_none());1186    }11871188    #[test]1189    fn api_settings_decode_once_tls_and_memory_field_spellings() {1190        let settings: DeploySettings = serde_json::from_value(serde_json::json!({1191            "host": "writer.example.test",1192            "disableTLS": true,1193            "resources": {"cpus": 2, "memoryMB": 512}1194        }))1195        .unwrap();11961197        assert_eq!(settings.disable_tls, Some(true));1198        assert_eq!(1199            settings.resources.as_ref().map(|value| value.memory_mb),1200            Some(512)1201        );1202    }12031204    #[actix_web::test]1205    async fn conflict_errors_are_stable_and_do_not_echo_hostnames() {1206        let response = error_response(&OnceError::HostConflict("secret.example.test".into()));1207        assert_eq!(response.status(), StatusCode::CONFLICT);1208        let body = actix_web::body::to_bytes(response.into_body())1209            .await1210            .unwrap();1211        assert!(1212            !String::from_utf8(body.to_vec())1213                .unwrap()1214                .contains("secret.example.test")1215        );1216    }12171218    #[actix_web::test]1219    async fn health_is_public_and_real_list_requires_a_valid_bearer_key() {1220        let (state, removed_data, requested_tails) = api_state();1221        let app = actix_test::init_service(1222            App::new()1223                .app_data(web::Data::new(state))1224                .route("/up", web::get().to(health))1225                .configure(configure_app),1226        )1227        .await;12281229        let response =1230            actix_test::call_service(&app, actix_test::TestRequest::get().uri("/up").to_request())1231                .await;1232        assert_eq!(response.status(), StatusCode::OK);12331234        let response = actix_test::call_service(1235            &app,1236            actix_test::TestRequest::get()1237                .uri("/api/v1/apps")1238                .to_request(),1239        )1240        .await;1241        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);1242        let body = actix_test::read_body(response).await;1243        let body = String::from_utf8(body.to_vec()).unwrap();1244        assert!(body.contains("unauthorized"));1245        assert!(!body.contains("test-secret"));12461247        let response = actix_test::call_service(1248            &app,1249            actix_test::TestRequest::get()1250                .uri("/api/v1/apps")1251                .insert_header(("Authorization", "Bearer wrong-secret"))1252                .to_request(),1253        )1254        .await;1255        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);12561257        let response = actix_test::call_service(1258            &app,1259            actix_test::TestRequest::get()1260                .uri("/api/v1/apps")1261                .insert_header(("Authorization", "Bearer test-secret"))1262                .to_request(),1263        )1264        .await;1265        assert_eq!(response.status(), StatusCode::OK);1266        let body: serde_json::Value = actix_test::read_body_json(response).await;1267        assert_eq!(body[0]["host"], "writer.example.test");1268        assert_eq!(body[0]["image"], "example.test/writer:v1");1269        assert_eq!(body[0]["running"], true);1270        assert_eq!(body[0]["isServer"], false);1271        assert!(body[0].get("env").is_none());1272        assert!(body[0].get("registry").is_none());1273        assert!(!body.to_string().contains("test-secret"));12741275        let response = actix_test::call_service(1276            &app,1277            actix_test::TestRequest::post()1278                .uri("/api/v1/apps")1279                .insert_header(("Authorization", "Bearer test-secret"))1280                .set_json(serde_json::json!({1281                    "image": "example.test/new:v2",1282                    "settings": {1283                        "host": "new.example.test",1284                        "env": {"MODE": "test"}1285                    }1286                }))1287                .to_request(),1288        )1289        .await;1290        assert_eq!(response.status(), StatusCode::CREATED);1291        let deployed: serde_json::Value = actix_test::read_body_json(response).await;1292        assert_eq!(deployed["host"], "new.example.test");1293        assert_eq!(deployed["image"], "example.test/new:v2");12941295        let response = actix_test::call_service(1296            &app,1297            actix_test::TestRequest::patch()1298                .uri("/api/v1/apps/writer.example.test")1299                .insert_header(("Authorization", "Bearer test-secret"))1300                .set_json(serde_json::json!({1301                    "image": "example.test/writer:v2",1302                    "settings": {"autoUpdate": false}1303                }))1304                .to_request(),1305        )1306        .await;1307        assert_eq!(response.status(), StatusCode::OK);1308        let updated: serde_json::Value = actix_test::read_body_json(response).await;1309        assert_eq!(updated["host"], "writer.example.test");1310        assert_eq!(updated["image"], "example.test/writer:v2");13111312        for (action, expected_running) in [("start", true), ("stop", false), ("restart", true)] {1313            let response = actix_test::call_service(1314                &app,1315                actix_test::TestRequest::post()1316                    .uri(&format!("/api/v1/apps/writer.example.test/{action}"))1317                    .insert_header(("Authorization", "Bearer test-secret"))1318                    .to_request(),1319            )1320            .await;1321            assert_eq!(response.status(), StatusCode::OK);1322            let body: serde_json::Value = actix_test::read_body_json(response).await;1323            assert_eq!(body["running"], expected_running);1324        }13251326        let response = actix_test::call_service(1327            &app,1328            actix_test::TestRequest::delete()1329                .uri("/api/v1/apps/writer.example.test")1330                .insert_header(("Authorization", "Bearer test-secret"))1331                .to_request(),1332        )1333        .await;1334        assert_eq!(response.status(), StatusCode::NO_CONTENT);1335        let response = actix_test::call_service(1336            &app,1337            actix_test::TestRequest::delete()1338                .uri("/api/v1/apps/writer.example.test?remove_data=true")1339                .insert_header(("Authorization", "Bearer test-secret"))1340                .to_request(),1341        )1342        .await;1343        assert_eq!(response.status(), StatusCode::NO_CONTENT);1344        assert_eq!(*removed_data.lock().unwrap(), [false, true]);13451346        let response = actix_test::call_service(1347            &app,1348            actix_test::TestRequest::post()1349                .uri("/api/v1/apps/writer.example.test/exec")1350                .insert_header(("Authorization", "Bearer test-secret"))1351                .set_json(serde_json::json!({"command":["sh","-c","exit 7"]}))1352                .to_request(),1353        )1354        .await;1355        assert_eq!(response.status(), StatusCode::OK);1356        let output: serde_json::Value = actix_test::read_body_json(response).await;1357        assert_eq!(output["exitCode"], 7);1358        assert_eq!(output["stdout"], "stdout");1359        assert_eq!(output["stderr"], "stderr");1360        assert_eq!(output["truncated"], false);13611362        let response = actix_test::call_service(1363            &app,1364            actix_test::TestRequest::post()1365                .uri("/api/v1/apps/writer.example.test/exec")1366                .insert_header(("Authorization", "Bearer test-secret"))1367                .set_json(serde_json::json!({"command":[]}))1368                .to_request(),1369        )1370        .await;1371        assert_eq!(response.status(), StatusCode::BAD_REQUEST);13721373        let oversized = serde_json::json!({1374            "image": "example.test/writer:v1",1375            "settings": {1376                "host": "writer.example.test",1377                "env": {"LARGE": "x".repeat(super::MAX_API_REQUEST_BYTES)}1378            }1379        })1380        .to_string();1381        let response = actix_test::call_service(1382            &app,1383            actix_test::TestRequest::post()1384                .uri("/api/v1/apps")1385                .insert_header(("Authorization", "Bearer test-secret"))1386                .insert_header(("Content-Type", "application/json"))1387                .set_payload(oversized)1388                .to_request(),1389        )1390        .await;1391        assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);1392        let body = actix_test::read_body(response).await;1393        assert!(1394            String::from_utf8(body.to_vec())1395                .unwrap()1396                .contains("payload_too_large")1397        );13981399        let response = actix_test::call_service(1400            &app,1401            actix_test::TestRequest::get()1402                .uri("/api/v1/apps/writer.example.test/logs?tail=not-a-number")1403                .insert_header(("Authorization", "Bearer test-secret"))1404                .to_request(),1405        )1406        .await;1407        assert_eq!(response.status(), StatusCode::BAD_REQUEST);14081409        let response = actix_test::call_service(1410            &app,1411            actix_test::TestRequest::get()1412                .uri("/api/v1/apps/writer.example.test/logs?tail=999")1413                .insert_header(("Authorization", "Bearer test-secret"))1414                .to_request(),1415        )1416        .await;1417        assert_eq!(response.status(), StatusCode::OK);1418        let logs: serde_json::Value = actix_test::read_body_json(response).await;1419        assert_eq!(logs["output"], "app log");1420        let response = actix_test::call_service(1421            &app,1422            actix_test::TestRequest::get()1423                .uri("/api/v1/apps/writer.example.test/logs")1424                .insert_header(("Authorization", "Bearer test-secret"))1425                .to_request(),1426        )1427        .await;1428        assert_eq!(response.status(), StatusCode::OK);1429        assert_eq!(*requested_tails.lock().unwrap(), [500, 100]);14301431        let response = actix_test::call_service(1432            &app,1433            actix_test::TestRequest::get()1434                .uri("/api/v1/apps/writer.example.test/logs?timestamps=true")1435                .insert_header(("Authorization", "Bearer test-secret"))1436                .to_request(),1437        )1438        .await;1439        assert_eq!(response.status(), StatusCode::OK);1440        let logs: serde_json::Value = actix_test::read_body_json(response).await;1441        assert_eq!(logs["output"], "2026-11-21T14:03:04.123456789Z app log");14421443        let response = actix_test::call_service(1444            &app,1445            actix_test::TestRequest::get()1446                .uri("/api/v1/apps/writer.example.test/logs?timestamps=maybe")1447                .insert_header(("Authorization", "Bearer test-secret"))1448                .to_request(),1449        )1450        .await;1451        assert_eq!(response.status(), StatusCode::BAD_REQUEST);1452    }14531454    #[test]1455    fn validates_environment_names_and_values_before_docker_sees_them() {1456        assert!(valid_env_name("DATABASE_URL"));1457        assert!(valid_env_name("_private2"));1458        assert!(!valid_env_name("2FA_SECRET"));1459        assert!(!valid_env_name("BAD-NAME"));1460        assert!(!valid_env_name("KEY=VALUE"));1461        assert!(!valid_env_name(""));14621463        let valid = BTreeMap::from([("MODE".to_owned(), "a value with spaces".to_owned())]);1464        assert!(validate_env(&valid).is_ok());1465        let nul_value = BTreeMap::from([("MODE".to_owned(), "a\0b".to_owned())]);1466        assert!(validate_env(&nul_value).is_err());1467        let bad_name = BTreeMap::from([("BAD NAME".to_owned(), "x".to_owned())]);1468        assert!(validate_env(&bad_name).is_err());1469    }14701471    #[actix_web::test]1472    async fn environment_routes_replace_custom_variables_and_reject_bad_names() {1473        let (state, _removed_data, _requested_tails) = api_state();1474        let app = actix_test::init_service(1475            App::new()1476                .app_data(web::Data::new(state))1477                .configure(configure_app),1478        )1479        .await;14801481        let response = actix_test::call_service(1482            &app,1483            actix_test::TestRequest::get()1484                .uri("/api/v1/apps/writer.example.test/env")1485                .to_request(),1486        )1487        .await;1488        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);14891490        let response = actix_test::call_service(1491            &app,1492            actix_test::TestRequest::get()1493                .uri("/api/v1/apps/writer.example.test/env")1494                .insert_header(("Authorization", "Bearer test-secret"))1495                .to_request(),1496        )1497        .await;1498        assert_eq!(response.status(), StatusCode::OK);1499        let environment: serde_json::Value = actix_test::read_body_json(response).await;1500        assert_eq!(environment["env"]["MODE"], "test");1501        assert!(1502            environment["reserved"]1503                .as_array()1504                .unwrap()1505                .contains(&serde_json::json!("PORT"))1506        );15071508        let response = actix_test::call_service(1509            &app,1510            actix_test::TestRequest::put()1511                .uri("/api/v1/apps/writer.example.test/env")1512                .insert_header(("Authorization", "Bearer test-secret"))1513                .set_json(serde_json::json!({1514                    "env": {"MODE": "production", "API_TOKEN": "abc"}1515                }))1516                .to_request(),1517        )1518        .await;1519        assert_eq!(response.status(), StatusCode::OK);1520        let saved: serde_json::Value = actix_test::read_body_json(response).await;1521        assert_eq!(saved["env"]["API_TOKEN"], "abc");15221523        for body in [1524            serde_json::json!({"env": {"BAD-NAME": "x"}}),1525            serde_json::json!({"env": {"MODE": "a\u{0}b"}}),1526        ] {1527            let response = actix_test::call_service(1528                &app,1529                actix_test::TestRequest::put()1530                    .uri("/api/v1/apps/writer.example.test/env")1531                    .insert_header(("Authorization", "Bearer test-secret"))1532                    .set_json(body)1533                    .to_request(),1534            )1535            .await;1536            assert_eq!(response.status(), StatusCode::BAD_REQUEST);1537            let body = actix_test::read_body(response).await;1538            assert!(1539                String::from_utf8(body.to_vec())1540                    .unwrap()1541                    .contains("invalid_request")1542            );1543        }15441545        let response = actix_test::call_service(1546            &app,1547            actix_test::TestRequest::put()1548                .uri("/api/v1/apps/writer.example.test/env")1549                .insert_header(("Authorization", "Bearer test-secret"))1550                .set_json(serde_json::json!({"env": {"PORT": "8080"}}))1551                .to_request(),1552        )1553        .await;1554        assert_eq!(response.status(), StatusCode::BAD_REQUEST);1555        let body = actix_test::read_body(response).await;1556        assert!(1557            String::from_utf8(body.to_vec())1558                .unwrap()1559                .contains("reserved_environment")1560        );15611562        let response = actix_test::call_service(1563            &app,1564            actix_test::TestRequest::get()1565                .uri("/api/v1/apps/writer.example.test")1566                .insert_header(("Authorization", "Bearer test-secret"))1567                .to_request(),1568        )1569        .await;1570        assert_eq!(response.status(), StatusCode::OK);1571        let detail: serde_json::Value = actix_test::read_body_json(response).await;1572        assert_eq!(detail["host"], "writer.example.test");1573        assert_eq!(detail["isServer"], false);1574        assert_eq!(detail["disableTLS"], false);1575        assert_eq!(detail["resources"]["memoryMB"], 256);1576        assert_eq!(detail["registry"]["username"], "registry-user");1577        assert!(detail["registry"].get("password").is_none());1578        assert!(detail["smtp"].get("password").is_none());1579    }15801581    #[cfg(feature = "docker-tests")]1582    #[actix_web::test]1583    async fn namespace_manager_reads_a_fresh_real_docker_namespace() {1584        use super::NamespaceManager;1585        use crate::commands::once::{docker::DockerEngine, namespace::Namespace};15861587        let suffix = std::time::SystemTime::now()1588            .duration_since(std::time::UNIX_EPOCH)1589            .unwrap()1590            .as_nanos();1591        let namespace_name = format!("ino-api-read-{}-{suffix}", std::process::id());1592        let engine = Arc::new(DockerEngine::connect().unwrap());1593        let namespace = Namespace::restore(engine, namespace_name).await.unwrap();1594        let manager = Arc::new(NamespaceManager::new(Arc::new(tokio::sync::Mutex::new(1595            namespace,1596        ))));1597        let state = ApiState::new("docker-test-key".into(), manager);1598        let app = actix_test::init_service(1599            App::new()1600                .app_data(web::Data::new(state))1601                .route("/up", web::get().to(health))1602                .configure(configure_app),1603        )1604        .await;16051606        let response = actix_test::call_service(1607            &app,1608            actix_test::TestRequest::get()1609                .uri("/api/v1/apps")1610                .insert_header(("Authorization", "Bearer docker-test-key"))1611                .to_request(),1612        )1613        .await;1614        assert_eq!(response.status(), StatusCode::OK);1615        let apps: serde_json::Value = actix_test::read_body_json(response).await;1616        assert_eq!(apps, serde_json::json!([]));1617    }1618}