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
127 changes: 120 additions & 7 deletions crates/harness-cli/src/host/application/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,18 @@ impl InteractiveController {
/// has to be: a key must never act on a list the user cannot see. The plain
/// renderer draws no menu, and a panel or picker that owns the keyboard
/// replaces it, so neither may consume an arrow or an Enter for it.
/// The highlight is on a flag the menu offered on a blank word, and the
/// person did not move it there.
fn offered_flag(&self) -> bool {
!self.editor.suggestion_moved()
&& self.editor.display_buffer().ends_with(' ')
&& self
.editor
.suggestions()
.get(self.editor.suggestion_selected())
.is_some_and(|item| item.label.starts_with('-'))
}

fn suggestion_menu_open(&self) -> bool {
!self.plain
&& self.pending_approval.is_none()
Expand Down Expand Up @@ -1621,6 +1633,12 @@ impl InteractiveController {
// through it, as prime-agent's and Claude Code's panels are, and the
// composer is not being typed into while one is up. Escape still
// closes it, which is what acceptance U09 asserts.
// Typing means the person is done reading: the panel closes and
// the key goes to the composer, which shows its cursor and its
// menu again (`/features`, then `/` opens the command menu).
if matches!(key, Key::Char(character) if !character.is_control()) {
let _ = self.editor.take_overlay();
}
let scrolled = match key {
Key::Up => self.editor.scroll_overlay(-1),
Key::Down => self.editor.scroll_overlay(1),
Expand Down Expand Up @@ -1742,12 +1760,21 @@ impl InteractiveController {
self.editor.accept_suggestion();
return vec![Effect::Redraw];
}
Key::Enter => {
// A flag the menu offers on a blank word is optional: Enter
// runs the line as it is (`/new ` starts a session) unless the
// person moved the highlight to the flag. A command whose
// blank offers nothing (`/resume`, `/learn`) runs once its
// name is completed.
Key::Enter if !self.offered_flag() => {
let embedded = self.editor.suggestion_is_embedded();
self.editor.accept_suggestion();
let line = self.editor.display_buffer();
let whole = line
.strip_suffix(' ')
.is_some_and(super::commands::runs_bare);
if embedded
|| self.editor.display_buffer().ends_with(' ')
|| !self.editor.suggestions().is_empty()
|| (!whole
&& (line.ends_with(' ') || !self.editor.suggestions().is_empty()))
{
return vec![Effect::Redraw];
}
Expand Down Expand Up @@ -10730,8 +10757,8 @@ Command: \"npm run build\""
"plain mode must not complete a list it never showed: {lines}"
);

// TUI with a panel open: the panel owns the frame, so the same draft is
// submitted rather than silently completed into a list nobody can see.
// TUI with a panel open: typing closes it, so the menu that answers
// the draft is the one on screen.
let mut tui = tui_bench(true);
let _ = tui.controller.boot_lines();
let _ = submit_text(&mut tui.controller, "/help");
Expand All @@ -10741,9 +10768,14 @@ Command: \"npm run build\""
);
type_text(&mut tui.controller, "/he");
assert!(
!tui.controller.ui_state().suggestions.is_empty(),
"the editor still holds the candidates; the frame is what hides them"
tui.controller.ui_state().modal.is_none(),
"typing closed it"
);
assert!(
tui.controller.suggestion_menu_open(),
"the menu for the draft is drawn"
);
let _ = tui.controller.handle_key(Key::Esc);
let _ = tui.controller.handle_key(Key::Enter);
assert!(
tui.controller
Expand Down Expand Up @@ -14426,6 +14458,87 @@ Command: \"npm run build\""
assert!(!harness.controller.editor.suggestions().is_empty());
}

/// A panel open (`/features`) does not keep the composer from being typed
/// into: a typed key closes it, and the menu answers that key.
#[test]
fn typing_closes_a_reference_panel_and_reaches_the_composer() {
let harness = tui_bench(true);
let mut controller = harness.controller;
let _ = controller.boot_lines();
controller
.editor
.open_overlay("/features", vec!["no feature list".to_owned()]);
let _ = controller.handle_key(Key::Down);
assert!(controller.editor.overlay().is_some(), "arrows scroll it");
type_text(&mut controller, "/fe");
assert!(controller.editor.overlay().is_none());
assert_eq!(controller.editor.text(), "/fe");
assert!(controller.suggestion_menu_open(), "the menu is back");
}

/// A command whose argument is optional shows what it takes and runs on
/// Enter, typed in full or completed from its beginning.
#[test]
fn an_optional_argument_command_runs_on_enter() {
let harness = tui_bench(true);
let mut controller = harness.controller;
let _ = controller.boot_lines();
type_text(&mut controller, "/resume");
assert!(
controller.editor.suggestions()[0]
.label
.starts_with("/resume ["),
"{:?}",
controller.editor.suggestions()
);
let _ = controller.handle_key(Key::Enter);
assert_eq!(controller.editor.text(), "", "Enter ran /resume");
type_text(&mut controller, "/resu");
let _ = controller.handle_key(Key::Enter);
assert_eq!(
controller.editor.text(),
"",
"Enter completed and ran /resume"
);
}

/// A blank word offers the command's flags; Enter runs the line as it is,
/// and a flag the person moves to is what Enter takes.
#[test]
fn a_blank_word_offers_the_flags_and_enter_runs_the_line() {
let harness = tui_bench(true);
let mut controller = harness.controller;
let _ = controller.boot_lines();
type_text(&mut controller, "/refine ");
assert!(
controller
.editor
.suggestions()
.iter()
.any(|item| item.label.starts_with("--rollback")),
"{:?}",
controller.editor.suggestions()
);
let _ = controller.handle_key(Key::Enter);
assert_eq!(controller.editor.text(), "", "Enter ran /refine as typed");
type_text(&mut controller, "/refine ");
let _ = controller.handle_key(Key::Down);
let _ = controller.handle_key(Key::Enter);
assert_eq!(
controller.editor.text(),
"/refine --rollback ",
"the flag moved to is taken"
);
// `/new` shows its flags first; the second Enter starts the session.
controller.editor.set_text("");
type_text(&mut controller, "/new");
let _ = controller.handle_key(Key::Enter);
assert_eq!(controller.editor.text(), "/new ");
assert!(!controller.editor.suggestions().is_empty(), "its flags");
let _ = controller.handle_key(Key::Enter);
assert_eq!(controller.editor.text(), "", "Enter ran /new");
}

/// The person's way through the review queue: `/memory` lists the waiting
/// changes, and typing the accept offers the action and then each id;
/// Enter on an id accepts it, and the next menu no longer offers it.
Expand Down
156 changes: 134 additions & 22 deletions crates/harness-cli/src/host/integrations/mcp_oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,25 @@ fn authorization_server_metadata_urls(issuer: &Url) -> Vec<String> {

/// The `resource_metadata` pointer of a `WWW-Authenticate` header.
fn header_resource_metadata(value: &str) -> Option<String> {
header_parameter(value, "resource_metadata")
}

/// The `scope` a `WWW-Authenticate` header asks for (MCP's scope selection).
fn header_scope(value: &str) -> Option<String> {
header_parameter(value, "scope").filter(|scope| !scope.trim().is_empty())
}

/// One quoted parameter of a `WWW-Authenticate` header, by its exact name.
fn header_parameter(value: &str, name: &str) -> Option<String> {
let lower = value.to_ascii_lowercase();
let at = lower.find("resource_metadata")?;
let rest = value[at + "resource_metadata".len()..].trim_start();
let at = lower.match_indices(name).map(|(at, _)| at).find(|&at| {
lower[..at]
.chars()
.next_back()
.is_none_or(|before| before == ',' || before.is_whitespace())
&& lower[at + name.len()..].trim_start().starts_with('=')
})?;
let rest = value[at + name.len()..].trim_start();
let rest = rest.strip_prefix('=')?.trim_start().strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
Expand Down Expand Up @@ -264,15 +280,50 @@ fn discover_server(issuer: &str) -> Result<ServerMetadata, String> {
))
}

/// What discovery found: the server metadata, and the resource indicator
/// when the server publishes protected-resource metadata.
fn discover(url: &str) -> Result<(ServerMetadata, Option<String>), String> {
/// What discovery found: the server metadata, the resource indicator when
/// the server publishes protected-resource metadata, and the scope to ask for.
struct Discovered {
metadata: ServerMetadata,
resource: Option<String>,
scope: Option<String>,
}

/// MCP's scope selection: the scope the server's challenge names, else the
/// resource's own `scopes_supported`. The authorization server's list is the
/// whole server's and may hold scopes this client may not ask for (Vercel's
/// `ema_issuer:manage`, refused as `invalid_scope`); it is asked for only
/// when the server publishes no resource metadata.
fn chosen_scope(
challenge: Option<String>,
resource_metadata: Option<&serde_json::Value>,
server: &ServerMetadata,
) -> Option<String> {
let joined = |scopes: Vec<String>| Some(scopes.join(" ")).filter(|scope| !scope.is_empty());
challenge.or_else(|| match resource_metadata {
Some(value) => joined(
value
.get("scopes_supported")
.and_then(serde_json::Value::as_array)
.map(|scopes| {
scopes
.iter()
.filter_map(|scope| scope.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default(),
),
None => server.scopes_supported.clone().and_then(joined),
})
}

fn discover(url: &str) -> Result<Discovered, String> {
let resource_url = validated_url(url, "MCP server URL")?;
// The probe never carries a token.
let pointer = http("GET", url, None, None)
let challenge = http("GET", url, None, None)
.ok()
.and_then(|(_, authenticate, ..)| authenticate)
.and_then(|value| header_resource_metadata(&value));
.and_then(|(_, authenticate, ..)| authenticate);
let pointer = challenge.as_deref().and_then(header_resource_metadata);
let challenge_scope = challenge.as_deref().and_then(header_scope);
let candidate = match &pointer {
Some(pointer) => validated_url(pointer, "resource_metadata")?.to_string(),
None => resource_metadata_url(&resource_url),
Expand All @@ -293,12 +344,21 @@ fn discover(url: &str) -> Result<(ServerMetadata, Option<String>), String> {
.ok_or_else(|| {
"Protected-resource metadata has no authorization_servers".to_owned()
})?;
Ok((discover_server(issuer)?, Some(resource)))
let metadata = discover_server(issuer)?;
Ok(Discovered {
scope: chosen_scope(challenge_scope, Some(&value), &metadata),
metadata,
resource: Some(resource),
})
}
Ok(None) if pointer.is_none() => {
let metadata = discover_server(&resource_url.origin().ascii_serialization())?;
Ok(Discovered {
scope: chosen_scope(challenge_scope, None, &metadata),
metadata,
resource: None,
})
}
Ok(None) if pointer.is_none() => Ok((
discover_server(&resource_url.origin().ascii_serialization())?,
None,
)),
Ok(None) => Err(format!("GET {candidate} failed: 404")),
Err(error) => Err(error),
}
Expand Down Expand Up @@ -497,7 +557,11 @@ pub fn login(
progress: &dyn Fn(&str),
) -> Result<(), String> {
progress(&format!("Discovering OAuth metadata for {server}..."));
let (metadata, resource) = discover(url)?;
let Discovered {
metadata,
resource,
scope: discovered_scope,
} = discover(url)?;
let client_id = if let Some(client_id) = client_id {
client_id.to_owned()
} else {
Expand All @@ -516,12 +580,7 @@ pub fn login(
let redirect = redirect_uri(port);
let scope = scopes
.map(str::to_owned)
.or_else(|| {
metadata
.scopes_supported
.as_ref()
.map(|scopes| scopes.join(" "))
})
.or(discovered_scope)
.unwrap_or_default();
let mut params = vec![
("client_id", client_id.as_str()),
Expand Down Expand Up @@ -677,8 +736,9 @@ mod tests {
}

use super::{
authorization_server_metadata_urls, canonical_resource, code_from,
header_resource_metadata, resource_metadata_url, server_metadata, validated_url,
authorization_server_metadata_urls, canonical_resource, chosen_scope, code_from,
header_resource_metadata, header_scope, resource_metadata_url, server_metadata,
validated_url,
};
use reqwest::Url;

Expand Down Expand Up @@ -801,6 +861,58 @@ mod tests {
);
}

#[test]
fn the_scope_is_the_challenge_s_then_the_resource_s_not_the_server_s() {
// Vercel: the authorization server lists a scope a client may not ask
// for; the resource asks for `openid` only.
let server = server_metadata(
&serde_json::json!({
"issuer": "https://vercel.com",
"authorization_endpoint": "https://vercel.com/oauth/authorize",
"token_endpoint": "https://api.vercel.com/login/oauth/token",
"scopes_supported": ["openid", "email", "profile", "offline_access", "ema_issuer:manage"],
}),
"https://vercel.com",
)
.expect("metadata");
let resource = serde_json::json!({
"resource": "https://mcp.vercel.com/",
"authorization_servers": ["https://vercel.com"],
"scopes_supported": ["openid"],
});
assert_eq!(
chosen_scope(None, Some(&resource), &server).as_deref(),
Some("openid")
);
let challenge = header_scope(
r#"Bearer error="insufficient_scope", scope="files:read files:write", resource_metadata="https://x/.well-known/oauth-protected-resource""#,
);
assert_eq!(challenge.as_deref(), Some("files:read files:write"));
assert_eq!(
chosen_scope(challenge, Some(&resource), &server).as_deref(),
Some("files:read files:write")
);
// Resource metadata without scopes asks for none.
let bare =
serde_json::json!({"resource": "https://x/", "authorization_servers": ["https://x"]});
assert_eq!(chosen_scope(None, Some(&bare), &server), None);
// No resource metadata at all: the server's own list, as before.
assert!(
chosen_scope(None, None, &server)
.is_some_and(|scope| scope.starts_with("openid email"))
);
// `resource_metadata` is not read as `scope`, nor the reverse.
assert_eq!(
header_scope(r#"Bearer resource_metadata="https://x/meta""#),
None
);
assert_eq!(
header_resource_metadata(r#"Bearer scope="a", resource_metadata="https://x/meta""#)
.as_deref(),
Some("https://x/meta")
);
}

#[test]
fn metadata_and_redirects_are_checked() {
let metadata = server_metadata(
Expand Down
Loading
Loading