Real third-party MCP clients (Superhuman x3, Flowy, "Toffu") registered via
DCR and tried to sign in, but 0 ever completed: /oauth/authorize's sign-in
fallback was a form asking a human to paste a raw Scribase session token,
which no real user can produce. A redirect to console.scribase.com's login
was considered and rejected (plans/railyard.md 2026-11-12): console's own
session cookie is host-only and differently named (ry_session, not
scribase_session) and there is no cross-domain bridge, so that redirect
would just strand the user on the wrong subdomain.
Real fix: Toolgate now does its own two-step email-code sign-in, entirely
on toolgate.scribase.com, against the platform's own public, unauthenticated,
enumeration-safe magic-link endpoints
(POST {api}/v1/auth/builtin/magic-link/request + /verify) -- confirmed live
to return session.token in the exact shape ScribaseIdentity.user_from_session
already verifies via GET /v1/account, so no new verification path was
needed, only a new way to obtain the token.
- IdentityProvider gets 3 new methods (supports_email_signin,
request_email_code, verify_email_code), all default-unimplemented (501)
so dev's StaticIdentity is unaffected.
- ScribaseIdentity implements them against the real magic-link endpoints.
- New routes POST /oauth/signin/email and POST /oauth/signin/code; sign_in_page
renders the real email form when the identity provider supports it (falls
back to login_url() redirect, then the old paste form, for other
deployments).
- Caught and fixed a real bug in the new code before it shipped: the
session+clear-email Set-Cookie pair was built as an array literal, which
axum's header IntoResponse impl inserts (last-wins), silently dropping the
session cookie -- a new integration test driving the full email+code+
redirect+consent flow caught it; fixed by appending both headers directly.
- 3 new unit tests (return_to/email/code validation) + 1 new end-to-end
integration test (wrong code rejected, right code opens a session, reaches
the real consent screen). cargo test --workspace: 0 failures.
280 lines
10 KiB
Rust
280 lines
10 KiB
Rust
//! Test harness: the real router and pipeline over MemStore, in-memory Relay
|
|
//! keys, and the testkit's fake upstreams, Mint and Rago.
|
|
|
|
#![allow(dead_code)]
|
|
|
|
use std::sync::Arc;
|
|
|
|
use axum::body::Body;
|
|
use axum::http::{HeaderMap, Request, StatusCode};
|
|
use axum::Router;
|
|
use chrono::Utc;
|
|
use secrecy::ExposeSecret;
|
|
use serde_json::{json, Value};
|
|
use switchyard_auth::{IdentityProvider, KeyVerifier, MemRelayKeys, StaticIdentity, TokenSigner};
|
|
use switchyard_meter::OutboxWorker;
|
|
use switchyard_server::{router, AppState, Deps, Settings};
|
|
use switchyard_store::{ApiKey, MemStore, Member, Org, Project, Store};
|
|
use switchyard_testkit::{fixtures, FakeHttp, FakeMint, FakeRago};
|
|
use switchyard_vault::Vault;
|
|
use tower::ServiceExt;
|
|
|
|
pub const BASE: &str = "https://sy.test";
|
|
pub const ACCOUNT: &str = "acct_acme";
|
|
pub const REVENUE: &str = "acct_switchyard_revenue";
|
|
|
|
pub struct H {
|
|
pub st: AppState,
|
|
pub app: Router,
|
|
pub http: Arc<FakeHttp>,
|
|
pub mint: Arc<FakeMint>,
|
|
pub rago: Arc<FakeRago>,
|
|
pub store: Arc<dyn Store>,
|
|
pub mem: Option<Arc<MemStore>>,
|
|
pub keys: Arc<MemRelayKeys>,
|
|
pub key: String,
|
|
pub org: Org,
|
|
pub project: Project,
|
|
}
|
|
|
|
pub fn project(org_id: &str) -> Project {
|
|
Project {
|
|
id: format!("prj_{}", ulid::Ulid::new().to_string().to_lowercase()),
|
|
org_id: org_id.into(),
|
|
name: "default".into(),
|
|
monthly_cap_micros: None,
|
|
daily_cap_micros: None,
|
|
tool_daily_caps: Default::default(),
|
|
routing_policy: "free_first".into(),
|
|
egress_extra_hosts: vec![],
|
|
pinned_tools: vec![],
|
|
daily_send_limit: Some(100),
|
|
created_at: Utc::now(),
|
|
}
|
|
}
|
|
|
|
pub async fn harness() -> H {
|
|
let mem = Arc::new(MemStore::new());
|
|
harness_with(mem.clone(), Some(mem)).await
|
|
}
|
|
|
|
/// Like [`harness`], but the identity provider is a [`FakeEmailIdentity`]
|
|
/// (real inline email-code sign-in) instead of the dev-only `StaticIdentity`.
|
|
pub async fn harness_email_identity() -> H {
|
|
let mem = Arc::new(MemStore::new());
|
|
harness_configured_with_identity(mem.clone(), Some(mem), fixtures::catalog(), |_| {}, Arc::new(FakeEmailIdentity)).await
|
|
}
|
|
|
|
pub async fn harness_with(store: Arc<dyn Store>, mem: Option<Arc<MemStore>>) -> H {
|
|
harness_full(store, mem, fixtures::catalog()).await
|
|
}
|
|
|
|
/// The shipped catalog with `edit` applied to every tool manifest.
|
|
pub fn catalog_with(edit: impl Fn(&mut switchyard_core::ToolManifest)) -> switchyard_catalog::Catalog {
|
|
let base = fixtures::catalog();
|
|
let tools = base
|
|
.tools()
|
|
.cloned()
|
|
.map(|mut t| {
|
|
edit(&mut t);
|
|
t
|
|
})
|
|
.collect();
|
|
switchyard_catalog::Catalog::from_parts(
|
|
base.capabilities().cloned().collect(),
|
|
base.providers().cloned().collect(),
|
|
tools,
|
|
base.bundles().cloned().collect(),
|
|
)
|
|
.expect("edited catalog verifies")
|
|
}
|
|
|
|
pub async fn harness_with_catalog(catalog: switchyard_catalog::Catalog) -> H {
|
|
let mem = Arc::new(MemStore::new());
|
|
harness_full(mem.clone(), Some(mem), catalog).await
|
|
}
|
|
|
|
pub async fn harness_full(store: Arc<dyn Store>, mem: Option<Arc<MemStore>>, catalog: switchyard_catalog::Catalog) -> H {
|
|
harness_configured(store, mem, catalog, |_| {}).await
|
|
}
|
|
|
|
/// The shipped catalog with `edit` applied to every provider manifest.
|
|
pub fn catalog_with_providers(edit: impl Fn(&mut switchyard_core::ProviderManifest)) -> switchyard_catalog::Catalog {
|
|
let base = fixtures::catalog();
|
|
let providers = base
|
|
.providers()
|
|
.cloned()
|
|
.map(|mut p| {
|
|
edit(&mut p);
|
|
p
|
|
})
|
|
.collect();
|
|
switchyard_catalog::Catalog::from_parts(base.capabilities().cloned().collect(), providers, base.tools().cloned().collect(), base.bundles().cloned().collect())
|
|
.expect("edited catalog verifies")
|
|
}
|
|
|
|
pub async fn harness_configured(store: Arc<dyn Store>, mem: Option<Arc<MemStore>>, catalog: switchyard_catalog::Catalog, configure: impl FnOnce(&mut Settings)) -> H {
|
|
let identity: Arc<dyn IdentityProvider> = Arc::new(StaticIdentity::new(&[("sess-alice", "u_alice", "alice@acme.test"), ("sess-mallory", "u_mallory", "m@evil.test")]));
|
|
harness_configured_with_identity(store, mem, catalog, configure, identity).await
|
|
}
|
|
|
|
/// Same as [`harness_configured`], but with the identity provider overridable
|
|
/// (the OAuth email-sign-in tests need one that actually supports it,
|
|
/// unlike the default `StaticIdentity`).
|
|
pub async fn harness_configured_with_identity(
|
|
store: Arc<dyn Store>,
|
|
mem: Option<Arc<MemStore>>,
|
|
catalog: switchyard_catalog::Catalog,
|
|
configure: impl FnOnce(&mut Settings),
|
|
identity: Arc<dyn IdentityProvider>,
|
|
) -> H {
|
|
let mut settings = Settings::for_tests(BASE);
|
|
settings.adapter_config = fixtures::test_config();
|
|
settings.platform_credentials.insert("rally".into(), "platform-rally-token".into());
|
|
settings.platform_credentials.insert("menivor".into(), "platform-menivor-token".into());
|
|
configure(&mut settings);
|
|
let keys = Arc::new(MemRelayKeys::new());
|
|
let http = FakeHttp::new();
|
|
fixtures::install_all(&http);
|
|
let mint = FakeMint::new();
|
|
mint.fund(ACCOUNT, 10_000_000);
|
|
let rago = FakeRago::new();
|
|
let st = AppState::new(Deps {
|
|
settings,
|
|
catalog,
|
|
store: store.clone(),
|
|
keys: keys.clone(),
|
|
identity,
|
|
vault: Vault::new(1, &Vault::generate_kek_b64()).unwrap(),
|
|
http: http.clone(),
|
|
mint: Some(mint.clone()),
|
|
rago: Some(rago.clone()),
|
|
signer: TokenSigner::new(None).unwrap(),
|
|
})
|
|
.unwrap();
|
|
let suffix = ulid::Ulid::new().to_string().to_lowercase();
|
|
let org = store
|
|
.create_org(Org {
|
|
id: format!("org_{suffix}"),
|
|
slug: format!("acme-{}", &suffix[suffix.len() - 8..]),
|
|
name: "Acme".into(),
|
|
mint_account_id: Some(ACCOUNT.into()),
|
|
rago_subscription_id: Some("sub_acme".into()),
|
|
created_at: Utc::now(),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
let project = store.create_project(project(&org.id)).await.unwrap();
|
|
store.upsert_member(Member { org_id: org.id.clone(), user_id: "u_alice".into(), role: "owner".into() }).await.unwrap();
|
|
let key = mint_key(&keys, store.as_ref(), &org, &project.id, &["tools:read", "tools:call", "tools:write", "tools:send", "tools:spend", "admin"], None).await;
|
|
let app = router(st.clone());
|
|
H { st, app, http, mint, rago, store, mem, keys, key, org, project }
|
|
}
|
|
|
|
pub async fn mint_key(keys: &MemRelayKeys, store: &dyn Store, org: &Org, project_id: &str, scopes: &[&str], tool_allow: Option<Vec<String>>) -> String {
|
|
let (raw, public_id) = keys.mint(&org.slug, project_id, "test").await.unwrap();
|
|
store
|
|
.insert_api_key(ApiKey {
|
|
public_id,
|
|
project_id: project_id.into(),
|
|
description: "test".into(),
|
|
scopes: scopes.iter().map(|s| s.to_string()).collect(),
|
|
tool_allow,
|
|
per_key_daily_cap_micros: None,
|
|
extra_projects: vec![],
|
|
revoked_at: None,
|
|
created_at: Utc::now(),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
raw.expose_secret().to_string()
|
|
}
|
|
|
|
pub struct Resp {
|
|
pub status: StatusCode,
|
|
pub headers: HeaderMap,
|
|
pub body: Value,
|
|
pub text: String,
|
|
}
|
|
|
|
pub async fn send(app: &Router, method: &str, path: &str, token: Option<&str>, body: Option<Value>, extra: &[(&str, &str)]) -> Resp {
|
|
let mut b = Request::builder().method(method).uri(path);
|
|
if let Some(t) = token {
|
|
b = b.header("authorization", format!("Bearer {t}"));
|
|
}
|
|
for (k, v) in extra {
|
|
b = b.header(*k, *v);
|
|
}
|
|
let req = match body {
|
|
Some(v) => b.header("content-type", "application/json").body(Body::from(v.to_string())).unwrap(),
|
|
None => b.body(Body::empty()).unwrap(),
|
|
};
|
|
raw(app, req).await
|
|
}
|
|
|
|
pub async fn raw(app: &Router, req: Request<Body>) -> Resp {
|
|
let resp = app.clone().oneshot(req).await.unwrap();
|
|
let status = resp.status();
|
|
let headers = resp.headers().clone();
|
|
let bytes = axum::body::to_bytes(resp.into_body(), 16 * 1024 * 1024).await.unwrap();
|
|
let text = String::from_utf8_lossy(&bytes).to_string();
|
|
let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
|
|
Resp { status, headers, body, text }
|
|
}
|
|
|
|
pub async fn call(h: &H, tool: &str, input: Value) -> Resp {
|
|
send(&h.app, "POST", &format!("/v1/tools/{tool}/call"), Some(&h.key), Some(json!({ "input": input })), &[]).await
|
|
}
|
|
|
|
pub async fn drain(h: &H) -> switchyard_meter::outbox::DrainReport {
|
|
OutboxWorker { store: h.store.clone(), rago: Some(h.rago.clone()), mint: Some(h.mint.clone()) }.drain_once().await
|
|
}
|
|
|
|
/// An [`IdentityProvider`] that exercises the real inline email-code sign-in
|
|
/// path (`StaticIdentity` deliberately does not, since real deployments
|
|
/// without `SWITCHYARD_SCRIBASE_LOGIN_URL`/`_API_URL` get `StaticIdentity`
|
|
/// only in dev, never in prod). One fixed address/code pair, resolving to the
|
|
/// same `u_alice` user the rest of this harness already wires up as an org
|
|
/// member -- so a real sign-in here reaches the same consent screen the
|
|
/// `StaticIdentity`-cookie tests do.
|
|
pub struct FakeEmailIdentity;
|
|
|
|
impl FakeEmailIdentity {
|
|
pub const EMAIL: &'static str = "alice@acme.test";
|
|
pub const CODE: &'static str = "424242";
|
|
const SESSION_TOKEN: &'static str = "fake-email-session-u_alice";
|
|
}
|
|
|
|
#[async_trait::async_trait]
|
|
impl IdentityProvider for FakeEmailIdentity {
|
|
async fn user_from_session(&self, session_token: &str) -> Result<switchyard_auth::User, switchyard_core::ApiError> {
|
|
if session_token == Self::SESSION_TOKEN {
|
|
Ok(switchyard_auth::User { id: "u_alice".into(), email: Self::EMAIL.into() })
|
|
} else {
|
|
Err(switchyard_core::ApiError::unauthorized("unknown session"))
|
|
}
|
|
}
|
|
|
|
fn login_url(&self, _return_to: &str) -> Option<String> {
|
|
None
|
|
}
|
|
|
|
fn supports_email_signin(&self) -> bool {
|
|
true
|
|
}
|
|
|
|
async fn request_email_code(&self, email: &str) -> Result<(), switchyard_core::ApiError> {
|
|
// Enumeration-safe like the real endpoint: never errors on an unknown address.
|
|
let _ = email;
|
|
Ok(())
|
|
}
|
|
|
|
async fn verify_email_code(&self, email: &str, code: &str) -> Result<String, switchyard_core::ApiError> {
|
|
if email == Self::EMAIL && code == Self::CODE {
|
|
Ok(Self::SESSION_TOKEN.to_string())
|
|
} else {
|
|
Err(switchyard_core::ApiError::unauthorized("that code was not accepted; request a new one"))
|
|
}
|
|
}
|
|
}
|