From 9031981ce37caa81c84e98de7b4273c77d429c02 Mon Sep 17 00:00:00 2001 From: Illia Polosukhin Date: Wed, 15 Jul 2026 05:53:17 +0000 Subject: [PATCH 1/5] =?UTF-8?q?test(reborn):=20channel-lifecycle=20transit?= =?UTF-8?q?ion=20coverage=20=E2=80=94=20delivery=20honesty,=20re-auth,=20e?= =?UTF-8?q?xit=20edges,=20OAuth=20retry,=20restart=20survival=20(#6105)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pins the five highest-priority channel-lifecycle state transitions from the #6105 issue-sweep classification, each at the deepest tier that can honestly reach it: - T1 use→deliver (#5944/#5943/#5877): chat.postMessage body targets the preference binding's DM; a Slack-rejected post on a Completed run records Failed, never Delivered (slack_delivery crate suite). - T2 revoked-token→re-auth (#5878): a provider 401 surfaces exclusively as the BlockedAuth gate — no generic Failed tool error, no hot retry (auth_gate integration suite). - T3 OAuth-extension exit edges (#6029/#6049): GitHub activate → use → remove → surfaces flip together → reconfigure + reactivate → use again (new scenario 7 in reborn_group_extensions). - T4 callback lost/replayed→retry (#2858/#2534/#6043): expired callback rejects terminally then a fresh flow succeeds; a replayed callback is idempotent on the durable services — a deliberate, now-documented divergence from the in-memory contract fake (oauth_connect suite). - T5 restart survival (#4556/#2939/#1327): connected/installed Slack state reads back through fresh store handles reopened at the same storage_root (new scenario 8 + test-support reopen seam). No production behavior changes; the two new seams are test-support-gated (zero bytes in production builds). Co-Authored-By: Claude Fable 5 --- .../src/factory.rs | 29 ++ .../src/slack/slack_delivery.rs | 96 ++++- .../test_support/slack_channel_connection.rs | 42 ++- tests/integration/auth_gate.rs | 21 ++ tests/integration/group_extensions/main.rs | 21 ++ ...ntial_extension_lifecycle_state_machine.rs | 175 +++++++++ .../scenario_slack_state_survives_reopen.rs | 89 +++++ tests/integration/oauth_connect.rs | 345 +++++++++++++++++- 8 files changed, 810 insertions(+), 8 deletions(-) create mode 100644 tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs create mode 100644 tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs diff --git a/crates/ironclaw_reborn_composition/src/factory.rs b/crates/ironclaw_reborn_composition/src/factory.rs index 37c4231866f..171ada11e18 100644 --- a/crates/ironclaw_reborn_composition/src/factory.rs +++ b/crates/ironclaw_reborn_composition/src/factory.rs @@ -3093,6 +3093,35 @@ fn local_dev_project_filesystem( Ok(filesystem) } +/// Test-only (C-SLACK-LIFECYCLE restart seam, issue #6105 T5): reopen the +/// composed Slack host-state filesystem at an existing local-dev +/// `storage_root` — a FRESH root filesystem (fresh durable-backend handles, +/// independent of the live runtime's `Arc`s) wrapped with the SAME +/// `slack_host_state_mount_view` production wraps it with. Mirrors the +/// production construction in [`build_reborn_services`] +/// (`local_dev_slack_host_state_filesystem` over the local-dev root), so a +/// restart-survival test proves durable Slack host state (identity bindings, +/// DM targets) is reconstructible the way a real process restart +/// reconstructs it. Tests only; zero bytes in production builds. +#[cfg(all( + feature = "test-support", + feature = "slack-v2-host-beta", + any(feature = "libsql", feature = "postgres") +))] +pub(crate) async fn open_local_dev_slack_host_state_filesystem_for_test( + storage_root: &Path, +) -> Result>, RebornBuildError> { + let workspace_root = storage_root.join("workspace"); + let bundle = build_local_dev_root_filesystem( + storage_root, + &workspace_root, + None, + LocalDevStorageBackendInput::LocalDefault, + ) + .await?; + Ok(local_dev_slack_host_state_filesystem(bundle.filesystem)) +} + /// Test-only (E-DURABLE seam): open a FRESH, independent /// [`ExtensionInstallationStore`] at an existing local-dev `storage_root`, /// paralleling how `assert_reply_persists_after_reopen` opens a fresh libsql diff --git a/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs b/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs index ce273e7cc7d..0fd418e4e6c 100644 --- a/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs +++ b/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs @@ -3742,16 +3742,104 @@ mod tests { let record = wait_for_delivery_record(&delivery_store, run_id).await; // Egress should have been called for chat.postMessage. + let post = egress + .calls() + .into_iter() + .find(|c| c.path == "/api/chat.postMessage") + .expect("expected chat.postMessage egress call"); + + // Right-target pin (#5943/#5877 shape, T1 of #6105): the posted body + // must carry the DM conversation id decoded from the saved + // preference's binding ref — not the run's current channel or another + // user's target. + let body = String::from_utf8(post.body).expect("postMessage body is UTF-8 JSON"); + assert!( + body.contains(r#""channel":"D456""#), + "chat.postMessage must target the preference binding's DM conversation; body: {body}" + ); + + // Outcome should be Delivered. + assert_eq!(record.outcome, TriggeredRunDeliveryOutcomeKind::Delivered); + } + + /// Delivery-honesty pin (#5944 shape, T1 of #6105): the RUN completed, but + /// Slack rejected the post (`200 {"ok":false,...}`). The delivery record + /// must say `Failed` — a `Delivered` here is exactly the "delivery + /// silently fails but run reports success" bug: run status alone cannot + /// distinguish the two, only this record can. + #[tokio::test] + async fn driver_slack_api_rejection_records_failed_not_delivered() { + let install = "test-install"; + let scope = personal_turn_scope(); + let run_id = TurnRunId::new(); + let binding_ref = + test_slack_binding_ref(install, scope.agent_id.as_ref().expect("agent").as_str()); + + let coordinator = Arc::new(ScriptedTurnCoordinator::with_single_status( + TurnStatus::Completed, + )); + let thread_service = Arc::new(InMemorySessionThreadService::default()); + seed_finalized_assistant_message(&thread_service, &scope, run_id, "Hello from Ironclaw") + .await; + + let outbound = Arc::new(InMemoryOutboundStateStore::default()); + seed_personal_preference(&outbound, &scope, binding_ref).await; + + // Slack accepts the HTTP call but rejects the post — the classic + // silent-failure shape (revoked channel, kicked bot, archived DM). + let egress = Arc::new(FakeProtocolHttpEgress::new(vec!["slack.com".to_string()])); + egress.allow_credential_handle("slack_bot_token"); + egress.program_response( + "slack.com", + Ok(EgressResponse::new( + 200, + serde_json::json!({"ok": false, "error": "channel_not_found"}) + .to_string() + .into_bytes(), + )), + ); + + let delivery_store = Arc::new(InMemoryTriggeredRunDeliveryStore::default()); + let route_store = Arc::new(InMemoryDeliveredGateRouteStore::default()); + let services = make_services( + coordinator, + thread_service, + egress.clone(), + outbound, + install, + ); + let settings = SlackFinalReplyDeliverySettings { + poll_interval: std::time::Duration::ZERO, + max_wait: std::time::Duration::from_secs(5), + max_concurrent_deliveries: NonZeroUsize::new(1).unwrap(), + max_pending_deliveries: NonZeroUsize::new(8).unwrap(), + }; + let driver = TriggeredRunDeliveryDriver::with_settings( + services, + settings, + delivery_store.clone(), + route_store.clone(), + scope.agent_id.clone().expect("test scope has agent"), + ); + + let fire = minimal_trigger_fire(None); + driver.on_trigger_submitted(fire, run_id, scope).await; + let record = wait_for_delivery_record(&delivery_store, run_id).await; + + // The post WAS attempted (this is not a skip/no-target case)… assert!( egress .calls() .iter() .any(|c| c.path == "/api/chat.postMessage"), - "expected chat.postMessage egress call" + "expected the rejected chat.postMessage egress call" + ); + // …and the rejection must be recorded as Failed, never Delivered. + assert_eq!( + record.outcome, + TriggeredRunDeliveryOutcomeKind::Failed, + "a Slack-rejected post on a Completed run must record Failed (#5944 honesty pair)" ); - - // Outcome should be Delivered. - assert_eq!(record.outcome, TriggeredRunDeliveryOutcomeKind::Delivered); } #[tokio::test] diff --git a/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs b/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs index 0d09a649eac..ea8cbd8b27a 100644 --- a/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs +++ b/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs @@ -61,6 +61,7 @@ pub struct SlackChannelConnectionTestConfig { /// See the module doc for the production call sites each method mirrors. pub struct SlackChannelConnectionTestBundle { tenant_id: TenantId, + host_user_id: UserId, agent_id: AgentId, installation_id: ironclaw_product_adapters::AdapterInstallationId, team_id: SlackTeamId, @@ -106,7 +107,7 @@ pub fn build_slack_channel_connection_for_test( let state = Arc::new(FilesystemSlackHostState::new( Arc::clone(&local_runtime.host_state_filesystem), tenant_id.clone(), - host_user_id, + host_user_id.clone(), agent_id.clone(), None, )); @@ -160,6 +161,7 @@ pub fn build_slack_channel_connection_for_test( } Ok(SlackChannelConnectionTestBundle { tenant_id, + host_user_id, agent_id, installation_id, team_id, @@ -223,6 +225,44 @@ impl SlackChannelConnectionTestBundle { Arc::clone(&self.facade) } + /// Restart-survival probe (T5 of issue #6105): read the SAME active-state + /// identity-binding predicate as + /// [`Self::has_any_active_identity_binding`], but through a FRESH + /// `FilesystemSlackHostState` over a FRESH local-dev root filesystem + /// reopened at `storage_root` — fully independent of the live runtime's + /// in-memory handles. This is the integration-tier approximation of a + /// process restart: it proves the durable binding is reconstructible the + /// way production reconstructs it on boot (`build_reborn_services` → + /// `local_dev_slack_host_state_filesystem` → Slack host-state mounts). + /// Tests only. + #[cfg(any(feature = "libsql", feature = "postgres"))] + pub async fn has_active_identity_binding_after_reopen( + &self, + storage_root: &std::path::Path, + user_id: &UserId, + ) -> Result { + let host_state_filesystem = + crate::factory::open_local_dev_slack_host_state_filesystem_for_test(storage_root) + .await + .map_err(|error| error.to_string())?; + let state = Arc::new(FilesystemSlackHostState::new( + host_state_filesystem, + self.tenant_id.clone(), + self.host_user_id.clone(), + self.agent_id.clone(), + None, + )); + let lookup: Arc = state; + lookup + .user_has_provider_binding_with_provider_user_id_prefix( + SLACK_IDENTITY_PROVIDER, + user_id, + None, + ) + .await + .map_err(|error| error.to_string()) + } + /// Surface (a) of the extensions page: what /// `list_extensions` merges via /// `ChannelConnectionFacade::caller_channel_connections` diff --git a/tests/integration/auth_gate.rs b/tests/integration/auth_gate.rs index 5b3ebec5385..68b4cd0f181 100644 --- a/tests/integration/auth_gate.rs +++ b/tests/integration/auth_gate.rs @@ -155,6 +155,27 @@ async fn runtime_401_after_injection_populates_provider_credential_requirement() wrong setup kind would route the WebUI to the wrong re-auth UI" ); + // T2 of the #6105 lifecycle transitions — the #5878 negative + // discriminator: a revoked/rejected token (provider 401) must surface + // EXCLUSIVELY as the re-auth gate asserted above, never as a generic + // model-visible failure ("the tool input could not be encoded" / "AI + // model provider was temporarily unavailable"). An empty reason matches + // any summary of the class, so this pins that NO Failed-classed tool + // error of any reason was persisted for the 401. + harness + .assert_no_tool_error(ToolErrorClass::Failed, "") + .await + .expect( + "a provider 401 must park at the auth gate, not persist a generic \ + Failed tool error (#5878 misleading-error regression)", + ); + // ...and it must not hot-retry the rejected credential: exactly the one + // 401 probe crossed the wire (#5878's "multiple retry attempts" shape). + harness + .assert_network_egress_count(1) + .await + .expect("a 401 must not be hot-retried against the provider"); + // Drain the run cleanly (deny) so the test doesn't leak a blocked run. harness .deny_auth_gate(run_id, &gate_ref) diff --git a/tests/integration/group_extensions/main.rs b/tests/integration/group_extensions/main.rs index ca7622327e0..1a37be173bb 100644 --- a/tests/integration/group_extensions/main.rs +++ b/tests/integration/group_extensions/main.rs @@ -20,10 +20,12 @@ mod support; // Modules are alphabetical (rustfmt reorders `mod` decls); execution order is // set by the `report.record(...)` sequence below, not declaration order. mod scenario_activate_then_active_cross_thread; +mod scenario_credential_extension_lifecycle_state_machine; mod scenario_install_then_visible_cross_thread; mod scenario_install_unknown_extension_id_fails_safely; mod scenario_remove_then_absent_cross_thread; mod scenario_slack_channel_lifecycle_state_machine; +mod scenario_slack_state_survives_reopen; mod scenario_uninstalled_tool_call_denied_until_activated; use reborn_support::group::{RebornIntegrationGroup, ScenarioReport}; @@ -83,5 +85,24 @@ async fn extensions_group_e2e() { scenario_slack_channel_lifecycle_state_machine::run(&g).await, ); + // Scenario 7 (issue #6105, T3): exit edges for a credential-injection + // extension — activate → use → remove (#6029's wedged edge) → surfaces + // flip → reconfigure + reactivate → use again. Reuses "github" AFTER + // every other scenario that reads it has run (scenario 1 leaves it + // installed), so its install exercises the idempotent-reinstall arm. + report.record( + "credential_extension_lifecycle_state_machine", + scenario_credential_extension_lifecycle_state_machine::run(&g).await, + ); + + // Scenario 8 (issue #6105, T5): restart survival — the connected/installed + // Slack state scenario 6 left behind reads back through FRESH store + // handles reopened at the same on-disk storage_root (what a process + // restart reconstructs). Depends on scenario 6's end state. + report.record( + "slack_state_survives_reopen", + scenario_slack_state_survives_reopen::run(&g).await, + ); + report.assert_all_passed(); } diff --git a/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs b/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs new file mode 100644 index 00000000000..a2aaf874a40 --- /dev/null +++ b/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs @@ -0,0 +1,175 @@ +//! Scenario 7 (T3 of issue #6105; the #6029/#6049 failure shapes): EXIT EDGES +//! for a credential-injection (OAuth-backed) extension — GitHub — through the +//! real lifecycle capabilities: activate → use → **remove** (the edge #6029 +//! reports as missing/wedged) → surfaces flip together → reconfigure (fresh +//! credential — the model-tool analog of the Configure card) → reactivate → +//! use again. +//! +//! Differs from the Slack scenario (scenario 6) on the axis that matters: +//! GitHub has NO channel connection — its "connected" surface is the +//! product-auth credential account injected at dispatch. The surfaces that +//! must flip together on remove are therefore: +//! - **lifecycle phase** seen by `builtin.extension_search`; +//! - **tool dispatchability** of `github.*` through the real capability port. +//! +//! Runs LAST in the group: scenario 1 leaves "github" installed (a +//! same-member reinstall is rejected "already installed" by design — +//! `install_policy.rs`), so phase 1 activates the existing install — the +//! state a real user's Extensions page is in when #6029 bites. The fresh +//! install→activate arm is pinned in phase 5, after the full remove. + +use super::reborn_support::group::{HarnessResult, RebornIntegrationGroup}; +use super::reborn_support::reply::RebornScriptedReply; +use serde_json::json; + +pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { + // ── Phase 1: activate the existing install; tools get published ───────── + let lifecycle = g + .thread("gh-lifecycle-install") + .script([ + RebornScriptedReply::tool_call( + "builtin.extension_activate", + json!({"extension_id": "github"}), + ), + RebornScriptedReply::text("github ready"), + ]) + .build() + .await?; + // Real secret material through the production manual-token flow — + // activation's credential gate and dispatch-time staging both select this + // account (same seed shape as scenario 6's slack_personal account). + lifecycle + .seed_capability_credential_account("github", "itest github", &[]) + .await?; + lifecycle.submit_turn("activate github").await?; + lifecycle + .assert_tool_result_contains("\"activated\":true") + .await?; + lifecycle + .assert_tool_result_contains(r#""github.get_repo""#) + .await?; + + // ── Phase 2: use — a github.* call dispatches through the real port ───── + // The caller uses TWO capabilities so per-thread baseline slicing keeps + // the post-remove negative check clean: get_repo only before the remove, + // create_issue only after it (mirrors scenario 6's search/send split). + let caller = g + .thread("gh-lifecycle-caller") + .script([ + RebornScriptedReply::tool_call( + "github.get_repo", + json!({"owner": "octocat", "repo": "hello-world"}), + ), + RebornScriptedReply::text("looked up repo"), + RebornScriptedReply::tool_call( + "github.create_issue", + json!({"owner": "octocat", "repo": "hello-world", + "title": "after remove?", "body": "should not dispatch"}), + ), + RebornScriptedReply::text("github unavailable"), + RebornScriptedReply::tool_call( + "github.create_issue", + json!({"owner": "octocat", "repo": "hello-world", + "title": "after restore", "body": "should dispatch"}), + ), + RebornScriptedReply::text("filed the issue"), + ]) + .build() + .await?; + caller.submit_turn("look up the repo").await?; + caller.assert_tool_invoked("github.get_repo").await?; + caller.assert_reply_contains("looked up repo").await?; + + // ── Phase 3: the exit edge — extension_remove must succeed (#6029) ────── + let remover = g + .thread("gh-lifecycle-remove") + .script([ + RebornScriptedReply::tool_call( + "builtin.extension_remove", + json!({"extension_id": "github"}), + ), + RebornScriptedReply::text("github removed"), + ]) + .build() + .await?; + remover.submit_turn("remove github").await?; + remover + .assert_tool_result_contains("\"removed\":true") + .await?; + + // Lifecycle phase flips (fresh viewer thread so phase-1 results can't + // satisfy the negative check)… + let viewer = g + .thread("gh-lifecycle-viewer-after-remove") + .script([ + RebornScriptedReply::tool_call("builtin.extension_search", json!({"query": "github"})), + RebornScriptedReply::text("searched catalog"), + ]) + .build() + .await?; + viewer.submit_turn("search github after removal").await?; + if viewer + .assert_tool_result_contains(r#""installation_phase":"active""#) + .await + .is_ok() + { + return Err( + "github still shows installation_phase:active after extension_remove; \ + the #6029 wedge — lifecycle phase did not flip with the remove" + .into(), + ); + } + // Non-vacuity: the catalog entry itself must still be discoverable. + viewer.assert_tool_result_contains("\"github\"").await?; + + // ── Phase 4: use after remove — dispatch is rejected fail-closed ──────── + caller.submit_turn("file an issue").await?; + if caller + .assert_tool_invoked("github.create_issue") + .await + .is_ok() + { + return Err("github.create_issue dispatched after extension_remove; \ + removal must unpublish the capability surface" + .into()); + } + caller.assert_reply_contains("github unavailable").await?; + + // ── Phase 5: reconfigure (fresh credential) + reactivate restores use ─── + // The model-tool analog of the Extensions page's Configure card: a new + // credential account for the same provider, then reactivation. + let restorer = g + .thread("gh-lifecycle-restore") + .script([ + RebornScriptedReply::tool_call( + "builtin.extension_install", + json!({"extension_id": "github"}), + ), + RebornScriptedReply::tool_call( + "builtin.extension_activate", + json!({"extension_id": "github"}), + ), + RebornScriptedReply::text("github restored"), + ]) + .build() + .await?; + restorer + .seed_capability_credential_account("github", "itest github reconfigure", &[]) + .await?; + restorer + .submit_turn("reinstall and activate github") + .await?; + restorer + .assert_tool_result_contains("\"installed\":true") + .await?; + restorer + .assert_tool_result_contains("\"activated\":true") + .await?; + + // ── Phase 6: the exact call that was rejected now dispatches ──────────── + caller.submit_turn("file the issue again").await?; + caller.assert_tool_invoked("github.create_issue").await?; + caller.assert_reply_contains("filed the issue").await?; + + Ok(()) +} diff --git a/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs b/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs new file mode 100644 index 00000000000..06dfbfa430a --- /dev/null +++ b/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs @@ -0,0 +1,89 @@ +//! Scenario 8 (T5 of issue #6105; the #4556/#2939/#1327 failure shapes): +//! RESTART SURVIVAL of connected-channel state. After the Slack lifecycle +//! scenario (scenario 6) leaves Slack reconnected and active, this reopens +//! the durable stores at the same on-disk local-dev `storage_root` through +//! FRESH handles — independent of every live `Arc` the running group holds — +//! and asserts the state a process restart must reconstruct is actually +//! there: +//! - the active Slack identity binding (the durable "connected" evidence), +//! read through a fresh `FilesystemSlackHostState` composed exactly the way +//! production boot composes it; +//! - the Slack extension installation record (the durable "installed" +//! evidence). +//! +//! Deliberately NOT claimed: the in-memory capability publication surviving — +//! production re-publishes tools on (re)activation over this same durable +//! state, and scenario 6's reinstall arm already pins that path. This +//! scenario pins the durable half a restart depends on; full process-restart +//! coverage belongs to the #6106 boot/upgrade gates. +//! +//! Ordering: depends on scenario 6 (connected end state); driven after it in +//! `main.rs`. + +use super::reborn_support::group::{HarnessResult, RebornIntegrationGroup}; + +pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { + let slack = g + .slack_channel_connection() + .ok_or("extension_lifecycle group must carry the Slack channel-connection bundle")?; + let actor = g.canonical_actor_user(); + let capability_harness = g + .capability_harness() + .ok_or("extension_lifecycle group always uses HostRuntime")?; + let storage_root = capability_harness.storage_root_for_test(); + + // Live-handle sanity: scenario 6 must have left Slack connected, or the + // reopen assertions below would be vacuous. + if !slack.caller_channel_connected(&actor).await? { + return Err( + "precondition: slack must still be connected after the lifecycle scenario".into(), + ); + } + + // Durable "connected": the active identity binding reads back through a + // FRESH host-state store over a FRESH root filesystem at the same + // storage_root — the state a restarted process would reconstruct. + if !slack + .has_active_identity_binding_after_reopen(&storage_root, &actor) + .await? + { + return Err( + "the active slack identity binding must survive an independent \ + store reopen; a restart would come up disconnected (#4556/#2939 shape)" + .into(), + ); + } + // Non-vacuity control: the same reopened probe must NOT report a binding + // for a user that never connected. + let stranger = ironclaw_host_api::UserId::new("reopen-probe-stranger") + .map_err(|error| error.to_string())?; + if slack + .has_active_identity_binding_after_reopen(&storage_root, &stranger) + .await? + { + return Err( + "reopened binding probe reported a binding for a user that never connected; \ + the reopen read is not scoped correctly" + .into(), + ); + } + + // Durable "installed": the slack installation record reads back through a + // fresh installation store at the same root. + let installations = ironclaw_reborn_composition::test_support::open_local_dev_extension_installation_store_for_test( + &storage_root, + ) + .await? + .list_installations() + .await?; + if !installations + .iter() + .any(|installation| installation.extension_id().as_str() == "slack") + { + return Err( + "the slack installation record must survive an independent store reopen".into(), + ); + } + + Ok(()) +} diff --git a/tests/integration/oauth_connect.rs b/tests/integration/oauth_connect.rs index 7b6a099c842..53dec0494bc 100644 --- a/tests/integration/oauth_connect.rs +++ b/tests/integration/oauth_connect.rs @@ -9,10 +9,10 @@ //! This proves design-spec §3.8 coverage: real stores, mock only the OAuth HTTP //! seam at the `RuntimeHttpEgress` boundary. -use chrono::{Duration, Utc}; +use chrono::{DateTime, Duration, Utc}; use ironclaw_auth::{ - AuthChallenge, AuthContinuationRef, AuthErrorCode, AuthFlowId, AuthFlowKind, AuthProductScope, - AuthProviderId, AuthSurface, AuthorizationCodeHash, CredentialAccountLabel, + AuthChallenge, AuthContinuationRef, AuthErrorCode, AuthFlowId, AuthFlowKind, AuthFlowStatus, + AuthProductScope, AuthProviderId, AuthSurface, AuthorizationCodeHash, CredentialAccountLabel, CredentialAccountListRequest, CredentialAccountLookupRequest, NewAuthFlow, OAuthAuthorizationCode, OAuthAuthorizationUrl, OAuthProviderCallbackRequest, OpaqueStateHash, PkceVerifierHash, PkceVerifierSecret, ProviderScope, @@ -36,6 +36,70 @@ fn test_scope() -> AuthProductScope { AuthProductScope::new(resource, AuthSurface::Callback) } +/// A `NewAuthFlow` for the connect-flow tests; only identity hashes and the +/// expiry vary between scenarios. +fn new_flow_request( + scope: &AuthProductScope, + provider: &AuthProviderId, + state_hash: &OpaqueStateHash, + pkce_hash: &PkceVerifierHash, + expires_at: DateTime, +) -> NewAuthFlow { + NewAuthFlow { + id: None, + scope: scope.clone(), + kind: AuthFlowKind::IntegrationCredential, + provider: provider.clone(), + challenge: AuthChallenge::OAuthUrl { + authorization_url: OAuthAuthorizationUrl::new( + "https://accounts.example.com/o/oauth2/auth", + ) + .unwrap(), + expires_at, + }, + continuation: AuthContinuationRef::SetupOnly, + update_binding: None, + opaque_state_hash: Some(state_hash.clone()), + pkce_verifier_hash: Some(pkce_hash.clone()), + expires_at, + } +} + +/// An `Authorized` provider-callback request matching `new_flow_request`'s +/// hashes — the "user completed the provider consent page" leg. +fn authorized_callback_request( + scope: &AuthProductScope, + flow_id: AuthFlowId, + provider: &AuthProviderId, + state_hash: &OpaqueStateHash, + pkce_hash: &PkceVerifierHash, + code_hash: &AuthorizationCodeHash, + label: &str, +) -> RebornOAuthCallbackRequest { + RebornOAuthCallbackRequest { + scope: scope.clone(), + flow_id, + opaque_state_hash: state_hash.clone(), + outcome: RebornOAuthCallbackOutcome::Authorized { + provider_request: OAuthProviderCallbackRequest { + provider: provider.clone(), + account_label: CredentialAccountLabel::new(label).unwrap(), + authorization_code: OAuthAuthorizationCode::new(SecretString::from(format!( + "auth-code-{label}" + ))) + .unwrap(), + authorization_code_hash: code_hash.clone(), + pkce_verifier: PkceVerifierSecret::new(SecretString::from(format!( + "pkce-verifier-{label}" + ))) + .unwrap(), + pkce_verifier_hash: pkce_hash.clone(), + scopes: vec![ProviderScope::new("test.readonly").unwrap()], + }, + }, + } +} + /// Core slice-7 scenario: a real OAuth connect flow produces a persisted /// `CredentialAccount` that reads back correctly, and exactly one /// token-exchange HTTP call was made to the scripted egress. @@ -214,3 +278,278 @@ async fn oauth_callback_without_prior_flow_fails() { page.accounts.len() ); } + +/// T4 of the #6105 lifecycle transitions (issues #2858/#2534/#6043 shape): a +/// callback that lands AFTER the flow lapsed (the user abandoned or lost the +/// provider tab) must be rejected terminally — and a RETRIED connect with a +/// fresh flow must then succeed cleanly. The expired first attempt must leave +/// no half-connected state behind: its record reads back terminal `Expired`, +/// no token exchange crossed the egress for it, and after the retry exactly +/// one credential account exists. +#[tokio::test] +async fn expired_flow_callback_rejected_then_fresh_flow_retry_succeeds() { + let bundle = build_oauth_product_auth_for_test(); + let scope = test_scope(); + let provider = AuthProviderId::new("test-oauth-provider").unwrap(); + + let state_hash = OpaqueStateHash::new(hex64(0x11)).unwrap(); + let pkce_hash = PkceVerifierHash::new(hex64(0x22)).unwrap(); + let code_hash = AuthorizationCodeHash::new(hex64(0x33)).unwrap(); + + // The flow lapsed before the callback arrived. + let expired_flow = bundle + .services + .flow_manager() + .create_flow(new_flow_request( + &scope, + &provider, + &state_hash, + &pkce_hash, + Utc::now() - Duration::seconds(1), + )) + .await + .expect("create_flow must accept a flow that will read back as lapsed"); + + let error = bundle + .services + .handle_oauth_callback(authorized_callback_request( + &scope, + expired_flow.id, + &provider, + &state_hash, + &pkce_hash, + &code_hash, + "Late Callback", + )) + .await + .expect_err("a callback for a lapsed flow must be rejected"); + assert_eq!( + error.code, + AuthErrorCode::UnknownOrExpiredFlow, + "lapsed-flow callback must surface as UnknownOrExpiredFlow" + ); + + // Durable evidence of a clean rejection: the record is terminal Expired + // (not half-claimed), and the token exchange never ran. + let record = bundle + .services + .flow_manager() + .get_flow(&scope, expired_flow.id) + .await + .expect("get_flow must not error") + .expect("the expired flow record must remain readable"); + assert_eq!( + record.status, + AuthFlowStatus::Expired, + "the lapsed flow must be marked terminal Expired, not left pending" + ); + assert_eq!( + bundle.egress.captured_count(), + 0, + "no token exchange may run for a lapsed-flow callback" + ); + + // Retry: a fresh flow (new state/PKCE — a new grant) for the same + // provider and scope. An expired predecessor must not fence it out. + let retry_state = OpaqueStateHash::new(hex64(0x44)).unwrap(); + let retry_pkce = PkceVerifierHash::new(hex64(0x55)).unwrap(); + let retry_code = AuthorizationCodeHash::new(hex64(0x66)).unwrap(); + let retry_flow = bundle + .services + .flow_manager() + .create_flow(new_flow_request( + &scope, + &provider, + &retry_state, + &retry_pkce, + Utc::now() + Duration::minutes(5), + )) + .await + .expect("a retried create_flow must succeed after an expired predecessor"); + let response = bundle + .services + .handle_oauth_callback(authorized_callback_request( + &scope, + retry_flow.id, + &provider, + &retry_state, + &retry_pkce, + &retry_code, + "Retry Account", + )) + .await + .expect("the retried callback must succeed; an expired flow must not wedge the retry"); + let account_id = response + .credential_account_id + .expect("the retried callback must mint a credential account"); + + // Exactly ONE account and ONE token exchange: the failed first attempt + // contributed nothing. + let page = bundle + .services + .credential_account_service() + .list_accounts(CredentialAccountListRequest::new( + scope.clone(), + provider.clone(), + )) + .await + .expect("list_accounts must not error after the retry"); + assert_eq!( + page.accounts.len(), + 1, + "only the retry's account may exist; a lapsed flow must not leave a half-connected account" + ); + assert_eq!( + page.accounts[0].id, account_id, + "the surviving account is the retry's account" + ); + assert_eq!( + bundle.egress.captured_count(), + 1, + "exactly the retry's token exchange may cross the egress" + ); +} + +/// T4 of the #6105 lifecycle transitions, replay arm (issue #2858 shape): a +/// callback REPLAYED after the flow already completed (browser back-button / +/// duplicated redirect) is IDEMPOTENT on the durable services: it returns the +/// original completed outcome — same credential account — without re-running +/// the token exchange or minting a second account, and a subsequent fresh +/// connect (reconnect epoch) still succeeds. +/// +/// Deliberate divergence from the `ironclaw_auth` in-memory contract fake, +/// which rejects a terminal-flow callback with `FlowAlreadyTerminal`: the +/// durable `claim_oauth_callback` short-circuits terminal flows to `Ok` +/// (`product_auth/durable/flows.rs`) so the hosted, unauthenticated callback +/// route stays replay-safe. This test pins the production (durable) shape. +#[tokio::test] +async fn replayed_callback_is_idempotent_then_fresh_flow_reconnects() { + let bundle = build_oauth_product_auth_for_test(); + let scope = test_scope(); + let provider = AuthProviderId::new("test-oauth-provider").unwrap(); + + let state_hash = OpaqueStateHash::new(hex64(0x71)).unwrap(); + let pkce_hash = PkceVerifierHash::new(hex64(0x72)).unwrap(); + let code_hash = AuthorizationCodeHash::new(hex64(0x73)).unwrap(); + + let flow = bundle + .services + .flow_manager() + .create_flow(new_flow_request( + &scope, + &provider, + &state_hash, + &pkce_hash, + Utc::now() + Duration::minutes(5), + )) + .await + .expect("create_flow must succeed"); + let first = bundle + .services + .handle_oauth_callback(authorized_callback_request( + &scope, + flow.id, + &provider, + &state_hash, + &pkce_hash, + &code_hash, + "First Grant", + )) + .await + .expect("the first callback must complete the flow"); + let first_account = first + .credential_account_id + .expect("the first callback must mint a credential account"); + assert_eq!( + bundle.egress.captured_count(), + 1, + "the first callback runs exactly one token exchange" + ); + + // Replay the identical callback (browser back-button / duplicated + // redirect). It must return the ORIGINAL completed outcome — not error, + // not a half-processed or duplicated grant. + let replay = bundle + .services + .handle_oauth_callback(authorized_callback_request( + &scope, + flow.id, + &provider, + &state_hash, + &pkce_hash, + &code_hash, + "First Grant", + )) + .await + .expect("a replayed callback for a completed flow must be idempotent, not an error"); + assert_eq!( + replay.credential_account_id, + Some(first_account), + "the replayed callback must return the original grant's credential account" + ); + assert_eq!( + bundle.egress.captured_count(), + 1, + "a replayed callback must not re-run the token exchange" + ); + let page = bundle + .services + .credential_account_service() + .list_accounts(CredentialAccountListRequest::new( + scope.clone(), + provider.clone(), + )) + .await + .expect("list_accounts must not error after the replay"); + assert_eq!( + page.accounts.len(), + 1, + "a replayed callback must not mint a second credential account" + ); + + // Reconnect: a fresh flow must still succeed after the replay rejection. + let reconnect_state = OpaqueStateHash::new(hex64(0x81)).unwrap(); + let reconnect_pkce = PkceVerifierHash::new(hex64(0x82)).unwrap(); + let reconnect_code = AuthorizationCodeHash::new(hex64(0x83)).unwrap(); + let reconnect_flow = bundle + .services + .flow_manager() + .create_flow(new_flow_request( + &scope, + &provider, + &reconnect_state, + &reconnect_pkce, + Utc::now() + Duration::minutes(5), + )) + .await + .expect("a reconnect create_flow must succeed after a replayed predecessor"); + let reconnect = bundle + .services + .handle_oauth_callback(authorized_callback_request( + &scope, + reconnect_flow.id, + &provider, + &reconnect_state, + &reconnect_pkce, + &reconnect_code, + "Reconnect Grant", + )) + .await + .expect("the reconnect callback must succeed; a replayed flow must not wedge reconnects"); + let reconnect_account = reconnect + .credential_account_id + .expect("the reconnect callback must mint a credential account"); + let listed = bundle + .services + .credential_account_service() + .list_accounts(CredentialAccountListRequest::new(scope, provider)) + .await + .expect("list_accounts must not error after the reconnect"); + assert!( + listed + .accounts + .iter() + .any(|account| account.id == reconnect_account), + "the reconnect's account must be listed alongside any prior account" + ); +} From a585057d69cb841db49e80482a6404e91c44eff6 Mon Sep 17 00:00:00 2001 From: Illia Polosukhin Date: Wed, 15 Jul 2026 06:15:20 +0000 Subject: [PATCH 2/5] docs(test): correct the replay-idempotency characterization on the T4 test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The behavior is not a fake-vs-durable divergence: both AuthFlowManager impls agree (claim is replay-idempotent on terminal flows, complete is fail-closed). The split is between seams — the handle_oauth_callback wrapper short-circuits at the idempotent claim. Established while building the shared conformance suite (ironclaw_auth::conformance). [skip-regression-check] Co-Authored-By: Claude Fable 5 --- tests/integration/oauth_connect.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/integration/oauth_connect.rs b/tests/integration/oauth_connect.rs index 53dec0494bc..11372736384 100644 --- a/tests/integration/oauth_connect.rs +++ b/tests/integration/oauth_connect.rs @@ -417,11 +417,14 @@ async fn expired_flow_callback_rejected_then_fresh_flow_retry_succeeds() { /// the token exchange or minting a second account, and a subsequent fresh /// connect (reconnect epoch) still succeeds. /// -/// Deliberate divergence from the `ironclaw_auth` in-memory contract fake, -/// which rejects a terminal-flow callback with `FlowAlreadyTerminal`: the -/// durable `claim_oauth_callback` short-circuits terminal flows to `Ok` -/// (`product_auth/durable/flows.rs`) so the hosted, unauthenticated callback -/// route stays replay-safe. This test pins the production (durable) shape. +/// NOT a fake-vs-durable divergence (both impls agree at every +/// `AuthFlowManager` method — see `ironclaw_auth::conformance`): the +/// replay-safety split is between SEAMS. `claim_oauth_callback` is +/// idempotent on terminal flows in both impls, and `handle_oauth_callback` +/// (this wrapper, the hosted unauthenticated callback route's entry) +/// short-circuits at that claim — while trait-level +/// `complete_oauth_callback` stays fail-closed (`FlowAlreadyTerminal`) in +/// both. This test pins the wrapper's replay-idempotent shape. #[tokio::test] async fn replayed_callback_is_idempotent_then_fresh_flow_reconnects() { let bundle = build_oauth_product_auth_for_test(); From 1980250a2cf4e9243c829e145011beb99b0f0ce5 Mon Sep 17 00:00:00 2001 From: Illia Polosukhin Date: Wed, 15 Jul 2026 06:36:45 +0000 Subject: [PATCH 3/5] test(reborn): activation-time re-auth gate over a revoked credential (#5878/#6043 arms) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Scenario 9 in reborn_group_extensions pins the activation-time auth surface the dispatch-time 401 pin (auth_gate.rs) does not reach — the surface #5878 actually reported: - connect notion (production manual-token flow), revoke the grant externally (the same update_status transition the refresh sweep's terminal invalid_grant path performs), then extension_activate: the run must park BlockedAuth with a renderable provider requirement (#6043's "start authentication, not a generic capability error"), and persist NO Failed-classed tool error (#5878's misleading-error shape); - a reconfigure (fresh credential) unwedges activation. New test-support: harness revoke_credential_accounts_for_provider + thread-level revoke_capability_credential_accounts (fails loud when nothing was revoked, so a scope mismatch can't vacuously pass the re-auth assertion). update_status is called with each account's OWN stored scope — full scope equality is required and the stored scope carries the minting invocation id. Co-Authored-By: Claude Fable 5 --- tests/integration/group_extensions/main.rs | 12 ++ ...enario_extension_activation_reauth_gate.rs | 123 ++++++++++++++++++ tests/integration/support/builder.rs | 27 ++++ tests/integration/support/harness/mod.rs | 44 +++++++ 4 files changed, 206 insertions(+) create mode 100644 tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs diff --git a/tests/integration/group_extensions/main.rs b/tests/integration/group_extensions/main.rs index 1a37be173bb..c3af4b60e4b 100644 --- a/tests/integration/group_extensions/main.rs +++ b/tests/integration/group_extensions/main.rs @@ -21,6 +21,7 @@ mod support; // set by the `report.record(...)` sequence below, not declaration order. mod scenario_activate_then_active_cross_thread; mod scenario_credential_extension_lifecycle_state_machine; +mod scenario_extension_activation_reauth_gate; mod scenario_install_then_visible_cross_thread; mod scenario_install_unknown_extension_id_fails_safely; mod scenario_remove_then_absent_cross_thread; @@ -104,5 +105,16 @@ async fn extensions_group_e2e() { scenario_slack_state_survives_reopen::run(&g).await, ); + // Scenario 9 (issue #6105 bucket-3 arms): activation-time re-auth gate — + // activate over a REVOKED credential parks BlockedAuth with a renderable + // provider requirement (#6043 shape), persists no misleading Failed error + // (#5878's reported extension_activate surface), and a reconfigure + // unwedges it. Uses "notion" (removed by scenario 2; credentials + // untouched by every other scenario). + report.record( + "extension_activation_reauth_gate", + scenario_extension_activation_reauth_gate::run(&g).await, + ); + report.assert_all_passed(); } diff --git a/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs b/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs new file mode 100644 index 00000000000..fc2caa17a29 --- /dev/null +++ b/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs @@ -0,0 +1,123 @@ +//! Scenario 9 (bucket-3 arms of issue #6105; the #5878 and #6043 failure +//! shapes): ACTIVATION-TIME auth surface. `extension_activate` when the +//! caller's only credential account for the provider is REVOKED (external +//! revocation — the user pulled the grant on the provider side) must open a +//! REAL re-auth gate: +//! - the run parks `BlockedAuth` with `credential_requirements` populated +//! (provider set — what the Configure card / auth prompt renders, the +//! #6043 "starts authentication instead of a generic capability error" +//! discriminator); +//! - NO `Failed`-classed tool error is persisted (#5878's misleading "the +//! tool input could not be encoded" / "provider unavailable" regression); +//! - after a reconfigure (fresh credential through the production +//! manual-token flow) activation completes — the revoked state does not +//! wedge the machine (#5878's "requires multiple retry attempts" arm). +//! +//! Complements the DISPATCH-TIME 401 → re-auth pin in +//! `tests/integration/auth_gate.rs` (issue #5878 reported the +//! `extension_activate` surface specifically, which that test does not +//! drive). Uses "notion" (installed+removed by scenario 2, so the install +//! here is fresh; no other scenario touches its credential accounts). + +use super::reborn_support::assertions::ToolErrorClass; +use super::reborn_support::group::{HarnessResult, RebornIntegrationGroup}; +use super::reborn_support::reply::RebornScriptedReply; +use ironclaw_turns::TurnStatus; +use serde_json::json; + +pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { + // ── Phase 1: activation with only a revoked credential opens the gate ─── + let activator = g + .thread("notion-reauth-activate") + .script([ + RebornScriptedReply::tool_call( + "builtin.extension_install", + json!({"extension_id": "notion"}), + ), + RebornScriptedReply::tool_call( + "builtin.extension_activate", + json!({"extension_id": "notion"}), + ), + // Consumed by the post-deny resume model call. + RebornScriptedReply::text("notion needs reauthorization"), + ]) + .build() + .await?; + // The #5878 repro order: CONNECT first (a real account under the + // capability dispatch scope, via the production manual-token flow)… + activator + .seed_capability_credential_account("notion", "itest notion original", &[]) + .await?; + // …then the user revokes the grant on the provider side: the account + // flips to Revoked through the same update_status transition the refresh + // sweep's terminal invalid_grant path performs. + activator + .revoke_capability_credential_accounts("notion") + .await?; + + let (run_id, gate_ref) = activator + .submit_turn_until_auth_blocked("set up notion") + .await?; + let state = activator + .wait_for_status(run_id, TurnStatus::BlockedAuth) + .await?; + // #6043 discriminator: a REAL auth gate the UI can render — provider + // populated — not a provider-null unsubmittable gate and not a failure. + if state.credential_requirements.is_empty() { + return Err("activation over a revoked credential must populate \ + credential_requirements; an empty list is the unsubmittable-gate shape" + .into()); + } + let notion_provider = ironclaw_host_api::RuntimeCredentialAccountProviderId::new("notion") + .map_err(|error| error.to_string())?; + if !state + .credential_requirements + .iter() + .any(|requirement| requirement.provider == notion_provider) + { + return Err(format!( + "the re-auth gate must name the notion provider; got {:?}", + state.credential_requirements + ) + .into()); + } + // #5878 discriminator: the revoked credential surfaced EXCLUSIVELY as the + // gate — no misleading Failed-classed tool error was persisted (an empty + // reason matches any summary of the class). + activator + .assert_no_tool_error(ToolErrorClass::Failed, "") + .await + .map_err(|error| { + format!( + "activation over a revoked credential must park at the auth gate only, \ + not persist a Failed-classed tool error (#5878 misleading-error shape): {error}" + ) + })?; + + activator.deny_auth_gate(run_id, &gate_ref).await?; + activator + .wait_for_status(run_id, TurnStatus::Completed) + .await?; + + // ── Phase 2: reconfigure (fresh credential) unwedges activation ───────── + let restorer = g + .thread("notion-reauth-restore") + .script([ + RebornScriptedReply::tool_call( + "builtin.extension_activate", + json!({"extension_id": "notion"}), + ), + RebornScriptedReply::text("notion reauthorized"), + ]) + .build() + .await?; + restorer + .seed_capability_credential_account("notion", "itest notion reconfigure", &[]) + .await?; + restorer.submit_turn("activate notion again").await?; + restorer + .assert_tool_result_contains("\"activated\":true") + .await?; + + Ok(()) +} diff --git a/tests/integration/support/builder.rs b/tests/integration/support/builder.rs index f206e0ee039..433b6bbca32 100644 --- a/tests/integration/support/builder.rs +++ b/tests/integration/support/builder.rs @@ -1578,6 +1578,33 @@ impl RebornIntegrationHarness { .await } + /// Flip every non-revoked credential account for `provider` under this + /// group's capability dispatch scope to `Revoked` — modeling an external + /// revocation of the user's grant (#5878 shape). Same scoping as + /// [`Self::seed_capability_credential_account`]; errors if nothing was + /// revoked so a vacuous revoke can't silently pass a re-auth assertion. + pub async fn revoke_capability_credential_accounts(&self, provider: &str) -> HarnessResult<()> { + let harness = match &self._shared.capability { + GroupCapability::HostRuntime(arc) => arc, + GroupCapability::Recording => { + return Err( + "no host-runtime capability backend to revoke credential accounts".into(), + ); + } + }; + let scope = self.run_resource_scope_for_user(harness.capability_user_id().clone()); + let revoked = harness + .revoke_credential_accounts_for_provider(&scope, provider) + .await?; + if revoked == 0 { + return Err(format!( + "no non-revoked credential account for provider {provider:?} was found to revoke" + ) + .into()); + } + Ok(()) + } + /// This thread's run `(tenant, agent, project)` scope with `user_id` as /// the owner — the exact four fields dispatch-time credential-account /// selection matches. Which user is correct depends on the caller: the diff --git a/tests/integration/support/harness/mod.rs b/tests/integration/support/harness/mod.rs index d1fbc3d3617..7eff3910785 100644 --- a/tests/integration/support/harness/mod.rs +++ b/tests/integration/support/harness/mod.rs @@ -411,6 +411,50 @@ impl HostRuntimeCapabilityHarness { Ok(()) } + /// Flip every non-revoked credential account for `provider` under + /// `scope`'s credential-owner view to `Revoked`, returning how many were + /// flipped. Models an EXTERNAL revocation (the user revoked the grant on + /// the provider's side) through the same production transition the + /// refresh sweep's `report_terminal_refresh_status` performs: + /// `CredentialAccountService::update_status(.., Revoked)`. Companion to + /// [`Self::seed_credential_account_with_material`] for the #5878 + /// activation-with-revoked-credential shape. + pub(crate) async fn revoke_credential_accounts_for_provider( + &self, + scope: &ResourceScope, + provider: &str, + ) -> HarnessResult { + let product_auth = self + .product_auth + .as_ref() + .ok_or("harness missing local-dev product auth (not built via new_with_options)")?; + let scope = AuthProductScope::credential_owner(scope, AuthSurface::Api); + let provider_id = AuthProviderId::new(provider)?; + let accounts = product_auth + .credential_account_record_source_for_test() + .accounts_for_owner(&scope) + .await + .map_err(|error| format!("account enumeration for revoke failed: {error:?}"))?; + let mut revoked = 0; + for account in accounts { + if account.provider != provider_id || account.status == CredentialAccountStatus::Revoked + { + continue; + } + // Pass the account's OWN stored scope: `update_status` requires + // full scope equality, and the stored scope carries the minting + // invocation id no reconstructed scope can reproduce (same + // pattern as the refresh sweep's terminal-status write). + product_auth + .credential_account_service() + .update_status(&account.scope, account.id, CredentialAccountStatus::Revoked) + .await + .map_err(|error| format!("revoking account {} failed: {error:?}", account.id))?; + revoked += 1; + } + Ok(revoked) + } + /// The fixed user this harness dispatches first-party capabilities under /// (see [`Self::with_user_id`]). Credential seeding aimed at a capability's /// dispatch-time account selection must use THIS user — for groups that do From 58d8237f26ea8c0ace4c731b59127e6b0cfa238a Mon Sep 17 00:00:00 2001 From: Illia Polosukhin Date: Thu, 16 Jul 2026 00:10:29 +0000 Subject: [PATCH 4/5] =?UTF-8?q?test(reborn):=20address=20#6113=20review=20?= =?UTF-8?q?=E2=80=94=20strengthen=20T4=20reconnect=20assertions,=20JSON-pa?= =?UTF-8?q?rse=20the=20T1=20target=20pin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - replayed_callback_is_idempotent_then_fresh_flow_reconnects: pin that the fresh reconnect mints a DISTINCT credential account (assert_ne against the original), that exactly the two accounts exist and both are listed, and that the reconnect ran its own token exchange (egress count 2) — the prior tail passed even if reconnect had silently reused the first account. - T1 right-target pin: parse the chat.postMessage body as JSON and assert the "channel" field equals the preference binding's DM conversation, instead of a formatting-sensitive substring match. - expired-flow arm: widen the lapsed-flow offset from 1s to 10s so timestamp rounding in a durable backend can't un-expire the flow. [skip-regression-check] test-only strengthening from PR #6113 review Co-Authored-By: Claude Fable 5 --- .../src/slack/slack_delivery.rs | 8 +++-- tests/integration/oauth_connect.rs | 30 ++++++++++++++----- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs b/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs index 0fd418e4e6c..b4525a6e1e0 100644 --- a/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs +++ b/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs @@ -3752,9 +3752,11 @@ mod tests { // must carry the DM conversation id decoded from the saved // preference's binding ref — not the run's current channel or another // user's target. - let body = String::from_utf8(post.body).expect("postMessage body is UTF-8 JSON"); - assert!( - body.contains(r#""channel":"D456""#), + let body: serde_json::Value = + serde_json::from_slice(&post.body).expect("postMessage body is valid JSON"); + assert_eq!( + body.get("channel").and_then(|channel| channel.as_str()), + Some("D456"), "chat.postMessage must target the preference binding's DM conversation; body: {body}" ); diff --git a/tests/integration/oauth_connect.rs b/tests/integration/oauth_connect.rs index 11372736384..10a3c7a700c 100644 --- a/tests/integration/oauth_connect.rs +++ b/tests/integration/oauth_connect.rs @@ -305,7 +305,7 @@ async fn expired_flow_callback_rejected_then_fresh_flow_retry_succeeds() { &provider, &state_hash, &pkce_hash, - Utc::now() - Duration::seconds(1), + Utc::now() - Duration::seconds(10), )) .await .expect("create_flow must accept a flow that will read back as lapsed"); @@ -542,17 +542,33 @@ async fn replayed_callback_is_idempotent_then_fresh_flow_reconnects() { let reconnect_account = reconnect .credential_account_id .expect("the reconnect callback must mint a credential account"); + assert_ne!( + reconnect_account, first_account, + "a fresh reconnect flow must mint a DISTINCT credential account, not reuse the original" + ); + assert_eq!( + bundle.egress.captured_count(), + 2, + "the reconnect must run its own token exchange (first callback's plus one)" + ); let listed = bundle .services .credential_account_service() .list_accounts(CredentialAccountListRequest::new(scope, provider)) .await .expect("list_accounts must not error after the reconnect"); - assert!( - listed - .accounts - .iter() - .any(|account| account.id == reconnect_account), - "the reconnect's account must be listed alongside any prior account" + assert_eq!( + listed.accounts.len(), + 2, + "exactly the original and the reconnect accounts must exist" ); + for expected in [&first_account, &reconnect_account] { + assert!( + listed + .accounts + .iter() + .any(|account| &account.id == expected), + "account {expected:?} must be listed after the reconnect" + ); + } } From 058c476bd96db3a014ed7f76d375c8c806dbcb26 Mon Sep 17 00:00:00 2001 From: Illia Polosukhin Date: Thu, 16 Jul 2026 03:26:54 +0000 Subject: [PATCH 5/5] =?UTF-8?q?test(reborn):=20apply=20max-effort=20review?= =?UTF-8?q?=20findings=20=E2=80=94=20re-fire=20arm,=20error-shape=20pins,?= =?UTF-8?q?=20cfg=20narrowing,=20dedup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Coverage strengthening (the tests could previously stay green while the pinned behavior regressed): - scenario 9: new phase 2 pins that a RETRIED activation over the still-revoked credential parks at a fresh BlockedAuth gate (the lifecycle.md "reconnect must not resume without updated credentials" arm) — without it, the post-reconfigure success could not distinguish "fresh credential unwedged it" from "the gate only fires once". - new assert_no_error_shaped_tool_result[_except]: structural negative (model_observation.status == "error" OR either class prefix) replacing the prefix-only assert_no_tool_error(Failed, "") at the #5878 pins in auth_gate.rs and scenario 9 — the prefix filter was blind to Denied-classed and raw planner summaries. Mutation-verified: emptying the post-resume allowlist fails on ("auth gate denied by user", Some("error")) via the observation arm. - auth_gate.rs: both #5878 discriminators re-asserted AFTER the deny resume (egress still exactly 1; only the gate-declined planner summary persisted) — the pre-park samples could not see the resume leg. - factory.rs reopen seam narrowed to libsql-only: the body's LocalDefault reopen mounts a fresh InMemoryBackend on non-libsql builds, so the advertised postgres arm could only ever probe an empty store (false CI red); caller narrowed to match. - main.rs: scenario 6 now gates via .expect() (dependent-scenario convention) so a lifecycle regression is not misattributed to the scenario-8 restart-survival probe. Accuracy and dedup: - corrected the false "idempotent-reinstall arm" / "Runs LAST" wiring comments and the leftover "replay rejection" mischaracterization a585057d6 missed. - oauth_connect.rs: both pre-existing tests now build flows/callbacks through the shared new_flow_request/authorized_callback_request helpers (~100 lines of duplicated literals removed). - scenario 7 phase 4 uses assert_tool_not_invoked (dispatch diagnostics on the failure branch that matters). - scenario 8: identity-binding probe pair reads through ONE reopened host-state store (active_identity_bindings_after_reopen), and the installation check delegates to the shared E-DURABLE reopen helper, now hoisted to GroupCapability with a group-level wrapper. - slack_delivery.rs: the T1 Delivered/Failed pair shares one deliver_completed_run_with_programmed_post_response arrangement. [skip-regression-check] test-only strengthening from the multi-agent review of PR #6113; the new scenario-9 arm and error-shape assertions are themselves the regression pins. Co-Authored-By: Claude Fable 5 --- .../src/factory.rs | 8 +- .../src/slack/slack_delivery.rs | 85 +++++---------- .../test_support/slack_channel_connection.rs | 52 +++++---- tests/integration/group_extensions/main.rs | 20 ++-- ...ntial_extension_lifecycle_state_machine.rs | 25 ++--- ...enario_extension_activation_reauth_gate.rs | 64 +++++++++-- .../scenario_slack_state_survives_reopen.rs | 54 +++------- tests/integration/oauth_connect.rs | 96 +++++------------ tests/integration/support/assertions.rs | 101 ++++++++++++++++++ tests/integration/support/builder.rs | 31 +----- tests/integration/support/group.rs | 53 +++++++++ 11 files changed, 350 insertions(+), 239 deletions(-) diff --git a/crates/ironclaw_reborn_composition/src/factory.rs b/crates/ironclaw_reborn_composition/src/factory.rs index a0383447397..1ae8d39e028 100644 --- a/crates/ironclaw_reborn_composition/src/factory.rs +++ b/crates/ironclaw_reborn_composition/src/factory.rs @@ -3129,10 +3129,16 @@ fn local_dev_project_filesystem( /// restart-survival test proves durable Slack host state (identity bindings, /// DM targets) is reconstructible the way a real process restart /// reconstructs it. Tests only; zero bytes in production builds. +/// +/// `libsql`-only (not `any(libsql, postgres)`): the body reopens via +/// `LocalDevStorageBackendInput::LocalDefault`, whose non-libsql arm mounts a +/// fresh `InMemoryBackend` — under a postgres-composed runtime that would be +/// a brand-new empty store, not the live Postgres-backed host state, so a +/// postgres gate here would compile a probe that can only report absence. #[cfg(all( feature = "test-support", feature = "slack-v2-host-beta", - any(feature = "libsql", feature = "postgres") + feature = "libsql" ))] pub(crate) async fn open_local_dev_slack_host_state_filesystem_for_test( storage_root: &Path, diff --git a/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs b/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs index b4525a6e1e0..114653abd02 100644 --- a/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs +++ b/crates/ironclaw_reborn_composition/src/slack/slack_delivery.rs @@ -3684,8 +3684,15 @@ mod tests { // --- Tests ---------------------------------------------------------------- - #[tokio::test] - async fn driver_happy_path_completed_run_with_preference_delivers_and_records_delivered() { + /// Shared arrangement for the T1 delivery-honesty pair (#6105): a + /// `Completed` run with a finalized reply and a saved personal DM + /// preference, driven through the real `TriggeredRunDeliveryDriver` + /// against a programmed `chat.postMessage` response body. The two tests + /// differ ONLY in that body and in what they assert — one arrangement + /// keeps the Delivered and Failed arms from drifting apart. + async fn deliver_completed_run_with_programmed_post_response( + post_response_body: Vec, + ) -> (TriggeredRunDeliveryRecord, Arc) { let install = "test-install"; let scope = personal_turn_scope(); let run_id = TurnRunId::new(); @@ -3706,10 +3713,7 @@ mod tests { egress.allow_credential_handle("slack_bot_token"); egress.program_response( "slack.com", - Ok(EgressResponse::new( - 200, - slack_post_ok_json("D456", "1234.5678"), - )), + Ok(EgressResponse::new(200, post_response_body)), ); let delivery_store = Arc::new(InMemoryTriggeredRunDeliveryStore::default()); @@ -3740,6 +3744,15 @@ mod tests { // Poll until the spawned delivery task writes its outcome record. let record = wait_for_delivery_record(&delivery_store, run_id).await; + (record, egress) + } + + #[tokio::test] + async fn driver_happy_path_completed_run_with_preference_delivers_and_records_delivered() { + let (record, egress) = deliver_completed_run_with_programmed_post_response( + slack_post_ok_json("D456", "1234.5678"), + ) + .await; // Egress should have been called for chat.postMessage. let post = egress @@ -3771,62 +3784,14 @@ mod tests { /// distinguish the two, only this record can. #[tokio::test] async fn driver_slack_api_rejection_records_failed_not_delivered() { - let install = "test-install"; - let scope = personal_turn_scope(); - let run_id = TurnRunId::new(); - let binding_ref = - test_slack_binding_ref(install, scope.agent_id.as_ref().expect("agent").as_str()); - - let coordinator = Arc::new(ScriptedTurnCoordinator::with_single_status( - TurnStatus::Completed, - )); - let thread_service = Arc::new(InMemorySessionThreadService::default()); - seed_finalized_assistant_message(&thread_service, &scope, run_id, "Hello from Ironclaw") - .await; - - let outbound = Arc::new(InMemoryOutboundStateStore::default()); - seed_personal_preference(&outbound, &scope, binding_ref).await; - // Slack accepts the HTTP call but rejects the post — the classic // silent-failure shape (revoked channel, kicked bot, archived DM). - let egress = Arc::new(FakeProtocolHttpEgress::new(vec!["slack.com".to_string()])); - egress.allow_credential_handle("slack_bot_token"); - egress.program_response( - "slack.com", - Ok(EgressResponse::new( - 200, - serde_json::json!({"ok": false, "error": "channel_not_found"}) - .to_string() - .into_bytes(), - )), - ); - - let delivery_store = Arc::new(InMemoryTriggeredRunDeliveryStore::default()); - let route_store = Arc::new(InMemoryDeliveredGateRouteStore::default()); - let services = make_services( - coordinator, - thread_service, - egress.clone(), - outbound, - install, - ); - let settings = SlackFinalReplyDeliverySettings { - poll_interval: std::time::Duration::ZERO, - max_wait: std::time::Duration::from_secs(5), - max_concurrent_deliveries: NonZeroUsize::new(1).unwrap(), - max_pending_deliveries: NonZeroUsize::new(8).unwrap(), - }; - let driver = TriggeredRunDeliveryDriver::with_settings( - services, - settings, - delivery_store.clone(), - route_store.clone(), - scope.agent_id.clone().expect("test scope has agent"), - ); - - let fire = minimal_trigger_fire(None); - driver.on_trigger_submitted(fire, run_id, scope).await; - let record = wait_for_delivery_record(&delivery_store, run_id).await; + let (record, egress) = deliver_completed_run_with_programmed_post_response( + serde_json::json!({"ok": false, "error": "channel_not_found"}) + .to_string() + .into_bytes(), + ) + .await; // The post WAS attempted (this is not a skip/no-target case)… assert!( diff --git a/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs b/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs index ea8cbd8b27a..05d9aea0059 100644 --- a/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs +++ b/crates/ironclaw_reborn_composition/src/test_support/slack_channel_connection.rs @@ -227,20 +227,26 @@ impl SlackChannelConnectionTestBundle { /// Restart-survival probe (T5 of issue #6105): read the SAME active-state /// identity-binding predicate as - /// [`Self::has_any_active_identity_binding`], but through a FRESH - /// `FilesystemSlackHostState` over a FRESH local-dev root filesystem - /// reopened at `storage_root` — fully independent of the live runtime's - /// in-memory handles. This is the integration-tier approximation of a - /// process restart: it proves the durable binding is reconstructible the - /// way production reconstructs it on boot (`build_reborn_services` → - /// `local_dev_slack_host_state_filesystem` → Slack host-state mounts). - /// Tests only. - #[cfg(any(feature = "libsql", feature = "postgres"))] - pub async fn has_active_identity_binding_after_reopen( + /// [`Self::has_any_active_identity_binding`] for EACH of `user_ids`, but + /// through ONE fresh `FilesystemSlackHostState` over ONE fresh local-dev + /// root filesystem reopened at `storage_root` — fully independent of the + /// live runtime's in-memory handles. This is the integration-tier + /// approximation of a process restart: it proves the durable binding is + /// reconstructible the way production reconstructs it on boot + /// (`build_reborn_services` → `local_dev_slack_host_state_filesystem` → + /// Slack host-state mounts). Results come back in `user_ids` order; the + /// single reopen means a positive probe and its non-vacuity control read + /// the same reconstructed store. Tests only. + /// + /// `libsql`-only, matching the factory seam it opens: the local-default + /// reopen path composes the libsql local-dev backend, so a wider gate + /// would silently probe a fresh in-memory store on non-libsql builds. + #[cfg(feature = "libsql")] + pub async fn active_identity_bindings_after_reopen( &self, storage_root: &std::path::Path, - user_id: &UserId, - ) -> Result { + user_ids: &[&UserId], + ) -> Result, String> { let host_state_filesystem = crate::factory::open_local_dev_slack_host_state_filesystem_for_test(storage_root) .await @@ -253,14 +259,20 @@ impl SlackChannelConnectionTestBundle { None, )); let lookup: Arc = state; - lookup - .user_has_provider_binding_with_provider_user_id_prefix( - SLACK_IDENTITY_PROVIDER, - user_id, - None, - ) - .await - .map_err(|error| error.to_string()) + let mut bindings = Vec::with_capacity(user_ids.len()); + for user_id in user_ids { + bindings.push( + lookup + .user_has_provider_binding_with_provider_user_id_prefix( + SLACK_IDENTITY_PROVIDER, + user_id, + None, + ) + .await + .map_err(|error| error.to_string())?, + ); + } + Ok(bindings) } /// Surface (a) of the extensions page: what diff --git a/tests/integration/group_extensions/main.rs b/tests/integration/group_extensions/main.rs index c3af4b60e4b..e39097f5176 100644 --- a/tests/integration/group_extensions/main.rs +++ b/tests/integration/group_extensions/main.rs @@ -81,16 +81,21 @@ async fn extensions_group_e2e() { // cleanup) → reconnect → reinstall → use again, asserting connection // state, durable bindings, lifecycle phase, and tool dispatchability stay // consistent at every transition. Uses "slack" (untouched by 1-5). - report.record( - "slack_channel_lifecycle_state_machine", - scenario_slack_channel_lifecycle_state_machine::run(&g).await, - ); + // dependent: must pass before scenario 8 consumes its reconnected end + // state — `.expect()` (not `report.record`) so a lifecycle regression is + // reported HERE, not misattributed to the restart-survival probe. + scenario_slack_channel_lifecycle_state_machine::run(&g) + .await + .expect("slack_channel_lifecycle_state_machine"); // Scenario 7 (issue #6105, T3): exit edges for a credential-injection // extension — activate → use → remove (#6029's wedged edge) → surfaces // flip → reconfigure + reactivate → use again. Reuses "github" AFTER - // every other scenario that reads it has run (scenario 1 leaves it - // installed), so its install exercises the idempotent-reinstall arm. + // every earlier scenario that reads it has run (scenario 1 leaves it + // installed and active-phase-free), so phase 1 activates the + // already-installed package — the exact Extensions-page state #6029 + // bites in (same-member re-INSTALL is rejected "already installed" by + // design; the reinstall arm scenario 7 drives is post-remove, phase 5). report.record( "credential_extension_lifecycle_state_machine", scenario_credential_extension_lifecycle_state_machine::run(&g).await, @@ -99,7 +104,8 @@ async fn extensions_group_e2e() { // Scenario 8 (issue #6105, T5): restart survival — the connected/installed // Slack state scenario 6 left behind reads back through FRESH store // handles reopened at the same on-disk storage_root (what a process - // restart reconstructs). Depends on scenario 6's end state. + // restart reconstructs). Scenario 6's `.expect()` above guarantees the + // end state this consumes. report.record( "slack_state_survives_reopen", scenario_slack_state_survives_reopen::run(&g).await, diff --git a/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs b/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs index a2aaf874a40..2e9c5cfc300 100644 --- a/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs +++ b/tests/integration/group_extensions/scenario_credential_extension_lifecycle_state_machine.rs @@ -12,11 +12,12 @@ //! - **lifecycle phase** seen by `builtin.extension_search`; //! - **tool dispatchability** of `github.*` through the real capability port. //! -//! Runs LAST in the group: scenario 1 leaves "github" installed (a -//! same-member reinstall is rejected "already installed" by design — -//! `install_policy.rs`), so phase 1 activates the existing install — the -//! state a real user's Extensions page is in when #6029 bites. The fresh +//! Runs after every earlier scenario that reads "github": scenario 1 leaves +//! it installed (a same-member reinstall is rejected "already installed" by +//! design — `install_policy.rs`), so phase 1 activates the existing install — +//! the state a real user's Extensions page is in when #6029 bites. The fresh //! install→activate arm is pinned in phase 5, after the full remove. +//! (Scenarios 8 and 9 run later but touch only slack/notion state.) use super::reborn_support::group::{HarnessResult, RebornIntegrationGroup}; use super::reborn_support::reply::RebornScriptedReply; @@ -124,15 +125,15 @@ pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { // ── Phase 4: use after remove — dispatch is rejected fail-closed ──────── caller.submit_turn("file an issue").await?; - if caller - .assert_tool_invoked("github.create_issue") + caller + .assert_tool_not_invoked("github.create_issue") .await - .is_ok() - { - return Err("github.create_issue dispatched after extension_remove; \ - removal must unpublish the capability surface" - .into()); - } + .map_err(|error| { + format!( + "github.create_issue dispatched after extension_remove; removal must \ + unpublish the capability surface: {error}" + ) + })?; caller.assert_reply_contains("github unavailable").await?; // ── Phase 5: reconfigure (fresh credential) + reactivate restores use ─── diff --git a/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs b/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs index fc2caa17a29..dc742888bee 100644 --- a/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs +++ b/tests/integration/group_extensions/scenario_extension_activation_reauth_gate.rs @@ -7,8 +7,12 @@ //! (provider set — what the Configure card / auth prompt renders, the //! #6043 "starts authentication instead of a generic capability error" //! discriminator); -//! - NO `Failed`-classed tool error is persisted (#5878's misleading "the +//! - NO error-shaped tool result is persisted (#5878's misleading "the //! tool input could not be encoded" / "provider unavailable" regression); +//! - a RETRIED activation with the credential still revoked parks at a +//! fresh re-auth gate — denied once is not satisfied, and the gate is not +//! one-shot (the lifecycle.md "reconnect must not resume without updated +//! credentials" arm); //! - after a reconfigure (fresh credential through the production //! manual-token flow) activation completes — the revoked state does not //! wedge the machine (#5878's "requires multiple retry attempts" arm). @@ -19,7 +23,6 @@ //! drive). Uses "notion" (installed+removed by scenario 2, so the install //! here is fresh; no other scenario touches its credential accounts). -use super::reborn_support::assertions::ToolErrorClass; use super::reborn_support::group::{HarnessResult, RebornIntegrationGroup}; use super::reborn_support::reply::RebornScriptedReply; use ironclaw_turns::TurnStatus; @@ -82,15 +85,17 @@ pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { .into()); } // #5878 discriminator: the revoked credential surfaced EXCLUSIVELY as the - // gate — no misleading Failed-classed tool error was persisted (an empty - // reason matches any summary of the class). + // gate — no error-shaped tool result of ANY class was persisted + // (structural observation-status check plus both class prefixes, so a + // Denied-classed or raw-literal misleading error can't slip past a + // Failed-prefix-only filter). activator - .assert_no_tool_error(ToolErrorClass::Failed, "") + .assert_no_error_shaped_tool_result() .await .map_err(|error| { format!( "activation over a revoked credential must park at the auth gate only, \ - not persist a Failed-classed tool error (#5878 misleading-error shape): {error}" + not persist an error-shaped tool result (#5878 misleading-error shape): {error}" ) })?; @@ -99,7 +104,52 @@ pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { .wait_for_status(run_id, TurnStatus::Completed) .await?; - // ── Phase 2: reconfigure (fresh credential) unwedges activation ───────── + // ── Phase 2: retry over the STILL-revoked credential gates AGAIN ──────── + // The lifecycle.md authentication-failure arm: a denied re-auth gate must + // not mark the requirement satisfied, and activation must not resume + // merely because the user retried — with no new credential, the second + // attempt parks at a fresh BlockedAuth gate (not one-shot, not a wedge, + // not a silent success). Without this arm, phase 3's post-seed success + // cannot distinguish "fresh credential unwedged it" from "the gate only + // ever fires once". + let retrier = g + .thread("notion-reauth-retry") + .script([ + RebornScriptedReply::tool_call( + "builtin.extension_activate", + json!({"extension_id": "notion"}), + ), + RebornScriptedReply::text("notion still needs reauthorization"), + ]) + .build() + .await?; + let (retry_run_id, retry_gate_ref) = retrier + .submit_turn_until_auth_blocked("set up notion again") + .await?; + let retry_state = retrier + .wait_for_status(retry_run_id, TurnStatus::BlockedAuth) + .await?; + if !retry_state + .credential_requirements + .iter() + .any(|requirement| requirement.provider == notion_provider) + { + return Err(format!( + "a RETRIED activation over the still-revoked credential must re-open the \ + notion re-auth gate (one-shot gate = the #5878 wedge); got {:?}", + retry_state.credential_requirements + ) + .into()); + } + retrier.assert_no_error_shaped_tool_result().await?; + retrier + .deny_auth_gate(retry_run_id, &retry_gate_ref) + .await?; + retrier + .wait_for_status(retry_run_id, TurnStatus::Completed) + .await?; + + // ── Phase 3: reconfigure (fresh credential) unwedges activation ───────── let restorer = g .thread("notion-reauth-restore") .script([ diff --git a/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs b/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs index 06dfbfa430a..2fa87cd8b8e 100644 --- a/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs +++ b/tests/integration/group_extensions/scenario_slack_state_survives_reopen.rs @@ -42,48 +42,28 @@ pub async fn run(g: &RebornIntegrationGroup) -> HarnessResult<()> { // Durable "connected": the active identity binding reads back through a // FRESH host-state store over a FRESH root filesystem at the same - // storage_root — the state a restarted process would reconstruct. - if !slack - .has_active_identity_binding_after_reopen(&storage_root, &actor) - .await? - { - return Err( - "the active slack identity binding must survive an independent \ - store reopen; a restart would come up disconnected (#4556/#2939 shape)" - .into(), - ); - } - // Non-vacuity control: the same reopened probe must NOT report a binding - // for a user that never connected. + // storage_root — the state a restarted process would reconstruct. One + // reopen serves both probes, so the positive read and its non-vacuity + // control (a user that never connected) see the same reconstructed store. let stranger = ironclaw_host_api::UserId::new("reopen-probe-stranger") .map_err(|error| error.to_string())?; - if slack - .has_active_identity_binding_after_reopen(&storage_root, &stranger) - .await? - { - return Err( - "reopened binding probe reported a binding for a user that never connected; \ - the reopen read is not scoped correctly" - .into(), - ); + let bindings = slack + .active_identity_bindings_after_reopen(&storage_root, &[&actor, &stranger]) + .await?; + if bindings != [true, false] { + return Err(format!( + "reopened binding probe expected [connected actor, stranger] = [true, false], \ + got {bindings:?}; a restart would come up disconnected (#4556/#2939 shape) \ + or the reopen read is not scoped correctly" + ) + .into()); } // Durable "installed": the slack installation record reads back through a - // fresh installation store at the same root. - let installations = ironclaw_reborn_composition::test_support::open_local_dev_extension_installation_store_for_test( - &storage_root, - ) - .await? - .list_installations() - .await?; - if !installations - .iter() - .any(|installation| installation.extension_id().as_str() == "slack") - { - return Err( - "the slack installation record must survive an independent store reopen".into(), - ); - } + // fresh installation store at the same root (shared E-DURABLE reopen + // helper — prints the surviving installation list on failure). + g.assert_extension_install_persists_after_reopen("slack") + .await?; Ok(()) } diff --git a/tests/integration/oauth_connect.rs b/tests/integration/oauth_connect.rs index 10a3c7a700c..5415730bff1 100644 --- a/tests/integration/oauth_connect.rs +++ b/tests/integration/oauth_connect.rs @@ -113,29 +113,17 @@ async fn oauth_connect_flow_persists_credential_account() { let state_hash = OpaqueStateHash::new(hex64(0xaa)).unwrap(); let pkce_hash = PkceVerifierHash::new(hex64(0xbb)).unwrap(); let code_hash = AuthorizationCodeHash::new(hex64(0xcc)).unwrap(); - let expires_at = Utc::now() + Duration::minutes(5); let flow = bundle .services .flow_manager() - .create_flow(NewAuthFlow { - id: None, - scope: scope.clone(), - kind: AuthFlowKind::IntegrationCredential, - provider: provider.clone(), - challenge: AuthChallenge::OAuthUrl { - authorization_url: OAuthAuthorizationUrl::new( - "https://accounts.example.com/o/oauth2/auth", - ) - .unwrap(), - expires_at, - }, - continuation: AuthContinuationRef::SetupOnly, - update_binding: None, - opaque_state_hash: Some(state_hash.clone()), - pkce_verifier_hash: Some(pkce_hash.clone()), - expires_at, - }) + .create_flow(new_flow_request( + &scope, + &provider, + &state_hash, + &pkce_hash, + Utc::now() + Duration::minutes(5), + )) .await .expect("create_flow must succeed"); @@ -143,28 +131,15 @@ async fn oauth_connect_flow_persists_credential_account() { // fixed access-token JSON body; no real network call is made. let response = bundle .services - .handle_oauth_callback(RebornOAuthCallbackRequest { - scope: scope.clone(), - flow_id: flow.id, - opaque_state_hash: state_hash, - outcome: RebornOAuthCallbackOutcome::Authorized { - provider_request: OAuthProviderCallbackRequest { - provider: provider.clone(), - account_label: CredentialAccountLabel::new("Test Account").unwrap(), - authorization_code: OAuthAuthorizationCode::new(SecretString::from( - "raw-auth-code-value".to_string(), - )) - .unwrap(), - authorization_code_hash: code_hash, - pkce_verifier: PkceVerifierSecret::new(SecretString::from( - "raw-pkce-verifier-value".to_string(), - )) - .unwrap(), - pkce_verifier_hash: pkce_hash, - scopes: vec![ProviderScope::new("test.readonly").unwrap()], - }, - }, - }) + .handle_oauth_callback(authorized_callback_request( + &scope, + flow.id, + &provider, + &state_hash, + &pkce_hash, + &code_hash, + "Test Account", + )) .await .expect("handle_oauth_callback must succeed"); @@ -216,37 +191,21 @@ async fn oauth_connect_flow_persists_credential_account() { async fn oauth_callback_without_prior_flow_fails() { let bundle = build_oauth_product_auth_for_test(); let scope = test_scope(); - // Clone scope before it is moved into the callback request so we can use - // it for the list_accounts assertion after the error is returned. - let scope_for_assert = scope.clone(); let state_hash = OpaqueStateHash::new(hex64(0xdd)).unwrap(); let pkce_hash = PkceVerifierHash::new(hex64(0xee)).unwrap(); let code_hash = AuthorizationCodeHash::new(hex64(0xff)).unwrap(); let error = bundle .services - .handle_oauth_callback(RebornOAuthCallbackRequest { - scope, - flow_id: AuthFlowId::new(), // no flow was created for this id - opaque_state_hash: state_hash, - outcome: RebornOAuthCallbackOutcome::Authorized { - provider_request: OAuthProviderCallbackRequest { - provider: AuthProviderId::new("test-oauth-provider").unwrap(), - account_label: CredentialAccountLabel::new("Guard Account").unwrap(), - authorization_code: OAuthAuthorizationCode::new(SecretString::from( - "guard-auth-code".to_string(), - )) - .unwrap(), - authorization_code_hash: code_hash, - pkce_verifier: PkceVerifierSecret::new(SecretString::from( - "guard-pkce-verifier".to_string(), - )) - .unwrap(), - pkce_verifier_hash: pkce_hash, - scopes: vec![], - }, - }, - }) + .handle_oauth_callback(authorized_callback_request( + &scope, + AuthFlowId::new(), // no flow was created for this id + &AuthProviderId::new("test-oauth-provider").unwrap(), + &state_hash, + &pkce_hash, + &code_hash, + "Guard Account", + )) .await .expect_err("callback with no prior flow must return an error"); @@ -267,7 +226,7 @@ async fn oauth_callback_without_prior_flow_fails() { .services .credential_account_service() .list_accounts(CredentialAccountListRequest::new( - scope_for_assert, + scope, AuthProviderId::new("test-oauth-provider").unwrap(), )) .await @@ -510,7 +469,8 @@ async fn replayed_callback_is_idempotent_then_fresh_flow_reconnects() { "a replayed callback must not mint a second credential account" ); - // Reconnect: a fresh flow must still succeed after the replay rejection. + // Reconnect: a fresh flow must still succeed after the idempotent replay + // (which returned the ORIGINAL completed outcome — no rejection occurred). let reconnect_state = OpaqueStateHash::new(hex64(0x81)).unwrap(); let reconnect_pkce = PkceVerifierHash::new(hex64(0x82)).unwrap(); let reconnect_code = AuthorizationCodeHash::new(hex64(0x83)).unwrap(); diff --git a/tests/integration/support/assertions.rs b/tests/integration/support/assertions.rs index 98e2942f0e0..6b7827f3c41 100644 --- a/tests/integration/support/assertions.rs +++ b/tests/integration/support/assertions.rs @@ -621,6 +621,107 @@ impl RebornIntegrationHarness { ) } + /// Every persisted `ToolResultReference`'s `(safe_summary, + /// observation_status)` pair, where `observation_status` is the envelope's + /// parsed `model_observation.status` (`"success"` / `"error"`) when an + /// observation is present. Shared collector for the error-SHAPE negative + /// assertions below; same fail-loud decode contract as + /// `persisted_tool_error_summaries`. + async fn persisted_tool_result_reference_shapes( + &self, + ) -> HarnessResult)>> { + let history = self + .thread_harness + .history(self.binding.thread_id.clone()) + .await?; + history + .iter() + .filter(|message| message.kind == ironclaw_threads::MessageKind::ToolResultReference) + .map(|message| { + let Some(content) = message.content.as_deref() else { + return Err("ToolResultReference message missing content".into()); + }; + serde_json::from_str::(content) + .map(|envelope| { + let status = envelope + .model_observation + .as_ref() + .and_then(|observation| observation.get("status")) + .and_then(|status| status.as_str()) + .map(str::to_string); + (envelope.safe_summary.as_str().to_string(), status) + }) + .map_err(|err| { + let truncated = match content.char_indices().nth(200) { + Some((cutoff, _)) => format!("{}...[truncated]", &content[..cutoff]), + None => content.to_string(), + }; + format!( + "failed to decode ToolResultReferenceEnvelope: {err}; raw: {truncated}" + ) + .into() + }) + }) + .collect() + } + + /// Assert NO persisted `ToolResultReference` is ERROR-SHAPED — where + /// error-shaped means EITHER the envelope's `model_observation.status` is + /// `"error"` (the structural marker + /// `model_visible_capability_failure_observation` attaches to Failed and + /// Denied outcomes) OR its `safe_summary` starts with a + /// [`ToolErrorClass`] prefix. + /// + /// Strictly stronger than `assert_no_tool_error(class, "")` for a + /// "surfaced EXCLUSIVELY as the gate" pin (#5878/#6105 T2): that prefix + /// filter is blind to the OTHER class's prefix and to executor-synthesized + /// raw planner summaries (e.g. the gate-declined "auth gate denied by + /// user"), which persist with no class prefix — the bypass + /// `short_circuit_denied_resume`'s own test documents. Residual gap + /// (accepted): an error persisted with no observation AND a novel + /// unprefixed summary evades both arms. + /// + /// Scans the full thread history (not baseline-sliced) — single-turn + /// threads only, like [`assert_tool_error`]. + /// + /// [`assert_tool_error`]: Self::assert_tool_error + pub async fn assert_no_error_shaped_tool_result(&self) -> HarnessResult<()> { + self.assert_no_error_shaped_tool_result_except(&[]).await + } + + /// [`Self::assert_no_error_shaped_tool_result`], allowing error-shaped + /// references whose summary contains one of `allowed_substrings` — for + /// post-resume checks where one deliberate error IS the contract (a + /// denied gate persists its planner summary) but nothing else + /// error-shaped may exist. + pub async fn assert_no_error_shaped_tool_result_except( + &self, + allowed_substrings: &[&str], + ) -> HarnessResult<()> { + let shapes = self.persisted_tool_result_reference_shapes().await?; + let offending: Vec<&(String, Option)> = shapes + .iter() + .filter(|(summary, status)| { + status.as_deref() == Some("error") + || summary.starts_with(ToolErrorClass::Failed.summary_prefix()) + || summary.starts_with(ToolErrorClass::Denied.summary_prefix()) + }) + .filter(|(summary, _)| { + !allowed_substrings + .iter() + .any(|allowed| summary.contains(allowed)) + }) + .collect(); + if offending.is_empty() { + return Ok(()); + } + Err(format!( + "expected no error-shaped ToolResultReference beyond {allowed_substrings:?}; \ + found (summary, observation-status) pairs {offending:?}" + ) + .into()) + } + /// Assert that any captured **network** egress request whose URL /// contains `url_substr` carried a header named `header_name` /// (case-insensitive) whose value contains `value_substr` — the diff --git a/tests/integration/support/builder.rs b/tests/integration/support/builder.rs index 433b6bbca32..ab1028d430c 100644 --- a/tests/integration/support/builder.rs +++ b/tests/integration/support/builder.rs @@ -25,7 +25,6 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; -use ironclaw_extensions::ExtensionInstallationStore; use ironclaw_filesystem::{ CompositeRootFilesystem, InMemoryBackend, LibSqlRootFilesystem, ScopedFilesystem, }; @@ -1007,32 +1006,10 @@ impl RebornIntegrationHarness { &self, extension_id: &str, ) -> HarnessResult<()> { - let harness = match &self._shared.capability { - GroupCapability::HostRuntime(arc) => arc, - GroupCapability::Recording => { - return Err("no host-runtime capability backend for durable reopen".into()); - } - }; - let store = - ironclaw_reborn_composition::test_support::open_local_dev_extension_installation_store_for_test( - &harness.storage_root_for_test(), - ) - .await?; - let installations = store.list_installations().await?; - if installations - .iter() - .any(|installation| installation.extension_id().as_str() == extension_id) - { - return Ok(()); - } - let seen: Vec<&str> = installations - .iter() - .map(|installation| installation.extension_id().as_str()) - .collect(); - Err( - format!("extension {extension_id:?} not found after independent reopen; saw {seen:?}") - .into(), - ) + self._shared + .capability + .assert_extension_install_persists_after_reopen(extension_id) + .await } /// Assert the named capability was invoked through the real capability path diff --git a/tests/integration/support/group.rs b/tests/integration/support/group.rs index c554dd55ef1..9973f4f3765 100644 --- a/tests/integration/support/group.rs +++ b/tests/integration/support/group.rs @@ -55,6 +55,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicU64; use std::time::Duration; +use ironclaw_extensions::ExtensionInstallationStore; use ironclaw_filesystem::CompositeRootFilesystem; use ironclaw_host_api::{ResourceScope, UserId}; use ironclaw_llm::testing::provider_chain_over; @@ -328,6 +329,45 @@ impl GroupCapability { Self::HostRuntime(arc) => HarnessCapabilityMode::HostRuntime(Arc::clone(arc)), } } + + /// E-DURABLE core: assert `extension_id` is present in a FRESHLY reopened + /// `ExtensionInstallationStore` at this backend's on-disk `storage_root` + /// (a handle independent of the live `Arc`) — proving the install + /// persisted to disk, not just to in-memory state. One implementation + /// behind both the harness- and group-level + /// `assert_extension_install_persists_after_reopen` so the reopen shape + /// and the `seen` diagnostics cannot drift. + pub(crate) async fn assert_extension_install_persists_after_reopen( + &self, + extension_id: &str, + ) -> HarnessResult<()> { + let harness = match self { + Self::HostRuntime(arc) => arc, + Self::Recording => { + return Err("no host-runtime capability backend for durable reopen".into()); + } + }; + let store = + ironclaw_reborn_composition::test_support::open_local_dev_extension_installation_store_for_test( + &harness.storage_root_for_test(), + ) + .await?; + let installations = store.list_installations().await?; + if installations + .iter() + .any(|installation| installation.extension_id().as_str() == extension_id) + { + return Ok(()); + } + let seen: Vec<&str> = installations + .iter() + .map(|installation| installation.extension_id().as_str()) + .collect(); + Err( + format!("extension {extension_id:?} not found after independent reopen; saw {seen:?}") + .into(), + ) + } } // --------------------------------------------------------------------------- @@ -442,6 +482,19 @@ impl RebornIntegrationGroup { } } + /// Group-level twin of the harness's + /// `assert_extension_install_persists_after_reopen`, for scenarios that + /// assert durable state without building a thread (E-DURABLE / T5). + pub async fn assert_extension_install_persists_after_reopen( + &self, + extension_id: &str, + ) -> HarnessResult<()> { + self.shared + .capability + .assert_extension_install_persists_after_reopen(extension_id) + .await + } + /// W5-WIRING-PARITY: the Some/None shape of the `DefaultPlannedRuntimeParts` /// literal this group's ONE planned runtime was actually built from /// (`into_group`), captured at construction time before the struct was