Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,11 @@ it only reduces access, so it asks for no confirmation. `--json` prints `ok`,
`app_id`, `state`, `sole_publisher`, `ready`, `restarting`, `capabilities`,
`pending_capabilities`, `confirmed_at`, `message` and `approval_url`.

Both commands use your `bl auth login` session, with the same Kgoose settings as
`bl apps community list`, and need no `--base-url`. Exit codes follow the other `bl`
On a BuilderLab Blox workstation, both commands use the workstation's user identity
through the configured `BL_TOOLS_BASE_URL` proxy, without a local login or organization
configuration. The proxy defaults to Kgoose's internal `/cash-app/goose` prefix;
`--kgoose-service-path` or `KGOOSE_SERVICE_PATH` can override it. Elsewhere the commands
use your `bl auth login` session. Neither needs `--base-url`. Exit codes follow the other `bl`
commands: 3 when you need to log in, 4 when you are not the app's owner, 5 for a
network or server failure, and 1 for refusals such as `background_disabled` (not
available in this environment), `other_publishers` or an unsupported runtime. Each
Expand Down
204 changes: 184 additions & 20 deletions src/bl/apps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ use super::runner;
#[cfg(test)]
use super::skills_api::failure_info;
use super::skills_api::{exit_codes, failure, failure_trace_id, with_failure_trace_id, CliFailure};
use super::skills_config::{kgoose_service_url, SkillsConfig};
use super::skills_config::{
kgoose_service_url, normalize_kgoose_service_path, read_optional_env, SkillsConfig,
DEFAULT_KGOOSE_SERVICE_PATH, KGOOSE_SERVICE_PATH_ENV_VAR,
};
use super::static_site::{package_static_dir, NotFoundHandling};

const APPS_BASE_URL_ENV_VAR: &str = "BL_APPS_CONTROL_PLANE_URL";
Expand Down Expand Up @@ -868,9 +871,12 @@ pub fn run(matches: &ArgMatches) -> Result<()> {
}

fn dispatch(config: &SkillsConfig, matches: &ArgMatches) -> Result<()> {
if !uses_proxy_auth(matches)
&& !lists_communities_through_proxy(matches)
&& !refuses_community_list_on_this_workstation(matches)
let workstation_background = matches.subcommand_name() == Some("background")
&& super::workspace::workstation_base_url()?.is_some();
if !(uses_proxy_auth(matches)
|| lists_communities_through_proxy(matches)
|| refuses_community_list_on_this_workstation(matches)
|| workstation_background)
{
runner::ensure_org_configured(config)?;
}
Expand All @@ -891,7 +897,20 @@ fn dispatch(config: &SkillsConfig, matches: &ArgMatches) -> Result<()> {
Some(("debug", debug_matches)) => run_debug(config, debug_matches),
Some(("access", access_matches)) => run_access(config, access_matches),
Some(("community", community_matches)) => run_community(config, community_matches),
Some(("background", background_matches)) => run_background(config, background_matches),
Some(("background", background_matches)) => {
let mut config = config.clone();
if workstation_background {
// The workstation proxy calls Kgoose directly, bypassing the public BFF prefix.
config.kgoose_service_path = matches
.get_one::<String>("kgoose-service-path")
.cloned()
.or(read_optional_env(KGOOSE_SERVICE_PATH_ENV_VAR)?)
.map(|path| normalize_kgoose_service_path(&path))
.transpose()?
.unwrap_or_else(|| DEFAULT_KGOOSE_SERVICE_PATH.to_string());
}
run_background(&config, background_matches)
}
Some(("visibility", visibility_matches)) => run_visibility(config, visibility_matches),
Some(("publishers", publishers_matches)) => run_publishers(config, publishers_matches),
_ => anyhow::bail!("expected an apps subcommand"),
Expand Down Expand Up @@ -2175,7 +2194,7 @@ const BACKGROUND_ACCESS_TIMEOUT: Duration = Duration::from_secs(30);
const BACKGROUND_ACCESS_RESPONSE_MAX_BYTES: usize = 256 * 1024;

/// `status` reads and `off` revokes an owner's background tool call access for
/// one app, through Kgoose with the stored CLI session. Turning access on is
/// one app, through Kgoose with workstation authentication or a stored CLI session. Turning access on is
/// deliberately not here: Kgoose only takes that from the owner's browser, so
/// this prints the approval link and never approves.
fn run_background(config: &SkillsConfig, matches: &ArgMatches) -> Result<()> {
Expand Down Expand Up @@ -2225,12 +2244,11 @@ fn background_access_path(app_id: &str) -> String {
format!("/v1/hosted-apps/{app_id}/background-access")
}

fn background_access_url(config: &SkillsConfig, app_id: &str) -> Result<url::Url> {
fn background_access_url(service_url: &str, app_id: &str) -> Result<url::Url> {
if app_id.is_empty() || app_id == "." || app_id == ".." {
anyhow::bail!("APP_ID must be an app identifier returned by `bl apps list`");
}
let service_url = kgoose_service_url(&config.kgoose_base_url, &config.kgoose_service_path);
let mut url = url::Url::parse(&service_url).context("Kgoose URL must be absolute")?;
let mut url = url::Url::parse(service_url).context("Kgoose URL must be absolute")?;
url.path_segments_mut()
.map_err(|_| anyhow::anyhow!("Kgoose URL cannot carry a path"))?
.pop_if_empty()
Expand All @@ -2243,18 +2261,27 @@ fn background_access_call(
app_id: &str,
method: reqwest::Method,
) -> Result<Value> {
let storage = default_session_storage(config)?;
let session = storage
.get(&session_storage_key_from_config(config))?
.and_then(|credential| credential.session_credential_header_value())
.ok_or_else(auth_required_error)?;
let url = background_access_url(config, app_id)?;
let (base_url, session) = match super::workspace::workstation_base_url()? {
Some(base_url) => (base_url, None),
None => {
let storage = default_session_storage(config)?;
let session = storage
.get(&session_storage_key_from_config(config))?
.and_then(|credential| credential.session_credential_header_value())
.ok_or_else(auth_required_error)?;
(config.kgoose_base_url.clone(), Some(session))
}
};
let service_url = kgoose_service_url(&base_url, &config.kgoose_service_path);
let url = background_access_url(&service_url, app_id)?;
let path = background_access_path(app_id);
let mut request = build_auth_http_client(BACKGROUND_ACCESS_TIMEOUT)?
.request(method.clone(), url)
.header(USER_AGENT, CLI_USER_AGENT)
.header(ACCEPT, "application/json")
.header(SESSION_CREDENTIAL_HEADER, &session);
.header(ACCEPT, "application/json");
if let Some(session) = &session {
request = request.header(SESSION_CREDENTIAL_HEADER, session);
}
if let Some(baggage) = playpen_baggage(config.playpen.as_deref()) {
request = request.header("Baggage", baggage);
}
Expand All @@ -2277,12 +2304,21 @@ fn background_access_call(
)
})?;
let status = response.status();
let body = read_limited_response_body(
if status == StatusCode::UNAUTHORIZED && session.is_none() {
return Err(failure(
exit_codes::AUTH_REQUIRED,
"workstation_auth_required",
"Workstation authentication failed; ask the platform operator to check the workstation's credentials",
));
}
let mut body = read_limited_response_body(
response,
BACKGROUND_ACCESS_RESPONSE_MAX_BYTES,
"background tool call access",
)?
.replace(&session, "[REDACTED]");
)?;
if let Some(session) = &session {
body = body.replace(session, "[REDACTED]");
}
background_access_response(app_id, status, &body)
}

Expand Down Expand Up @@ -5200,6 +5236,7 @@ mod tests {
command.env_remove("BL_APPS_MANAGEMENT_BASE_URL");
command.env_remove(APPS_COMMUNITY_SHARING_ENV_VAR);
command.env_remove("BL_TOOLS_BASE_URL");
command.env_remove(KGOOSE_SERVICE_PATH_ENV_VAR);
command.env_remove("TRACEPARENT");
command
}
Expand Down Expand Up @@ -11915,6 +11952,133 @@ mod tests {
assert!(control_plane.finish().is_empty());
}

#[test]
fn bl_apps_background_uses_workstation_auth_without_a_local_login() {
for (action, method, state) in [
("status", "GET", "not_granted"),
("off", "DELETE", "revoked"),
] {
for json_output in [false, true] {
let kgoose = ProcessServer::start(vec![ProcessResponse::json(background_body(
state,
json!({}),
))]);
let control_plane = ProcessServer::start(vec![]);
let mut args = vec!["apps", "background", action, "my-app"];
if json_output {
args.push("--json");
}
let output =
process_command(&kgoose, &control_plane, &args, "apps-e2e-only.unused")
.env("BL_APPS_E2E_PROXY", "true")
.env("BL_TOOLS_BASE_URL", &kgoose.base_url)
.output()
.expect("run workstation background process");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = process_stdout(&output);
if json_output {
let response: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(response["state"], state);
} else {
assert!(
stdout.contains("Background tool calls for my-app: off"),
"{stdout}"
);
}
let requests = kgoose.finish();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].method, method);
assert_eq!(
requests[0].path,
"/cash-app/goose/v1/hosted-apps/my-app/background-access"
);
for header in ["authorization", "cookie", "x-bb-session-credential"] {
assert!(!requests[0].headers.contains_key(header), "{header}");
}
assert!(control_plane.finish().is_empty());
}
}
}

#[test]
fn bl_apps_background_workstation_auth_failure_does_not_ask_for_local_login() {
let kgoose = ProcessServer::start(vec![ProcessResponse::raw(401, "")]);
let control_plane = ProcessServer::start(vec![]);
let output = process_command(
&kgoose,
&control_plane,
&["apps", "background", "status", "demo", "--json"],
"apps-e2e-only.unused",
)
.env("BL_APPS_E2E_PROXY", "true")
.env("BL_TOOLS_BASE_URL", &kgoose.base_url)
.output()
.expect("run workstation background process");
assert_eq!(output.status.code(), Some(exit_codes::AUTH_REQUIRED));
let error = process_error(&output);
assert_eq!(error["error"]["code"], "workstation_auth_required");
assert!(!error.to_string().contains("bl auth login"));
assert_eq!(kgoose.finish().len(), 1);
assert!(control_plane.finish().is_empty());
}

#[test]
fn bl_apps_background_workstation_service_path_honors_environment_and_flag() {
for flag_override in [false, true] {
let kgoose = ProcessServer::start(vec![ProcessResponse::json(background_body(
"not_granted",
json!({}),
))]);
let control_plane = ProcessServer::start(vec![]);
let mut args = vec!["apps", "background", "status", "demo", "--json"];
if flag_override {
args.extend(["--kgoose-service-path", "flag/goose"]);
}
let output = process_command(&kgoose, &control_plane, &args, "apps-e2e-only.unused")
.env("BL_APPS_E2E_PROXY", "true")
.env("BL_TOOLS_BASE_URL", &kgoose.base_url)
.env(KGOOSE_SERVICE_PATH_ENV_VAR, "env/goose")
.output()
.expect("run workstation background process");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = kgoose.finish();
assert_eq!(requests.len(), 1);
let prefix = if flag_override { "flag" } else { "env" };
assert_eq!(
requests[0].path,
format!("/{prefix}/goose/v1/hosted-apps/demo/background-access")
);
assert!(control_plane.finish().is_empty());
}
}

#[test]
fn bl_apps_background_does_not_delegate_auth_outside_the_workstation_origin() {
let kgoose = ProcessServer::start(vec![]);
let control_plane = ProcessServer::start(vec![]);
let output = process_command(
&kgoose,
&control_plane,
&["apps", "background", "status", "demo", "--json"],
"apps-e2e-only.unused",
)
.env("BL_APPS_E2E_PROXY", "true")
.env("BL_TOOLS_BASE_URL", "http://proxy.mesh.example")
.output()
.expect("run workstation background process");
assert_eq!(output.status.code(), Some(exit_codes::AUTH_REQUIRED));
assert!(kgoose.finish().is_empty());
assert!(control_plane.finish().is_empty());
}

#[test]
fn background_access_errors_map_to_exit_codes_and_never_print_server_text() {
for (status, body, code, exit_code, explanation) in [
Expand Down