diff --git a/src/commands/connect.rs b/src/commands/connect.rs index 1227343..a44fbcd 100644 --- a/src/commands/connect.rs +++ b/src/commands/connect.rs @@ -205,7 +205,14 @@ fn move_history(scratch: &Path, hosted: &AppSource, repo: &str, rerun: &str) -> let hosted_url = format!("https://github.com/{hosted_repo}.git"); let target_url = format!("https://github.com/{repo}.git"); let mirror = scratch.join("hosted.git"); - let cloned = hosted_git(scratch, &hosted_url) + let mut clone = hosted_git(scratch, &hosted_url).map_err(|error| { + Stop( + format!("{} Nothing changed.", error.message), + "GIT_CLONE_FAILED", + rerun.to_string(), + ) + })?; + let cloned = clone .args(["clone", "--bare", "--quiet", "--"]) .arg(&hosted_url) .arg(&mirror) diff --git a/src/commands/deploy.rs b/src/commands/deploy.rs index 87d0ebf..ef87f73 100644 --- a/src/commands/deploy.rs +++ b/src/commands/deploy.rs @@ -27,7 +27,6 @@ const POLL_TIMEOUT: Duration = Duration::from_secs(1200); struct EnvInjectionPlan { mode: String, services: Vec, - notes: Vec, } #[derive(Debug, Serialize)] @@ -738,34 +737,39 @@ fn run_preflight( } // --- Human output --- - display_preflight_human( - &app_name, - &resolved, - &services, - &per_service_detection, - &runtime_plan, - &env_injection_plan, - &validation_findings, - ); + if !reports { + // `floo deploy` shows only what needs attention; the deploy prints its own progress. + print_warnings(&all_findings); + } else { + display_preflight_human( + &app_name, + &resolved, + &services, + &per_service_detection, + &runtime_plan, + &env_injection_plan, + &validation_findings, + ); - if !managed_services.is_empty() { - eprintln!(" Managed services (declared):"); - for ms in &managed_services { - let tier_label = ms.tier.as_deref().unwrap_or("basic"); - eprintln!(" {} (tier {tier_label})", ms.env_handle()); + if !managed_services.is_empty() { + eprintln!(" Managed services:"); + for ms in &managed_services { + let tier_label = ms.tier.as_deref().unwrap_or("basic"); + eprintln!(" {} ({tier_label})", ms.env_handle()); + } + eprintln!(); } - eprintln!(); - } - if let Some(ref plan) = remote_plan { - render_plan_human(plan, &app_name); - } - if app_not_created { - eprintln!(" {}", app_not_created_note(&app_name)); - eprintln!(); - } + if let Some(ref plan) = remote_plan { + render_plan_human(plan, &app_name); + } + if app_not_created { + eprintln!(" {}", app_not_created_note(&app_name)); + eprintln!(); + } - render_security_findings_human(&security_findings); + render_security_findings_human(&security_findings); + } if !valid { for f in all_findings.iter().filter(|f| f.is_error()) { @@ -780,26 +784,23 @@ fn run_preflight( process::exit(1); } - match &deploy_plan { - Some(preview) => { - let warn_count = all_findings - .iter() - .filter(|f| f.severity == Severity::Warning) - .count(); - eprintln!(); - if warn_count > 0 { - output::success( - &format!("Config valid with {warn_count} warning(s); review them above."), - None, - ); - } else { - output::success("Config valid.", None); - } - for line in preview.summary.lines() { - eprintln!(" {line}"); - } + if let Some(preview) = &deploy_plan { + let warn_count = all_findings + .iter() + .filter(|f| f.severity == Severity::Warning) + .count(); + eprintln!(); + if warn_count > 0 { + output::success( + &format!("Config valid with {warn_count} warning(s); review them above."), + None, + ); + } else { + output::success("Config valid.", None); + } + for line in preview.summary.lines() { + eprintln!(" {line}"); } - None => print_preflight_ready(&all_findings), } (resolved, services, primary_detection) } @@ -2033,14 +2034,9 @@ fn build_env_injection_plan( .map(|ms| ms.env_handle()) .collect::>(); - let mut notes = Vec::new(); let mode = if explicit_managed { "explicit".to_string() } else if !declared_handles.is_empty() { - notes.push( - "No service declares env.managed, so managed service credentials use legacy implicit injection." - .to_string(), - ); "implicit_all".to_string() } else { "none".to_string() @@ -2085,28 +2081,22 @@ fn build_env_injection_plan( EnvInjectionPlan { mode, services: service_plans, - notes, } } fn display_env_injection_plan(plan: &EnvInjectionPlan) { - eprintln!(" Env injection plan:"); - match plan.mode.as_str() { - "explicit" => eprintln!(" mode: explicit per-service env.managed"), - "implicit_all" => eprintln!(" mode: legacy implicit managed env on every service"), - _ => eprintln!(" mode: no managed service credentials declared locally"), - } - for note in &plan.notes { - eprintln!(" note: {note}"); + if plan + .services + .iter() + .all(|svc| svc.managed.is_empty() && svc.required.is_empty() && svc.optional.is_empty()) + { + return; } + eprintln!(" Env vars:"); for svc in &plan.services { eprintln!(" {}", svc.service); - if svc.managed.is_empty() { - eprintln!(" managed: none"); - } else { - for managed in &svc.managed { - eprintln!(" {} -> {}", managed.handle, managed.keys.join(", ")); - } + for managed in &svc.managed { + eprintln!(" {}: {}", managed.handle, managed.keys.join(", ")); } if !svc.required.is_empty() { eprintln!(" required: {}", svc.required.join(", ")); @@ -2185,10 +2175,7 @@ fn display_preflight_human( .as_deref() .map(|f| format!(" ({f})")) .unwrap_or_default(); - eprintln!( - " runtime: {}{framework_label} \u{2014} {} confidence", - det.runtime, det.confidence - ); + eprintln!(" runtime: {}{framework_label}", det.runtime); if runtime.availability == "paused" { eprintln!(" availability: paused, 0 running instances"); } else if runtime.availability == "fixed" { @@ -2211,7 +2198,6 @@ fn display_preflight_human( for note in &runtime.notes { eprintln!(" note: {note}"); } - eprintln!(" note: plan limits are resolved by the server; verify with `floo services show --json`"); eprintln!(); } @@ -2245,6 +2231,10 @@ fn display_preflight_human( } } + print_warnings(findings); +} + +fn print_warnings(findings: &[PreflightFinding]) { for f in findings.iter().filter(|f| f.severity == Severity::Warning) { // The root service uses path "." — a "." : prefix there is just noise. match f.path.as_deref() { @@ -2268,33 +2258,6 @@ fn render_security_findings_human(findings: &[PreflightFinding]) { eprintln!(); } -/// Print the auto-deploy contract and the final "ready" line. Only called when -/// the config has no errors; the warning count keeps a clean green honest. -fn print_preflight_ready(findings: &[PreflightFinding]) { - // Closes feedback c9b70eb5: "no obvious signal anywhere in the floo - // workflow that dev auto-deploys on GitHub push." The CLI is the surface - // the user is in front of right before pushing — surfacing the auto-deploy - // contract here means they don't have to leave for the docs. - eprintln!(); - eprintln!(" Deploys: dev auto-deploys on every `git push` to your default branch."); - eprintln!(" See https://getfloo.com/docs/guides/golden-path.md for the full flow."); - - let warn_count = findings - .iter() - .filter(|f| f.severity == Severity::Warning) - .count(); - if warn_count > 0 { - output::success( - &format!( - "Config valid with {warn_count} warning(s) \u{2014} review the warnings above before deploying." - ), - None, - ); - } else { - output::success("Config valid \u{2014} ready to deploy.", None); - } -} - /// Stream deploy logs via SSE and return the final deploy state. pub(crate) fn stream_deploy( client: &FlooClient, diff --git a/src/commands/projects.rs b/src/commands/projects.rs index 3322174..06eff1b 100644 --- a/src/commands/projects.rs +++ b/src/commands/projects.rs @@ -1,3 +1,4 @@ +use std::env; use std::io::{self, BufRead}; use std::path::Path; use std::process::{self, Command, Stdio}; @@ -8,6 +9,10 @@ use crate::errors::{ErrorCode, FlooApiError}; use crate::output; use crate::resolve::resolve_app; +/// The app and push token floo's own git commands pass to `floo git-credential`. +pub(crate) const GIT_TOKEN_APP_ENV: &str = "FLOO_GIT_APP_ID"; +pub(crate) const GIT_TOKEN_ENV: &str = "FLOO_GIT_TOKEN"; + fn fail(error: FlooApiError) -> ! { let next = if error.status_code == 401 || error.code == "NOT_AUTHENTICATED" { "next: floo auth login" @@ -233,10 +238,17 @@ pub fn git_credential(operation: &str) { )) }); let Some(app_id) = app_id else { return }; - let credential = client() - .project_git_token(&app_id) - .unwrap_or_else(|error| fail(error)); - output::git_credentials(&credential.token).unwrap_or_else(|_| { + // floo's own git commands fetch the token first and hand it over here. + let token = match (env::var(GIT_TOKEN_APP_ENV), env::var(GIT_TOKEN_ENV)) { + (Ok(for_app), Ok(token)) if for_app == app_id => token, + _ => { + client() + .project_git_token(&app_id) + .unwrap_or_else(|error| fail(error)) + .token + } + }; + output::git_credentials(&token).unwrap_or_else(|_| { fail(FlooApiError::new( 0, "INVALID_RESPONSE", diff --git a/src/commands/ship.rs b/src/commands/ship.rs index 4cf6717..260cc88 100644 --- a/src/commands/ship.rs +++ b/src/commands/ship.rs @@ -14,11 +14,11 @@ use serde_json::{json, Value}; use crate::api_client::FlooClient; use crate::api_types::{AppSource, DeployPlan}; -use crate::errors::ErrorCode; +use crate::errors::{ErrorCode, FlooApiError}; use crate::output; use crate::project_config::{self, AppAccessMode, AppFileConfig}; -use super::projects::{managed_app_id, shell_quote}; +use super::projects::{managed_app_id, shell_quote, GIT_TOKEN_APP_ENV, GIT_TOKEN_ENV}; /// The remote a hosted repo gets when `origin` already points elsewhere. const HOSTED_REMOTE: &str = "floo"; @@ -737,7 +737,7 @@ fn dev_access_mode(config: &AppFileConfig, plan: &DeployPlan) -> Option } } -/// Said when only the org can open the app, since a plain request then gets 401. +/// Said when only the org can open the app. fn access_note(config: &AppFileConfig, plan: &DeployPlan) -> Option { if dev_access_mode(config, plan).as_deref() != Some("accounts") { return None; @@ -750,9 +750,7 @@ fn access_note(config: &AppFileConfig, plan: &DeployPlan) -> Option { your users can't reach it. Set {table} access_mode = \"public\" in floo.app.toml." )); } - let mut note = format!( - "Only signed-in members of {org} can open it; a request without a floo sign-in gets 401." - ); + let mut note = format!("Only signed-in members of {org} can open it."); if config.dev_access_mode().is_none() { note.push_str(" For a public site, set [app] access_mode = \"public\" in floo.app.toml."); } @@ -967,18 +965,21 @@ fn push_github(path: &Path, remote: &str, branch: &str, head: &str, quoted: &str /// git with floo's short-lived token for a hosted repo, and no other credential /// helper, so no keychain stores the token. Refuses any URL that isn't a /// credential-free floo-hosted HTTPS URL, as `projects clone` does. -pub(crate) fn hosted_git(path: &Path, clone_url: &str) -> Command { - if clone_url +/// +/// floo asks for the token before git runs, so a failure is floo's own error, +/// and git may never prompt: a prompt from inside a deploy looks like a hang. +pub(crate) fn hosted_git(path: &Path, clone_url: &str) -> Result { + let Some(app_id) = clone_url .strip_prefix("https://github.com/") .and_then(managed_app_id) - .is_none() - { - stop( - "The app's hosted repository is not a floo-hosted repository.", + else { + return Err(FlooApiError::new( + 0, "INVALID_RESPONSE", - "Contact floo support with the app name.", - ); - } + "The app's hosted repository is not a floo-hosted repository. Contact floo support with the app name.", + )); + }; + let token = super::init_client(None).project_git_token(&app_id)?.token; let executable = std::env::current_exe() .ok() .and_then(|path| path.to_str().map(str::to_owned)) @@ -998,8 +999,13 @@ pub(crate) fn hosted_git(path: &Path, clone_url: &str) -> Command { let mut command = git(path); command .args(["-c", "credential.helper=", "-c", &helper]) - .args(["-c", "credential.useHttpPath=true"]); - command + .args(["-c", "credential.useHttpPath=true"]) + .env(GIT_TOKEN_APP_ENV, &app_id) + .env(GIT_TOKEN_ENV, token) + .env("GIT_TERMINAL_PROMPT", "0") + // Set but empty, so git skips core.askPass and SSH_ASKPASS too. + .env("GIT_ASKPASS", ""); + Ok(command) } /// Seconds to wait before each retry of a new hosted repo's first push. @@ -1014,7 +1020,14 @@ fn push_hosted(path: &Path, clone_url: &str, branch: &str, quoted: &str, new_rep let mut waits = waits.iter(); loop { // Push to the validated URL, not a remote name that could carry another pushurl. - let output = hosted_git(path, clone_url) + let mut push = hosted_git(path, clone_url).unwrap_or_else(|error| { + stop( + &error.message, + &error.code, + &format!("floo deploy {quoted}"), + ) + }); + let output = push .arg("push") .args([clone_url, refspec.as_str()]) // Keep stdout for floo's JSON; read git's errors to spot GitHub's 403. diff --git a/tests/connect_command_tests.rs b/tests/connect_command_tests.rs index 9a0cc2a..43ffdc8 100644 --- a/tests/connect_command_tests.rs +++ b/tests/connect_command_tests.rs @@ -159,13 +159,28 @@ fn mock_move(server: &mut Server) -> Mock { .create() } -fn hosted_app(server: &mut Server) -> Mock { - mock_apps( +/// A hosted app, and the push token floo asks for before git reads its repo. +fn hosted_app(server: &mut Server) -> Vec { + let token = server + .mock("POST", format!("/v1/apps/{APP_ID}/git-token").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + json!({ + "token": "push-token", + "expires_at": "2026-09-09T13:00:00Z", + "clone_url": format!("https://github.com/{HOSTED}.git"), + }) + .to_string(), + ) + .create(); + let apps = mock_apps( server, json!([app_with( json!({"kind": "floo", "repo": HOSTED, "branch": "main"}) )]), - ) + ); + vec![token, apps] } fn refs(bare: &Path) -> String { diff --git a/tests/deploy_command_tests.rs b/tests/deploy_command_tests.rs index 67a45f5..eea6013 100644 --- a/tests/deploy_command_tests.rs +++ b/tests/deploy_command_tests.rs @@ -65,7 +65,7 @@ fn setup(server: &Server) -> Env { std::fs::write( &shim, format!( - "#!/bin/sh\nfor arg in \"$@\"; do\n if [ \"$arg\" = push ]; then\n printf '%s\\n' \"$@\" > \"$PUSH_ARGS\"\n if [ -n \"$PUSH_403_ONCE\" ] && [ ! -e \"$PUSH_403_ONCE\" ]; then\n : > \"$PUSH_403_ONCE\"\n echo 'fatal: unable to access: The requested URL returned error: 403' >&2\n exit 128\n fi\n exit \"${{PUSH_EXIT:-0}}\"\n fi\n if [ \"$arg\" = ls-remote ]; then\n printf '%s' \"$LS_REMOTE\"\n exit 0\n fi\ndone\nexec {} \"$@\"\n", + "#!/bin/sh\nfor arg in \"$@\"; do\n if [ \"$arg\" = push ]; then\n printf '%s\\n' \"$@\" > \"$PUSH_ARGS\"\n printf '%s\\n' \"$GIT_TERMINAL_PROMPT\" \"$FLOO_GIT_APP_ID\" \"$FLOO_GIT_TOKEN\" > \"$PUSH_ARGS.env\"\n if [ -n \"$PUSH_403_ONCE\" ] && [ ! -e \"$PUSH_403_ONCE\" ]; then\n : > \"$PUSH_403_ONCE\"\n echo 'fatal: unable to access: The requested URL returned error: 403' >&2\n exit 128\n fi\n exit \"${{PUSH_EXIT:-0}}\"\n fi\n if [ \"$arg\" = ls-remote ]; then\n printf '%s' \"$LS_REMOTE\"\n exit 0\n fi\ndone\nexec {} \"$@\"\n", real_git() ), ) @@ -153,6 +153,32 @@ fn fails(env: &Env, args: &[&str]) -> Value { error(&out) } +/// The prompt switch and the app and token git ran with on the last push. +fn pushed_env(env: &Env) -> Vec { + std::fs::read_to_string(env.home.path().join("push-args.env")) + .unwrap() + .lines() + .map(str::to_string) + .collect() +} + +/// floo's push token for the hosted app, which deploy asks for before git runs. +fn mock_git_token(server: &mut Server) -> mockito::Mock { + server + .mock("POST", format!("/v1/apps/{APP_ID}/git-token").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + json!({ + "token": "push-token", + "expires_at": "2026-09-09T13:00:00Z", + "clone_url": format!("https://github.com/{REPO}.git"), + }) + .to_string(), + ) + .create() +} + fn pushed(env: &Env) -> Option> { std::fs::read_to_string(env.home.path().join("push-args")) .ok() @@ -764,6 +790,7 @@ fn a_taken_name_suggests_a_free_one_and_leaves_the_config_alone() { fn hosted_creates_an_empty_repo_adds_origin_and_pushes_without_force() { let mut server = Server::new(); let env = setup(&server); + let token = mock_git_token(&mut server); let sha = committed_repo(&env); let source = json!({"kind": "floo", "repo": REPO, "branch": "main"}); let planned = server @@ -812,12 +839,16 @@ fn hosted_creates_an_empty_repo_adds_origin_and_pushes_without_force() { "HEAD:refs/heads/main" ] ); + // floo fetched the token before git ran, and git may not prompt for one. + token.assert(); + assert_eq!(pushed_env(&env), ["0", APP_ID, "push-token"]); } #[test] fn a_new_hosted_repo_pushes_again_while_github_still_refuses_with_403() { let mut server = Server::new(); let env = setup(&server); + let _token = mock_git_token(&mut server); let sha = committed_repo(&env); let source = json!({"kind": "floo", "repo": REPO, "branch": "main"}); let _plan = server @@ -850,10 +881,48 @@ fn a_new_hosted_repo_pushes_again_while_github_still_refuses_with_403() { ); } +#[test] +fn a_push_token_floo_cannot_get_stops_before_git_runs() { + let mut server = Server::new(); + let env = setup(&server); + committed_repo(&env); + let _plan = server + .mock("POST", "/v1/deploy/plan") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(plan(json!({ + "ok": true, + "decision": "push", + "source": {"kind": "floo", "repo": REPO, "branch": "main"}, + }))) + .create(); + let _token = server + .mock("POST", format!("/v1/apps/{APP_ID}/git-token").as_str()) + .with_status(503) + .with_header("content-type", "application/json") + .with_body( + json!({"detail": { + "code": "PROJECT_REPO_NOT_READY", + "message": "The app's code is still being set up.", + }}) + .to_string(), + ) + .create(); + + let err = fails(&env, &[]); + assert_eq!(err["code"], "PROJECT_REPO_NOT_READY"); + assert!(err["suggestion"] + .as_str() + .unwrap() + .starts_with("floo deploy ")); + assert!(pushed(&env).is_none()); +} + #[test] fn an_existing_hosted_repo_does_not_retry_a_refused_push() { let mut server = Server::new(); let env = setup(&server); + let _token = mock_git_token(&mut server); committed_repo(&env); let _plan = server .mock("POST", "/v1/deploy/plan") @@ -882,6 +951,7 @@ fn an_existing_hosted_repo_does_not_retry_a_refused_push() { fn an_accepted_name_is_written_and_committed_before_the_push() { let mut server = Server::new(); let env = setup(&server); + let _token = mock_git_token(&mut server); committed_repo(&env); // A root service manifest names the app too, and must keep matching. std::fs::write( diff --git a/tests/projects_mock_api_tests.rs b/tests/projects_mock_api_tests.rs index b95d5bd..fa7ad75 100644 --- a/tests/projects_mock_api_tests.rs +++ b/tests/projects_mock_api_tests.rs @@ -90,6 +90,39 @@ fn token_mock(server: &mut Server, token: &str) -> mockito::Mock { .create() } +#[test] +fn credential_get_uses_the_token_floo_handed_over_for_that_app_only() { + let mut server = Server::new(); + let home = setup(&server); + let request = format!("protocol=https\nhost=github.com\npath={REPO}.git\n\n"); + let unused = server + .mock("POST", format!("/v1/apps/{APP_ID}/git-token").as_str()) + .expect(0) + .create(); + floo(&home) + .args(["git-credential", "get"]) + .env("FLOO_GIT_APP_ID", APP_ID) + .env("FLOO_GIT_TOKEN", "handed-over") + .write_stdin(request.clone()) + .assert() + .success() + .stdout("username=x-access-token\npassword=handed-over\n\n"); + unused.assert(); + unused.remove(); + + // A token for another app is never sent to this one. + let mock = token_mock(&mut server, TOKEN); + floo(&home) + .args(["git-credential", "get"]) + .env("FLOO_GIT_APP_ID", "ffffffff-ffff-ffff-ffff-ffffffffffff") + .env("FLOO_GIT_TOKEN", "handed-over") + .write_stdin(request) + .assert() + .success() + .stdout(format!("username=x-access-token\npassword={TOKEN}\n\n")); + mock.assert(); +} + #[test] fn credential_get_only_emits_password_protocol_and_fetches_each_time() { let mut server = Server::new();