Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(connect): list connected users and add a demo dashboard (#9272)
Eric Hayes458159ff1b91
diff --git a/Cargo.lock b/Cargo.lockindex 5e6f6f6dc8..626668ad9a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4946,6 +4946,7 @@ name = "connect_demo"version = "0.1.0"dependencies = ["axum",+ "chrono","connect_client","connect_platform","futures",diff --git a/connect/STATUS.md b/connect/STATUS.mdindex c0626577e4..36c9fc452f 100644--- a/connect/STATUS.md+++ b/connect/STATUS.md@@ -2,7 +2,7 @@Last updated 2026-10-31 by Claude. Slice 1 is deployed and proven end to endon dev: `https://connect-dev.macro.com`, demo at-`https://connect-dev.macro.com/demo`. Target: Macro's own users off Pipedream+`https://connect-dev.macro.com/demo`, dashboard at `/demo/dashboard`. Target: Macro's own users off Pipedreamfor catalog apps by 2026-11-06 ([plan](docs/plan.md#week-one)).## Human queue@@ -13,6 +13,9 @@ Eric. Each item is ready for one sitting; agents prepare the rest.Macro's deployed services).- [ ] **Review the demo PR** (stacked on #9231): the demo app, its optionalinfra, and the CDP driver.+- [ ] **Review the dashboard PR #9272** (stacked on the demo PR):+ `/v1/connections`, `/v1/users`, `/v1/connections/summary`, and+ `/demo/dashboard`.- [ ] **Company facts every vendor form asks for** (unblocks Zoom, Xero,Figma, Vercel, Box, Discord): legal company name; contact name, title,and email; Connect's production host and OAuth callback (proposed:@@ -66,6 +69,8 @@ expires, the gateway must refresh it; unit-tested, not yet seen live). Thenits tools (70, 68, 1, 12) and answered a read tool call.[T019](tasks/T019-demo-app.md) demo deployed at `/demo`: connect, listtools, and call a tool from the browser. `cdp.ts` drives the browser.+ [T020](tasks/T020-users-dashboard.md) user and connection listings plus+ `/demo/dashboard`, deployed and checked in the browser.- 2026-10-30: [T014](tasks/T014-deny-wrappers.md), [T015](tasks/T015-test-databases.md)CI fixes; [T016](tasks/T016-independent-hosting.md) Connect hosteddiff --git a/connect/crates/connect_client/AGENTS.md b/connect/crates/connect_client/AGENTS.mdindex c849189f81..5007c9c76e 100644--- a/connect/crates/connect_client/AGENTS.md+++ b/connect/crates/connect_client/AGENTS.md@@ -9,6 +9,10 @@ The public Rust surface for Macro Connect customers. API changes here are breaki- `src/lib.rs`: authenticated async client, error mapping, and MCP gateway address.- `catalog_icon` fetches public SVG icons so customer apps do not call the Connect API directly from the browser.- `src/wire.rs`: shared request and response types used by the client and `connect_api`.+- `list_connections(ConnectionsQuery)` returns a customer-scoped page;+ `all_connections` follows every cursor; `connections_summary` returns counts.+- `list_users(UsersQuery)` returns complete connected users in a customer-scoped+ page; `all_users` follows every cursor.## Scopediff --git a/connect/crates/connect_client/src/lib.rs b/connect/crates/connect_client/src/lib.rsindex 293d5a0f68..096db48102 100644--- a/connect/crates/connect_client/src/lib.rs+++ b/connect/crates/connect_client/src/lib.rs@@ -13,8 +13,9 @@ use url::Url;use zeroize::{Zeroize as _, Zeroizing};use wire::{- CatalogEntry, ConnectSessionRequest, ConnectSessionResponse, Connection, DeleteResponse,- ErrorResponse, TokenResponse,+ CatalogEntry, ConnectSessionRequest, ConnectSessionResponse, Connection, ConnectionsPage,+ ConnectionsQuery, ConnectionsSummary, DeleteResponse, ErrorResponse, ListedConnection,+ ListedUser, TokenResponse, UsersPage, UsersQuery,};/// A failure a Connect customer can act on.@@ -186,6 +187,134 @@ impl ConnectClient {.await}+ /// List one page of this customer's connections, newest first.+ #[tracing::instrument(+ name = "connect.client.list_connections",+ skip_all,+ fields(count, outcome),+ err+ )]+ pub async fn list_connections(+ &self,+ query: ConnectionsQuery,+ ) -> Result<ConnectionsPage, Error> {+ let mut url = self.route(&["v1", "connections"]);+ {+ let mut pairs = url.query_pairs_mut();+ if let Some(limit) = query.limit {+ pairs.append_pair("limit", &limit.to_string());+ }+ if let Some(cursor) = &query.cursor {+ pairs.append_pair("cursor", cursor);+ }+ if let Some(app_id) = &query.app_id {+ pairs.append_pair("app_id", app_id);+ }+ if let Some(status) = query.status {+ pairs.append_pair("status", &status.to_string());+ }+ }+ let page: ConnectionsPage = self.request_at(Method::GET, url, None).await?;+ Span::current().record("count", page.items.len());+ Ok(page)+ }++ /// Return summary counts for this customer.+ #[tracing::instrument(+ name = "connect.client.connections_summary",+ skip_all,+ fields(users, connections, outcome),+ err+ )]+ pub async fn connections_summary(&self) -> Result<ConnectionsSummary, Error> {+ let summary: ConnectionsSummary = self+ .request(Method::GET, &["v1", "connections", "summary"], None)+ .await?;+ Span::current().record("users", summary.users);+ Span::current().record("connections", summary.connections);+ Ok(summary)+ }++ /// Collect every page matching the filters. Callers should use pages for large datasets.+ pub async fn all_connections(+ &self,+ mut query: ConnectionsQuery,+ ) -> Result<Vec<ListedConnection>, Error> {+ let mut items = Vec::new();+ loop {+ let page = self.list_connections(query.clone()).await?;+ items.extend(page.items);+ match page.next_cursor {+ Some(cursor) if query.cursor.as_deref() != Some(&cursor) => {+ query.cursor = Some(cursor)+ }+ Some(_) => {+ return Err(Error::Internal(+ rootcause::Report::new(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "repeated connections cursor",+ ))+ .into_dynamic(),+ ));+ }+ None => return Ok(items),+ }+ }+ }++ /// List one page of connected users with all of each user's connections.+ #[tracing::instrument(+ name = "connect.client.list_users",+ skip_all,+ fields(count, outcome),+ err+ )]+ pub async fn list_users(&self, query: UsersQuery) -> Result<UsersPage, Error> {+ let mut url = self.route(&["v1", "users"]);+ {+ let mut pairs = url.query_pairs_mut();+ if let Some(limit) = query.limit {+ pairs.append_pair("limit", &limit.to_string());+ }+ if let Some(cursor) = &query.cursor {+ pairs.append_pair("cursor", cursor);+ }+ if let Some(app_id) = &query.app_id {+ pairs.append_pair("app_id", app_id);+ }+ if let Some(status) = query.status {+ pairs.append_pair("status", &status.to_string());+ }+ }+ let page: UsersPage = self.request_at(Method::GET, url, None).await?;+ Span::current().record("count", page.items.len());+ Ok(page)+ }++ /// Collect all connected users matching the filters.+ pub async fn all_users(&self, mut query: UsersQuery) -> Result<Vec<ListedUser>, Error> {+ let mut items = Vec::new();+ loop {+ let page = self.list_users(query.clone()).await?;+ items.extend(page.items);+ match page.next_cursor {+ Some(cursor) if query.cursor.as_deref() != Some(&cursor) => {+ query.cursor = Some(cursor)+ }+ Some(_) => {+ return Err(Error::Internal(+ rootcause::Report::new(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "repeated users cursor",+ ))+ .into_dynamic(),+ ));+ }+ None => return Ok(items),+ }+ }+ }+/// Delete a user's app connection locally. The vendor grant is not revoked.#[tracing::instrument(name = "connect.client.delete_connection", skip_all, fields(app_id = %app_id, outcome), err)]pub async fn delete_connection(@@ -247,12 +376,21 @@ impl ConnectClient {method: Method,parts: &[&str],body: Option<&ConnectSessionRequest>,+ ) -> Result<T, Error> {+ self.request_at(method, self.route(parts), body).await+ }++ async fn request_at<T: serde::de::DeserializeOwned>(+ &self,+ method: Method,+ url: Url,+ body: Option<&ConnectSessionRequest>,) -> Result<T, Error> {let mut headers = HeaderMap::new();inject_trace_headers(&mut headers);let mut request = self.http- .request(method, self.route(parts))+ .request(method, url).headers(headers).bearer_auth(self.customer_key.as_str());if let Some(body) = body {diff --git a/connect/crates/connect_client/src/test.rs b/connect/crates/connect_client/src/test.rsindex cc031d0bed..8e57a0a7c3 100644--- a/connect/crates/connect_client/src/test.rs+++ b/connect/crates/connect_client/src/test.rs@@ -1,7 +1,7 @@use super::*;use wiremock::{Mock, MockServer, ResponseTemplate,- matchers::{body_json, header, method, path},+ matchers::{body_json, header, method, path, query_param},};#[tokio::test]@@ -101,6 +101,91 @@ async fn calls_every_customer_route_with_the_shared_wire_contract() {assert_eq!(server.received_requests().await.unwrap().len(), 6);}+#[tokio::test]+async fn lists_customer_pages_and_summary_with_filters() {+ let server = MockServer::start().await;+ Mock::given(method("GET")).and(path("/v1/connections"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .and(query_param("limit", "1"))+ .and(query_param("app_id", "notion"))+ .and(query_param("status", "active"))+ .respond_with(|request: &wiremock::Request| {+ if request.url.query_pairs().any(|(key, value)| key == "cursor" && value == "next") {+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": [{"externalUserId":"second","appId":"notion","status":"active","scopes":[],"createdAt":"2026-10-29T09:00:00Z","updatedAt":"2026-10-29T10:00:00Z","accessTokenExpiresAt":null}],"nextCursor":null}))+ } else {+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": [{"externalUserId":"first","appId":"notion","status":"active","scopes":["read"],"createdAt":"2026-10-30T09:00:00Z","updatedAt":"2026-10-30T10:00:00Z","accessTokenExpiresAt":"2026-10-30T11:00:00Z"}],"nextCursor":"next"}))+ }+ }).mount(&server).await;+ Mock::given(method("GET")).and(path("/v1/connections/summary"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"users":2,"connections":2,"needsReauth":0,"apps":[{"appId":"notion","active":2,"needsReauth":0}]})))+ .mount(&server).await;+ let client = ConnectClient::new(&server.uri(), "ck_test_secret").unwrap();+ let query = wire::ConnectionsQuery {+ limit: Some(1),+ cursor: None,+ app_id: Some("notion".into()),+ status: Some(wire::ConnectionStatus::Active),+ };+ let page = client.list_connections(query.clone()).await.unwrap();+ assert_eq!(page.items[0].external_user_id, "first");+ assert!(page.items[0].access_token_expires_at.is_some());+ assert_eq!(page.next_cursor.as_deref(), Some("next"));+ let all = client.all_connections(query).await.unwrap();+ assert_eq!(+ all.iter()+ .map(|item| item.external_user_id.as_str())+ .collect::<Vec<_>>(),+ ["first", "second"]+ );+ let summary = client.connections_summary().await.unwrap();+ assert_eq!(+ (summary.users, summary.connections, summary.apps[0].active),+ (2, 2, 2)+ );+}++#[tokio::test]+async fn lists_complete_user_pages_with_filters() {+ let server = MockServer::start().await;+ Mock::given(method("GET")).and(path("/v1/users"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .and(query_param("limit", "1"))+ .and(query_param("app_id", "notion"))+ .and(query_param("status", "active"))+ .respond_with(|request: &wiremock::Request| {+ let (user, cursor) = if request.url.query_pairs().any(|(key, value)| key == "cursor" && value == "next") {+ ("second", serde_json::Value::Null)+ } else {+ ("first", serde_json::json!("next"))+ };+ ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "items":[{"externalUserId":user,"firstConnectedAt":"2026-10-30T09:00:00Z","connections":[+ {"externalUserId":user,"appId":"linear","status":"needs_reauth","scopes":[],"createdAt":"2026-10-29T09:00:00Z","updatedAt":"2026-10-29T10:00:00Z","accessTokenExpiresAt":null},+ {"externalUserId":user,"appId":"notion","status":"active","scopes":[],"createdAt":"2026-10-30T09:00:00Z","updatedAt":"2026-10-30T10:00:00Z","accessTokenExpiresAt":null}+ ]}],"nextCursor":cursor+ }))+ }).mount(&server).await;+ let client = ConnectClient::new(&server.uri(), "ck_test_secret").unwrap();+ let query = wire::UsersQuery {+ limit: Some(1),+ cursor: None,+ app_id: Some("notion".into()),+ status: Some(wire::ConnectionStatus::Active),+ };+ let first = client.list_users(query.clone()).await.unwrap();+ assert_eq!(first.items.len(), 1);+ assert_eq!(first.items[0].connections.len(), 2);+ assert_eq!(first.next_cursor.as_deref(), Some("next"));+ let all = client.all_users(query).await.unwrap();+ assert_eq!(+ all.iter()+ .map(|user| user.external_user_id.as_str())+ .collect::<Vec<_>>(),+ ["first", "second"]+ );+}+#[tokio::test]async fn maps_status_and_error_codes_for_callers() {for (status, code, expected) in [diff --git a/connect/crates/connect_client/src/wire.rs b/connect/crates/connect_client/src/wire.rsindex 75e3aa12f7..b8753b4daf 100644--- a/connect/crates/connect_client/src/wire.rs+++ b/connect/crates/connect_client/src/wire.rs@@ -59,6 +59,110 @@ pub struct Connection {pub created_at: DateTime<Utc>,}+/// Filters and paging for a customer's connections.+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+pub struct ConnectionsQuery {+ /// Page size; defaults to 100 and cannot exceed 500.+ pub limit: Option<u16>,+ /// Opaque cursor from a prior page.+ pub cursor: Option<String>,+ /// Restrict results to an app.+ pub app_id: Option<String>,+ /// Restrict results to a connection status.+ pub status: Option<ConnectionStatus>,+}++/// A connection and its owning customer's opaque user identifier.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListedConnection {+ /// Customer-provided user identifier.+ pub external_user_id: String,+ /// Stable app identifier.+ pub app_id: String,+ /// Current usability.+ pub status: ConnectionStatus,+ /// Granted OAuth scopes.+ pub scopes: Vec<String>,+ /// Creation time.+ pub created_at: DateTime<Utc>,+ /// Last connection update.+ pub updated_at: DateTime<Utc>,+ /// Access token expiration, when known.+ pub access_token_expires_at: Option<DateTime<Utc>>,+}++/// One page of customer connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectionsPage {+ /// Connections in descending creation order.+ pub items: Vec<ListedConnection>,+ /// Opaque position for the next page, or null when complete.+ pub next_cursor: Option<String>,+}++/// Filters and paging for a customer's connected users.+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+pub struct UsersQuery {+ /// Number of users per page; defaults to 100 and cannot exceed 500.+ pub limit: Option<u16>,+ /// Opaque cursor from a prior page.+ pub cursor: Option<String>,+ /// Select users with a matching app connection.+ pub app_id: Option<String>,+ /// Select users with a matching connection status.+ pub status: Option<ConnectionStatus>,+}++/// A customer user and all of their connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListedUser {+ /// Customer-provided user identifier.+ pub external_user_id: String,+ /// Creation time of the user's first connection.+ pub first_connected_at: DateTime<Utc>,+ /// Every connection of the user, ordered by app ID.+ pub connections: Vec<ListedConnection>,+}++/// One page of connected users.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct UsersPage {+ /// Users ordered by first connection time, newest first, then user ID descending.+ pub items: Vec<ListedUser>,+ /// Opaque position for the next page, or null when complete.+ pub next_cursor: Option<String>,+}++/// Connection counts for one catalog app.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct AppConnectionsSummary {+ /// Stable app identifier.+ pub app_id: String,+ /// Usable connections.+ pub active: u64,+ /// Connections requiring new consent.+ pub needs_reauth: u64,+}++/// Counts for a customer and each app with connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectionsSummary {+ /// Distinct users with at least one connection.+ pub users: u64,+ /// Total connections.+ pub connections: u64,+ /// Connections requiring new consent.+ pub needs_reauth: u64,+ /// Counts by app; apps with no connections are omitted.+ pub apps: Vec<AppConnectionsSummary>,+}+/// Current usability of a connection.#[derive(Clone, Copy, Debug, Deserialize, Serialize, ToSchema, strum::EnumString, strum::Display,diff --git a/connect/docs/plan.md b/connect/docs/plan.mdindex cd3cbf518c..5a384338a1 100644--- a/connect/docs/plan.md+++ b/connect/docs/plan.md@@ -53,7 +53,7 @@ the Pipedream integration (`pipedream_mcp`) is replaced by an adapter over| Part | Where | Does || --- | --- | --- || Registry | `connect/registry/apps/<id>/` | One directory per app: `app.toml` (name, description, MCP URL, access, client registration, scopes, Pipedream slugs it replaces) and `icon.svg`. Source of truth for the catalog. |-| Connect API | `connect/services/connect_api` | Catalog, connect flow (authorize, callback), connection list and delete, token export. Its own Postgres database and Secrets Manager runtime secret. |+| Connect API | `connect/services/connect_api` | Catalog, connect flow (authorize, callback), per-user and customer-wide paginated connection lists, complete paginated user list, customer connection summary, delete, token export. Its own Postgres database and Secrets Manager runtime secret. || Hosting | `connect/infra` | Its own Pulumi project: ECS cluster, ALB and certificate (`connect-dev.macro.com`), RDS, KMS key, Secrets Manager. Touches nothing of Macro's but one DNS record. || MCP gateway | in `connect_api` | Per-connection MCP endpoint: injects the vendor token, refreshes it, forwards to the vendor's server. Customers call this, as Macro called Pipedream's remote MCP. || OAuth client | `connect/crates/` | Client registration in order: CIMD, DCR, then Macro Connect's own OAuth app. Ported from Macro's `mcp_client`, which already does all three. |diff --git a/connect/services/connect_api/AGENTS.md b/connect/services/connect_api/AGENTS.mdindex d238785e1a..bae3294d75 100644--- a/connect/services/connect_api/AGENTS.md+++ b/connect/services/connect_api/AGENTS.md@@ -43,6 +43,14 @@ grants in Connect's own Postgres database.- Customer clients create sessions at `POST /v1/connect-sessions`. The browserfollows the returned URL through vendor consent and callback; token exportrefreshes grants expiring within 60 seconds.+- Customer clients list all connections with `GET /v1/connections` (newest first,+ `limit` 1–500, opaque `cursor`, optional `app_id` and `status`) and read counts+ with `GET /v1/connections/summary`. Both require the customer key and scope+ results to that customer. Invalid listing parameters return 400.+- Customer clients list connected users with `GET /v1/users` (ordered by first+ connection, `limit` 1–500, opaque `cursor`, optional `app_id` and `status`).+ Each user includes all their connections; filters select users with a matching+ connection and do not trim the returned connection list.- Customer agents call `POST`, `GET`, or `DELETE``/v1/users/{external_user_id}/mcp/{app_id}` with their customer key. The gatewayforwards MCP traffic to a connected live app, refreshes once on vendor 401diff --git a/connect/services/connect_api/migrations/20261031170401_list_customer_connections.sql b/connect/services/connect_api/migrations/20261031170401_list_customer_connections.sqlnew file mode 100644index 0000000000..e877fe0851--- /dev/null+++ b/connect/services/connect_api/migrations/20261031170401_list_customer_connections.sql@@ -0,0 +1,3 @@+-- no-transaction+CREATE INDEX CONCURRENTLY connections_customer_created_id_idx+ ON connections (customer_id, created_at DESC, id DESC);diff --git a/connect/services/connect_api/src/domain.rs b/connect/services/connect_api/src/domain.rsindex 8d4dece7d3..97110671da 100644--- a/connect/services/connect_api/src/domain.rs+++ b/connect/services/connect_api/src/domain.rs@@ -1,3 +1,4 @@+use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -69,6 +70,63 @@ pub struct Connection {pub created_at: DateTime<Utc>,}+pub struct ListedConnection {+ pub id: Uuid,+ pub external_user_id: String,+ pub app_id: String,+ pub status: ConnectionStatus,+ pub scopes: Vec<String>,+ pub created_at: DateTime<Utc>,+ pub updated_at: DateTime<Utc>,+ pub access_token_expires_at: Option<DateTime<Utc>>,+}++pub struct ConnectionsFilter {+ pub limit: Option<u16>,+ pub cursor: Option<String>,+ pub app_id: Option<String>,+ pub status: Option<String>,+}++pub struct ConnectionPosition {+ pub created_at: DateTime<Utc>,+ pub id: Uuid,+}++pub struct ConnectionsPage {+ pub items: Vec<ListedConnection>,+ pub next_cursor: Option<String>,+}++pub struct UserPosition {+ pub first_connected_at: DateTime<Utc>,+ pub external_user_id: String,+}++pub struct ListedUser {+ pub external_user_id: String,+ pub first_connected_at: DateTime<Utc>,+ pub connections: Vec<ListedConnection>,+}++pub struct UsersPage {+ pub items: Vec<ListedUser>,+ pub next_cursor: Option<String>,+}++pub struct AppConnectionsSummary {+ pub app_id: String,+ pub active: u64,+ pub needs_reauth: u64,+}++pub struct ConnectionsSummary {+ pub users: u64,+ pub connections: u64,+ pub needs_reauth: u64,+ pub apps: Vec<AppConnectionsSummary>,+}+#[derive(Clone, Copy, Debug, strum::EnumString, strum::Display)]#[strum(serialize_all = "snake_case")]pub enum ConnectionStatus {@@ -183,6 +241,23 @@ pub trait GrantCipher: Send + Sync {pub trait Repository: Send + Sync {async fn authenticate(&self, key: &str) -> Result<Uuid, Error>;async fn list(&self, customer_id: Uuid, user_id: &str) -> Result<Vec<Connection>, Error>;+ async fn list_customer_connections(+ &self,+ customer_id: Uuid,+ limit: i64,+ position: Option<ConnectionPosition>,+ app_id: Option<&str>,+ status: Option<ConnectionStatus>,+ ) -> Result<Vec<ListedConnection>, Error>;+ async fn list_users(+ &self,+ customer_id: Uuid,+ limit: i64,+ position: Option<UserPosition>,+ app_id: Option<&str>,+ status: Option<ConnectionStatus>,+ ) -> Result<Vec<ListedUser>, Error>;+ async fn connections_summary(&self, customer_id: Uuid) -> Result<ConnectionsSummary, Error>;async fn delete(&self, customer_id: Uuid, user_id: &str, app_id: &str) -> Result<bool, Error>;#[cfg(test)]async fn grant(@@ -213,6 +288,159 @@ impl Service {result}+ #[tracing::instrument(name = "connect.connections.list_customer", skip_all, fields(customer_id = %customer_id, count, outcome), err)]+ pub async fn list_customer_connections(+ &self,+ customer_id: Uuid,+ filter: ConnectionsFilter,+ ) -> Result<ConnectionsPage, Error> {+ let limit = usize::from(filter.limit.unwrap_or(100));+ if !(1..=500).contains(&limit) {+ return Err(Error::InvalidRequest("invalid_limit"));+ }+ if filter+ .app_id+ .as_ref()+ .is_some_and(|app_id| connect_registry::AppId::parse(app_id).is_err())+ {+ return Err(Error::InvalidRequest("invalid_app_id"));+ }+ let status = filter+ .status+ .as_deref()+ .map(str::parse::<ConnectionStatus>)+ .transpose()+ .map_err(|_| Error::InvalidRequest("invalid_status"))?;+ let position = filter+ .cursor+ .as_deref()+ .map(|cursor| {+ let bytes = URL_SAFE_NO_PAD+ .decode(cursor)+ .map_err(|_| Error::InvalidRequest("invalid_cursor"))?;+ let value = std::str::from_utf8(&bytes)+ .map_err(|_| Error::InvalidRequest("invalid_cursor"))?;+ let (time, id) = value+ .split_once('|')+ .ok_or(Error::InvalidRequest("invalid_cursor"))?;+ Ok::<_, Error>(ConnectionPosition {+ created_at: DateTime::parse_from_rfc3339(time)+ .map_err(|_| Error::InvalidRequest("invalid_cursor"))?+ .with_timezone(&Utc),+ id: Uuid::parse_str(id).map_err(|_| Error::InvalidRequest("invalid_cursor"))?,+ })+ })+ .transpose()?;+ let mut items = self+ .repository+ .list_customer_connections(+ customer_id,+ i64::try_from(limit + 1).map_err(|_| Error::InvalidRequest("invalid_limit"))?,+ position,+ filter.app_id.as_deref(),+ status,+ )+ .await?;+ let has_more = items.len() > limit;+ items.truncate(limit);+ let next_cursor = if has_more {+ items.last().map(|item| {+ URL_SAFE_NO_PAD.encode(format!("{}|{}", item.created_at.to_rfc3339(), item.id))+ })+ } else {+ None+ };+ tracing::Span::current().record("count", items.len());+ tracing::Span::current().record("outcome", "ok");+ Ok(ConnectionsPage { items, next_cursor })+ }++ #[tracing::instrument(name = "connect.users.list", skip_all, fields(customer_id = %customer_id, count, outcome), err)]+ pub async fn list_users(+ &self,+ customer_id: Uuid,+ filter: ConnectionsFilter,+ ) -> Result<UsersPage, Error> {+ let limit = usize::from(filter.limit.unwrap_or(100));+ if !(1..=500).contains(&limit) {+ return Err(Error::InvalidRequest("invalid_limit"));+ }+ if filter+ .app_id+ .as_ref()+ .is_some_and(|app_id| connect_registry::AppId::parse(app_id).is_err())+ {+ return Err(Error::InvalidRequest("invalid_app_id"));+ }+ let status = filter+ .status+ .as_deref()+ .map(str::parse::<ConnectionStatus>)+ .transpose()+ .map_err(|_| Error::InvalidRequest("invalid_status"))?;+ let position = filter+ .cursor+ .as_deref()+ .map(|cursor| {+ let bytes = URL_SAFE_NO_PAD+ .decode(cursor)+ .map_err(|_| Error::InvalidRequest("invalid_cursor"))?;+ let value = std::str::from_utf8(&bytes)+ .map_err(|_| Error::InvalidRequest("invalid_cursor"))?;+ let (time, external_user_id) = value+ .split_once('|')+ .ok_or(Error::InvalidRequest("invalid_cursor"))?;+ if external_user_id.is_empty() {+ return Err(Error::InvalidRequest("invalid_cursor"));+ }+ Ok(UserPosition {+ first_connected_at: DateTime::parse_from_rfc3339(time)+ .map_err(|_| Error::InvalidRequest("invalid_cursor"))?+ .with_timezone(&Utc),+ external_user_id: external_user_id.to_owned(),+ })+ })+ .transpose()?;+ let mut items = self+ .repository+ .list_users(+ customer_id,+ i64::try_from(limit + 1).map_err(|_| Error::InvalidRequest("invalid_limit"))?,+ position,+ filter.app_id.as_deref(),+ status,+ )+ .await?;+ let has_more = items.len() > limit;+ items.truncate(limit);+ let next_cursor = if has_more {+ items.last().map(|item| {+ URL_SAFE_NO_PAD.encode(format!(+ "{}|{}",+ item.first_connected_at.to_rfc3339(),+ item.external_user_id+ ))+ })+ } else {+ None+ };+ tracing::Span::current().record("count", items.len());+ tracing::Span::current().record("outcome", "ok");+ Ok(UsersPage { items, next_cursor })+ }++ #[tracing::instrument(name = "connect.connections.summary", skip_all, fields(customer_id = %customer_id, users, connections, outcome), err)]+ pub async fn connections_summary(+ &self,+ customer_id: Uuid,+ ) -> Result<ConnectionsSummary, Error> {+ let summary = self.repository.connections_summary(customer_id).await?;+ tracing::Span::current().record("users", summary.users);+ tracing::Span::current().record("connections", summary.connections);+ tracing::Span::current().record("outcome", "ok");+ Ok(summary)+ }+#[tracing::instrument(name = "connect.connections.delete", skip_all, fields(customer_id = %customer_id, app_id = %app_id, external_user_hash = %hash_user(user_id), outcome), err)]pub async fn delete(&self,diff --git a/connect/services/connect_api/src/main.rs b/connect/services/connect_api/src/main.rsindex ed6fb96ca8..158261a189 100644--- a/connect/services/connect_api/src/main.rs+++ b/connect/services/connect_api/src/main.rs@@ -16,8 +16,9 @@ use axum::{};use clap::{Parser, Subcommand};use connect_client::wire::{- CatalogEntry, ConnectSessionRequest, ConnectSessionResponse, Connection, ConnectionStatus,- DeleteResponse, ErrorResponse, McpErrorResponse, TokenResponse,+ AppConnectionsSummary, CatalogEntry, ConnectSessionRequest, ConnectSessionResponse, Connection,+ ConnectionStatus, ConnectionsPage, ConnectionsSummary, DeleteResponse, ErrorResponse,+ ListedConnection, ListedUser, McpErrorResponse, TokenResponse, UsersPage,};use connect_platform::{ConfigLoader, Telemetry, http_trace_layer, load_aws_config};use connect_registry::{Access, App, ClientRegistration, Status, all_apps};@@ -165,6 +166,9 @@ impl Modify for SecurityAddon {catalog,icon,list_connections,+ list_customer_connections,+ list_users,+ connections_summary,delete_connection,export_token,create_connect_session,@@ -173,7 +177,7 @@ impl Modify for SecurityAddon {oauth_callback,mcp::proxy),- components(schemas(CatalogEntry, Connection, ConnectionStatus, TokenResponse, DeleteResponse, ErrorResponse, McpErrorResponse, ConnectSessionRequest, ConnectSessionResponse)),+ components(schemas(CatalogEntry, Connection, ConnectionStatus, ListedConnection, ConnectionsPage, ListedUser, UsersPage, AppConnectionsSummary, ConnectionsSummary, TokenResponse, DeleteResponse, ErrorResponse, McpErrorResponse, ConnectSessionRequest, ConnectSessionResponse)),modifiers(&SecurityAddon))]struct ApiDoc;@@ -374,6 +378,128 @@ async fn list_connections(.map_err(api_error)}+#[derive(Deserialize)]+struct CustomerConnectionsQuery {+ limit: Option<u16>,+ cursor: Option<String>,+ app_id: Option<String>,+ status: Option<String>,+}++#[utoipa::path(get, path = "/v1/connections", params(("limit" = Option<u16>, Query, description = "Page size, default 100, maximum 500"), ("cursor" = Option<String>, Query, description = "Opaque next_cursor from the prior page"), ("app_id" = Option<String>, Query), ("status" = Option<String>, Query, description = "active or needs_reauth")), responses((status = 200, body = ConnectionsPage), (status = 400, body = ErrorResponse, description = "invalid_limit, invalid_cursor, invalid_app_id, or invalid_status"), (status = 401)), security(("customer_key" = [])))]+async fn list_customer_connections(+ State(state): State<AppState>,+ axum::extract::Extension(customer_id): axum::extract::Extension<uuid::Uuid>,+ Query(query): Query<CustomerConnectionsQuery>,+) -> Result<Json<ConnectionsPage>, (StatusCode, Json<ErrorResponse>)> {+ let page = state+ .service+ .list_customer_connections(+ customer_id,+ domain::ConnectionsFilter {+ limit: query.limit,+ cursor: query.cursor,+ app_id: query.app_id,+ status: query.status,+ },+ )+ .await+ .map_err(api_error)?;+ Ok(Json(ConnectionsPage {+ items: page+ .items+ .into_iter()+ .map(|item| ListedConnection {+ external_user_id: item.external_user_id,+ app_id: item.app_id,+ status: match item.status {+ DomainConnectionStatus::Active => ConnectionStatus::Active,+ DomainConnectionStatus::NeedsReauth => ConnectionStatus::NeedsReauth,+ },+ scopes: item.scopes,+ created_at: item.created_at,+ updated_at: item.updated_at,+ access_token_expires_at: item.access_token_expires_at,+ })+ .collect(),+ next_cursor: page.next_cursor,+ }))+}++#[utoipa::path(get, path = "/v1/users", params(("limit" = Option<u16>, Query, description = "Users per page, default 100, maximum 500"), ("cursor" = Option<String>, Query, description = "Opaque next_cursor from the prior page"), ("app_id" = Option<String>, Query), ("status" = Option<String>, Query, description = "active or needs_reauth")), responses((status = 200, body = UsersPage), (status = 400, body = ErrorResponse, description = "invalid_limit, invalid_cursor, invalid_app_id, or invalid_status"), (status = 401)), security(("customer_key" = [])))]+async fn list_users(+ State(state): State<AppState>,+ axum::extract::Extension(customer_id): axum::extract::Extension<uuid::Uuid>,+ Query(query): Query<CustomerConnectionsQuery>,+) -> Result<Json<UsersPage>, (StatusCode, Json<ErrorResponse>)> {+ let page = state+ .service+ .list_users(+ customer_id,+ domain::ConnectionsFilter {+ limit: query.limit,+ cursor: query.cursor,+ app_id: query.app_id,+ status: query.status,+ },+ )+ .await+ .map_err(api_error)?;+ Ok(Json(UsersPage {+ items: page+ .items+ .into_iter()+ .map(|user| ListedUser {+ external_user_id: user.external_user_id,+ first_connected_at: user.first_connected_at,+ connections: user+ .connections+ .into_iter()+ .map(|item| ListedConnection {+ external_user_id: item.external_user_id,+ app_id: item.app_id,+ status: match item.status {+ DomainConnectionStatus::Active => ConnectionStatus::Active,+ DomainConnectionStatus::NeedsReauth => ConnectionStatus::NeedsReauth,+ },+ scopes: item.scopes,+ created_at: item.created_at,+ updated_at: item.updated_at,+ access_token_expires_at: item.access_token_expires_at,+ })+ .collect(),+ })+ .collect(),+ next_cursor: page.next_cursor,+ }))+}++#[utoipa::path(get, path = "/v1/connections/summary", responses((status = 200, body = ConnectionsSummary), (status = 401)), security(("customer_key" = [])))]+async fn connections_summary(+ State(state): State<AppState>,+ axum::extract::Extension(customer_id): axum::extract::Extension<uuid::Uuid>,+) -> Result<Json<ConnectionsSummary>, (StatusCode, Json<ErrorResponse>)> {+ let summary = state+ .service+ .connections_summary(customer_id)+ .await+ .map_err(api_error)?;+ Ok(Json(ConnectionsSummary {+ users: summary.users,+ connections: summary.connections,+ needs_reauth: summary.needs_reauth,+ apps: summary+ .apps+ .into_iter()+ .map(|app| AppConnectionsSummary {+ app_id: app.app_id,+ active: app.active,+ needs_reauth: app.needs_reauth,+ })+ .collect(),+ }))+}+#[utoipa::path(delete, path = "/v1/users/{external_user_id}/connections/{app_id}", params(("external_user_id" = String, Path), ("app_id" = String, Path)), responses((status = 200, body = DeleteResponse, description = "Deleted locally; vendor grant is not revoked upstream"), (status = 401), (status = 404)), security(("customer_key" = [])))]async fn delete_connection(State(state): State<AppState>,@@ -414,6 +540,9 @@ async fn export_token(fn router(state: AppState) -> Router {let protected = Router::new().route("/v1/connect-sessions", post(create_connect_session))+ .route("/v1/connections", get(list_customer_connections))+ .route("/v1/users", get(list_users))+ .route("/v1/connections/summary", get(connections_summary)).route("/v1/users/{external_user_id}/connections",get(list_connections),diff --git a/connect/services/connect_api/src/outbound.rs b/connect/services/connect_api/src/outbound.rsindex 70e133ca7d..fe0a431cf0 100644--- a/connect/services/connect_api/src/outbound.rs+++ b/connect/services/connect_api/src/outbound.rs@@ -17,8 +17,9 @@ use zeroize::Zeroizing;#[cfg(test)]use crate::domain::StoredGrant;use crate::domain::{- Connection, ConnectionStatus, CustomerApiKey, Envelope, Error, Grant, GrantCipher, GrantData,- Repository,+ AppConnectionsSummary, Connection, ConnectionPosition, ConnectionStatus, ConnectionsSummary,+ CustomerApiKey, Envelope, Error, Grant, GrantCipher, GrantData, ListedConnection, ListedUser,+ Repository, UserPosition,};pub mod mcp;@@ -123,6 +124,45 @@ struct ConnectionRow {created_at: DateTime<Utc>,}+#[derive(sqlx::FromRow)]+struct ListedConnectionRow {+ id: Uuid,+ external_user_id: String,+ app_id: String,+ status: String,+ scopes: Vec<String>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ access_token_expires_at: Option<DateTime<Utc>>,+}++#[derive(sqlx::FromRow)]+struct ListedUserRow {+ first_connected_at: DateTime<Utc>,+ id: Uuid,+ external_user_id: String,+ app_id: String,+ status: String,+ scopes: Vec<String>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ access_token_expires_at: Option<DateTime<Utc>>,+}++#[derive(sqlx::FromRow)]+struct SummaryRow {+ users: i64,+ connections: i64,+ needs_reauth: i64,+}++#[derive(sqlx::FromRow)]+struct AppSummaryRow {+ app_id: String,+ active: i64,+ needs_reauth: i64,+}+#[cfg(test)]#[derive(sqlx::FromRow)]struct GrantRow {@@ -173,6 +213,151 @@ impl Repository for PostgresRepository {.collect()}+ #[tracing::instrument(name = "connect.db.list_customer_connections", skip_all, fields(customer_id = %customer_id, count), err)]+ async fn list_customer_connections(+ &self,+ customer_id: Uuid,+ limit: i64,+ position: Option<ConnectionPosition>,+ app_id: Option<&str>,+ status: Option<ConnectionStatus>,+ ) -> Result<Vec<ListedConnection>, Error> {+ let time = position.as_ref().map(|position| position.created_at);+ let id = position.as_ref().map(|position| position.id);+ let status = status.map(|status| status.to_string());+ let rows = sqlx::query_as::<_, ListedConnectionRow>(+ "SELECT c.id, c.external_user_id, c.app_id, c.status, c.scopes, c.created_at, c.updated_at, g.access_token_expires_at \+ FROM connections c LEFT JOIN grants g ON g.connection_id = c.id \+ WHERE c.customer_id = $1 AND ($2::timestamptz IS NULL OR (c.created_at, c.id) < ($2, $3)) \+ AND ($4::text IS NULL OR c.app_id = $4) AND ($5::text IS NULL OR c.status = $5) \+ ORDER BY c.created_at DESC, c.id DESC LIMIT $6"+ ).bind(customer_id).bind(time).bind(id).bind(app_id).bind(status).bind(limit)+ .fetch_all(&self.pool).await.map_err(storage)?;+ tracing::Span::current().record("count", rows.len());+ rows.into_iter()+ .map(|row| {+ Ok(ListedConnection {+ id: row.id,+ external_user_id: row.external_user_id,+ app_id: row.app_id,+ status: row.status.parse().map_err(|error| {+ Error::Storage(rootcause::Report::new(error).into_dynamic())+ })?,+ scopes: row.scopes,+ created_at: row.created_at,+ updated_at: row.updated_at,+ access_token_expires_at: row.access_token_expires_at,+ })+ })+ .collect()+ }++ #[tracing::instrument(name = "connect.db.list_users", skip_all, fields(customer_id = %customer_id, count), err)]+ async fn list_users(+ &self,+ customer_id: Uuid,+ limit: i64,+ position: Option<UserPosition>,+ app_id: Option<&str>,+ status: Option<ConnectionStatus>,+ ) -> Result<Vec<ListedUser>, Error> {+ let time = position+ .as_ref()+ .map(|position| position.first_connected_at);+ let user_id = position+ .as_ref()+ .map(|position| position.external_user_id.as_str());+ let status = status.map(|status| status.to_string());+ let rows = sqlx::query_as::<_, ListedUserRow>(+ "WITH matching AS ( \+ SELECT external_user_id, MIN(created_at) AS first_connected_at \+ FROM connections WHERE customer_id = $1 \+ GROUP BY external_user_id \+ HAVING BOOL_OR(($4::text IS NULL OR app_id = $4) AND ($5::text IS NULL OR status = $5)) \+ ), page AS ( \+ SELECT external_user_id, first_connected_at FROM matching \+ WHERE $2::timestamptz IS NULL OR (first_connected_at, external_user_id) < ($2, $3) \+ ORDER BY first_connected_at DESC, external_user_id DESC LIMIT $6 \+ ) \+ SELECT page.first_connected_at, c.id, c.external_user_id, c.app_id, c.status, c.scopes, \+ c.created_at, c.updated_at, g.access_token_expires_at \+ FROM page JOIN connections c ON c.customer_id = $1 AND c.external_user_id = page.external_user_id \+ LEFT JOIN grants g ON g.connection_id = c.id \+ ORDER BY page.first_connected_at DESC, page.external_user_id DESC, c.app_id"+ ).bind(customer_id).bind(time).bind(user_id).bind(app_id).bind(status).bind(limit)+ .fetch_all(&self.pool).await.map_err(storage)?;+ let mut users: Vec<ListedUser> = Vec::new();+ for row in rows {+ if users+ .last()+ .is_none_or(|user| user.external_user_id != row.external_user_id)+ {+ users.push(ListedUser {+ external_user_id: row.external_user_id.clone(),+ first_connected_at: row.first_connected_at,+ connections: Vec::new(),+ });+ }+ if let Some(user) = users.last_mut() {+ user.connections.push(ListedConnection {+ id: row.id,+ external_user_id: row.external_user_id,+ app_id: row.app_id,+ status: row.status.parse().map_err(|error| {+ Error::Storage(rootcause::Report::new(error).into_dynamic())+ })?,+ scopes: row.scopes,+ created_at: row.created_at,+ updated_at: row.updated_at,+ access_token_expires_at: row.access_token_expires_at,+ });+ }+ }+ tracing::Span::current().record("count", users.len());+ Ok(users)+ }++ #[tracing::instrument(name = "connect.db.connections_summary", skip_all, fields(customer_id = %customer_id), err)]+ async fn connections_summary(&self, customer_id: Uuid) -> Result<ConnectionsSummary, Error> {+ let row = sqlx::query_as::<_, SummaryRow>(+ "SELECT COUNT(DISTINCT external_user_id) AS users, COUNT(*) AS connections, \+ COUNT(*) FILTER (WHERE status = 'needs_reauth') AS needs_reauth \+ FROM connections WHERE customer_id = $1",+ )+ .bind(customer_id)+ .fetch_one(&self.pool)+ .await+ .map_err(storage)?;+ let apps = sqlx::query_as::<_, AppSummaryRow>(+ "SELECT app_id, COUNT(*) FILTER (WHERE status = 'active') AS active, \+ COUNT(*) FILTER (WHERE status = 'needs_reauth') AS needs_reauth \+ FROM connections WHERE customer_id = $1 GROUP BY app_id ORDER BY app_id",+ )+ .bind(customer_id)+ .fetch_all(&self.pool)+ .await+ .map_err(storage)?;+ let count = |value| {+ u64::try_from(value)+ .map_err(|error| Error::Storage(rootcause::Report::new(error).into_dynamic()))+ };+ Ok(ConnectionsSummary {+ users: count(row.users)?,+ connections: count(row.connections)?,+ needs_reauth: count(row.needs_reauth)?,+ apps: apps+ .into_iter()+ .map(|app| {+ Ok(AppConnectionsSummary {+ app_id: app.app_id,+ active: count(app.active)?,+ needs_reauth: count(app.needs_reauth)?,+ })+ })+ .collect::<Result<_, Error>>()?,+ })+ }+async fn delete(&self, customer_id: Uuid, user_id: &str, app_id: &str) -> Result<bool, Error> {let result = sqlx::query("DELETE FROM connections WHERE customer_id = $1 AND external_user_id = $2 AND app_id = $3").bind(customer_id).bind(user_id).bind(app_id).execute(&self.pool).await.map_err(storage)?;diff --git a/connect/services/connect_api/src/test.rs b/connect/services/connect_api/src/test.rsindex d89f53e604..88e84beccd 100644--- a/connect/services/connect_api/src/test.rs+++ b/connect/services/connect_api/src/test.rs@@ -216,6 +216,360 @@ async fn openapi_route_describes_catalog() {schema["paths"]["/v1/users/{external_user_id}/connections"]["get"]["security"][0]["customer_key"],serde_json::json!([]));+ for path in ["/v1/connections", "/v1/connections/summary", "/v1/users"] {+ assert_eq!(+ schema["paths"][path]["get"]["security"][0]["customer_key"],+ serde_json::json!([])+ );+ }+}++#[tokio::test]+#[expect(+ clippy::disallowed_methods,+ reason = "Connect database tests use runtime-checked SQLx queries"+)]+async fn customer_connection_listing_is_scoped_ordered_filtered_and_safe() {+ use crate::outbound::{EnvelopeCipher, LocalKeyWrapper, PostgresRepository};+ use base64::{Engine as _, engine::general_purpose::STANDARD};+ let database = TestDatabase::new().await;+ let repository = Arc::new(PostgresRepository::new(database.pool().clone()));+ let key = repository.create_customer("one").await.unwrap();+ let other_key = repository.create_customer("two").await.unwrap();+ let customer_id = repository.authenticate(&key).await.unwrap();+ let other_id = repository.authenticate(&other_key).await.unwrap();+ let cipher = Arc::new(EnvelopeCipher::new(Arc::new(+ LocalKeyWrapper::from_base64(&STANDARD.encode([9_u8; 32])).unwrap(),+ )));+ let envelope = domain::Envelope {+ ciphertext: b"private-ciphertext".to_vec(),+ nonce: vec![0; 12],+ encrypted_data_key: b"private-key".to_vec(),+ kms_key_id: "local".into(),+ encryption_version: 1,+ access_token_expires_at: Some(chrono::Utc::now() + chrono::Duration::hours(1)),+ };+ for (owner, user, app_id, status, time) in [+ (+ customer_id,+ "old-user",+ "notion",+ "active",+ "2026-10-29T09:00:00Z",+ ),+ (+ customer_id,+ "new-user",+ "linear",+ "needs_reauth",+ "2026-10-30T09:00:00Z",+ ),+ (+ customer_id,+ "new-user",+ "notion",+ "active",+ "2026-10-30T09:00:00Z",+ ),+ (+ other_id,+ "other-user",+ "notion",+ "active",+ "2026-10-31T09:00:00Z",+ ),+ ] {+ let id = uuid::Uuid::now_v7();+ repository+ .insert_connection(id, owner, user, app_id, &["read".into()], &envelope)+ .await+ .unwrap();+ sqlx::query(+ "UPDATE connections SET status = $1, created_at = $2::timestamptz WHERE id = $3",+ )+ .bind(status)+ .bind(time)+ .bind(id)+ .execute(database.pool())+ .await+ .unwrap();+ }+ let apps = all_apps().unwrap();+ let app = router(AppState {+ apps,+ service: Arc::new(Service::new(repository.clone())),+ oauth: Arc::new(domain::oauth::OAuthService::new(+ repository.clone(),+ cipher,+ Arc::new(outbound::oauth::VendorOAuth::new().unwrap()),+ apps,+ url::Url::parse("http://localhost:8080").unwrap(),+ HashMap::new(),+ )),+ mcp_http: outbound::mcp::VendorMcp::new().unwrap(),+ });+ let get = |path: String, key: &str| {+ Request::builder()+ .uri(path)+ .header(header::AUTHORIZATION, format!("Bearer {key}"))+ .body(Body::empty())+ .unwrap()+ };+ let response = app+ .clone()+ .oneshot(get("/v1/connections?limit=2".into(), &key))+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let body = response.into_body().collect().await.unwrap().to_bytes();+ let first: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(first["items"].as_array().unwrap().len(), 2);+ assert!(+ first["items"]+ .as_array()+ .unwrap()+ .iter()+ .all(|item| item["externalUserId"] == "new-user")+ );+ assert_eq!(first["items"][0]["appId"], "notion");+ assert!(first["items"][0]["accessTokenExpiresAt"].is_string());+ let json = first.to_string();+ for secret in [+ "ciphertext",+ "nonce",+ "encrypted",+ "private",+ "\"accessToken\"",+ "refreshToken",+ ] {+ assert!(!json.contains(secret), "leaked {secret}");+ }+ let cursor = first["nextCursor"].as_str().unwrap();+ let mut url = url::Url::parse("http://localhost/v1/connections").unwrap();+ url.query_pairs_mut()+ .append_pair("limit", "2")+ .append_pair("cursor", cursor);+ let second = app+ .clone()+ .oneshot(get(+ format!("{}?{}", url.path(), url.query().unwrap()),+ &key,+ ))+ .await+ .unwrap();+ let second: serde_json::Value =+ serde_json::from_slice(&second.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(second["items"][0]["externalUserId"], "old-user");+ assert!(second["nextCursor"].is_null());+ for (path, expected) in [+ ("/v1/connections?app_id=notion", 2),+ ("/v1/connections?status=needs_reauth", 1),+ ("/v1/connections?app_id=linear&status=active", 0),+ ] {+ let response = app.clone().oneshot(get(path.into(), &key)).await.unwrap();+ let body: serde_json::Value =+ serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())+ .unwrap();+ assert_eq!(body["items"].as_array().unwrap().len(), expected);+ }+ for path in [+ "/v1/connections?cursor=bad",+ "/v1/connections?status=bad",+ "/v1/connections?app_id=%3Cbad%3E",+ "/v1/connections?app_id=-bad",+ "/v1/connections?limit=501",+ "/v1/connections?limit=0",+ ] {+ assert_eq!(+ app.clone()+ .oneshot(get(path.into(), &key))+ .await+ .unwrap()+ .status(),+ StatusCode::BAD_REQUEST+ );+ }+ assert_eq!(+ app.clone()+ .oneshot(+ Request::builder()+ .uri("/v1/connections")+ .body(Body::empty())+ .unwrap()+ )+ .await+ .unwrap()+ .status(),+ StatusCode::UNAUTHORIZED+ );+ for (key, users, connections, needs_reauth) in [(&key, 2, 3, 1), (&other_key, 1, 1, 0)] {+ let response = app+ .clone()+ .oneshot(get("/v1/connections/summary".into(), key))+ .await+ .unwrap();+ let summary: serde_json::Value =+ serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())+ .unwrap();+ assert_eq!(summary["users"], users);+ assert_eq!(summary["connections"], connections);+ assert_eq!(summary["needsReauth"], needs_reauth);+ let response = app+ .clone()+ .oneshot(get("/v1/connections".into(), key))+ .await+ .unwrap();+ let page: serde_json::Value =+ serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())+ .unwrap();+ assert_eq!(page["items"].as_array().unwrap().len(), connections);+ }+ let response = app+ .clone()+ .oneshot(get("/v1/connections/summary".into(), &key))+ .await+ .unwrap();+ let summary: serde_json::Value =+ serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(summary["apps"].as_array().unwrap().len(), 2);+ assert_eq!(+ summary["apps"]+ .as_array()+ .unwrap()+ .iter()+ .find(|app| app["appId"] == "notion")+ .unwrap()["active"],+ 2+ );+ sqlx::query("UPDATE connections SET created_at = '2026-10-20T09:00:00Z' WHERE customer_id = $1 AND external_user_id = 'new-user' AND app_id = 'linear'")+ .bind(customer_id).execute(database.pool()).await.unwrap();+ let first = app+ .clone()+ .oneshot(get("/v1/users?limit=1".into(), &key))+ .await+ .unwrap();+ assert_eq!(first.status(), StatusCode::OK);+ let first: serde_json::Value =+ serde_json::from_slice(&first.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(first["items"].as_array().unwrap().len(), 1);+ assert_eq!(first["items"][0]["externalUserId"], "old-user");+ let cursor = first["nextCursor"].as_str().unwrap();+ let mut url = url::Url::parse("http://localhost/v1/users").unwrap();+ url.query_pairs_mut()+ .append_pair("limit", "1")+ .append_pair("cursor", cursor);+ let second = app+ .clone()+ .oneshot(get(+ format!("{}?{}", url.path(), url.query().unwrap()),+ &key,+ ))+ .await+ .unwrap();+ let second: serde_json::Value =+ serde_json::from_slice(&second.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(second["items"][0]["externalUserId"], "new-user");+ assert_eq!(+ second["items"][0]["connections"].as_array().unwrap().len(),+ 2+ );+ assert_eq!(second["items"][0]["connections"][0]["appId"], "linear");+ assert_eq!(second["items"][0]["connections"][1]["appId"], "notion");+ assert_eq!(+ second["items"][0]["firstConnectedAt"],+ "2026-10-20T09:00:00Z"+ );+ assert!(second["nextCursor"].is_null());+ for secret in [+ "ciphertext",+ "encrypted",+ "private",+ "refreshToken",+ "\"accessToken\"",+ ] {+ assert!(!second.to_string().contains(secret), "leaked {secret}");+ }+ let filtered = app+ .clone()+ .oneshot(get(+ "/v1/users?app_id=linear&status=needs_reauth".into(),+ &key,+ ))+ .await+ .unwrap();+ let filtered: serde_json::Value =+ serde_json::from_slice(&filtered.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(filtered["items"].as_array().unwrap().len(), 1);+ assert_eq!(+ filtered["items"][0]["connections"]+ .as_array()+ .unwrap()+ .len(),+ 2+ );+ for path in [+ "/v1/users?cursor=bad",+ "/v1/users?limit=0",+ "/v1/users?limit=501",+ "/v1/users?status=bad",+ "/v1/users?app_id=-bad",+ ] {+ assert_eq!(+ app.clone()+ .oneshot(get(path.into(), &key))+ .await+ .unwrap()+ .status(),+ StatusCode::BAD_REQUEST+ );+ }+ let other = app+ .clone()+ .oneshot(get("/v1/users".into(), &other_key))+ .await+ .unwrap();+ let other: serde_json::Value =+ serde_json::from_slice(&other.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(other["items"].as_array().unwrap().len(), 1);+ assert_eq!(other["items"][0]["externalUserId"], "other-user");+ sqlx::query("INSERT INTO connections (id, customer_id, external_user_id, app_id, status, scopes, created_at) VALUES ($1, $2, 'z-user', 'linear', 'active', ARRAY[]::text[], '2026-10-29T09:00:00Z')")+ .bind(uuid::Uuid::now_v7()).bind(customer_id).execute(database.pool()).await.unwrap();+ let tied = app+ .clone()+ .oneshot(get("/v1/users?limit=1".into(), &key))+ .await+ .unwrap();+ let tied: serde_json::Value =+ serde_json::from_slice(&tied.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(tied["items"][0]["externalUserId"], "z-user");+ let mut tie_url = url::Url::parse("http://localhost/v1/users").unwrap();+ tie_url+ .query_pairs_mut()+ .append_pair("limit", "1")+ .append_pair("cursor", tied["nextCursor"].as_str().unwrap());+ let after_tie = app+ .clone()+ .oneshot(get(+ format!("{}?{}", tie_url.path(), tie_url.query().unwrap()),+ &key,+ ))+ .await+ .unwrap();+ let after_tie: serde_json::Value =+ serde_json::from_slice(&after_tie.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert_eq!(after_tie["items"][0]["externalUserId"], "old-user");+ assert_eq!(+ app.oneshot(+ Request::builder()+ .uri("/v1/users")+ .body(Body::empty())+ .unwrap()+ )+ .await+ .unwrap()+ .status(),+ StatusCode::UNAUTHORIZED+ );}#[tokio::test]diff --git a/connect/services/connect_demo/AGENTS.md b/connect/services/connect_demo/AGENTS.mdindex e47ce29337..372694b33f 100644--- a/connect/services/connect_demo/AGENTS.md+++ b/connect/services/connect_demo/AGENTS.md@@ -2,7 +2,7 @@## What it is-A standalone customer app for exercising Connect's catalog, OAuth flow, and MCP gateway from one page.+A standalone customer app for exercising Connect's catalog, OAuth flow, MCP gateway, and customer dashboard.## Start here@@ -20,6 +20,10 @@ A standalone customer app for exercising Connect's catalog, OAuth flow, and MCP- Connect access goes through `connect_client`; the demo never exports vendor tokens.- The configured public URL ends in `/demo` and is the OAuth redirect target base.+- `/demo/dashboard` uses the public client to show customer summary counts,+ catalog app totals, and up to 500 complete users per page.+ App and status filters are server-rendered query parameters; `cursor` moves+ to the next user page.## Checksdiff --git a/connect/services/connect_demo/Cargo.toml b/connect/services/connect_demo/Cargo.tomlindex 6fe521df05..34bbdebe26 100644--- a/connect/services/connect_demo/Cargo.toml+++ b/connect/services/connect_demo/Cargo.toml@@ -6,6 +6,7 @@ publish = false[dependencies]axum = { workspace = true }+chrono = { workspace = true }connect_client = { path = "../../crates/connect_client" }connect_platform = { path = "../../crates/connect_platform" }futures = { workspace = true }diff --git a/connect/services/connect_demo/src/main.rs b/connect/services/connect_demo/src/main.rsindex 01cc329452..df66b2c56b 100644--- a/connect/services/connect_demo/src/main.rs+++ b/connect/services/connect_demo/src/main.rs@@ -14,7 +14,10 @@ use axum::{response::{Html, IntoResponse, Redirect, Response},routing::{get, post},};-use connect_client::{ConnectClient, wire::ConnectionStatus};+use connect_client::{+ ConnectClient,+ wire::{ConnectionStatus, UsersQuery},+};use connect_platform::{ConfigLoader, Telemetry, http_trace_layer};use serde::Deserialize;use serde_json::Value;@@ -35,7 +38,7 @@ struct DemoUser(String);fn page(title: &str, content: &str) -> Html<String> {Html(format!(- "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>{}</title><style>{}</style></head><body><h1>Macro Connect demo</h1>{content}<script>{}</script></body></html>",+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>{}</title><style>{}</style></head><body><h1>Macro Connect demo</h1><nav><a href=\"/demo\">Catalog</a><a href=\"/demo/dashboard\">Dashboard</a></nav>{content}<script>{}</script></body></html>",escape(title),include_str!("style.css"),include_str!("app.js")@@ -143,6 +146,166 @@ async fn catalog(State(state): State<AppState>, Extension(user): Extension<DemoUpage("Catalog", &content).into_response()}+#[derive(Default, Deserialize)]+struct DashboardQuery {+ app_id: Option<String>,+ status: Option<String>,+ cursor: Option<String>,+}++fn dashboard_url(query: &DashboardQuery, cursor: Option<&str>) -> String {+ let mut pairs = url::form_urlencoded::Serializer::new(String::new());+ let mut has_query = false;+ if let Some(app_id) = &query.app_id {+ pairs.append_pair("app_id", app_id);+ has_query = true;+ }+ if let Some(status) = &query.status {+ pairs.append_pair("status", status);+ has_query = true;+ }+ if let Some(cursor) = cursor {+ pairs.append_pair("cursor", cursor);+ has_query = true;+ }+ let encoded = pairs.finish();+ if has_query {+ format!("/demo/dashboard?{encoded}")+ } else {+ "/demo/dashboard".to_owned()+ }+}++#[tracing::instrument(name = "demo.dashboard", skip_all, fields(count, outcome))]+async fn dashboard(+ State(state): State<AppState>,+ Extension(user): Extension<DemoUser>,+ Query(query): Query<DashboardQuery>,+) -> Response {+ let status = match query.status.as_deref() {+ None | Some("") => None,+ Some("active") => Some(ConnectionStatus::Active),+ Some("needs_reauth") => Some(ConnectionStatus::NeedsReauth),+ _ => {+ return (+ StatusCode::BAD_REQUEST,+ page("Dashboard", "<p class=\"error\">Invalid status filter.</p>"),+ )+ .into_response();+ }+ };+ let (apps, summary, users) = match tokio::try_join!(+ state.client.catalog(),+ state.client.connections_summary(),+ state.client.list_users(UsersQuery {+ limit: Some(500),+ cursor: query.cursor.clone(),+ app_id: query.app_id.clone().filter(|value| !value.is_empty()),+ status,+ })+ ) {+ Ok(value) => value,+ Err(error) => {+ Span::current().record("outcome", "error");+ return error_page(error);+ }+ };+ Span::current().record("count", users.items.len());+ Span::current().record("outcome", "ok");+ let mut content = format!(+ "<h2>Dashboard</h2><div class=\"tiles\"><section class=\"card\"><strong>{}</strong><span>Users</span></section><section class=\"card\"><strong>{}</strong><span>Connections</span></section><section class=\"card\"><strong>{}</strong><span>Needs re-auth</span></section></div>",+ summary.users, summary.connections, summary.needs_reauth+ );+ content.push_str("<h2>Apps</h2><table><thead><tr><th>App</th><th>Active</th><th>Needs re-auth</th></tr></thead><tbody>");+ for app in &apps {+ let counts = summary.apps.iter().find(|counts| counts.app_id == app.id);+ let active = counts.map_or(0, |counts| counts.active);+ let needs_reauth = counts.map_or(0, |counts| counts.needs_reauth);+ let icon = if app.icon_url.is_some() {+ format!(+ "<img class=\"app-icon\" alt=\"\" src=\"/demo/icons/{}\">",+ path_id(&app.id)+ )+ } else {+ String::new()+ };+ content.push_str(&format!("<tr><td data-label=\"App\">{icon}{}</td><td data-label=\"Active\">{active}</td><td data-label=\"Needs re-auth\">{needs_reauth}</td></tr>", escape(&app.name)));+ }+ content.push_str("</tbody></table><h2>Users</h2><form method=\"get\" action=\"/demo/dashboard\" class=\"filters\"><label>App<select name=\"app_id\"><option value=\"\">All apps</option>");+ for app in &apps {+ content.push_str(&format!(+ "<option value=\"{}\"{}>{}</option>",+ escape(&app.id),+ if query.app_id.as_deref() == Some(&app.id) {+ " selected"+ } else {+ ""+ },+ escape(&app.name)+ ));+ }+ content.push_str("</select></label><label>Status<select name=\"status\"><option value=\"\">All statuses</option>");+ for (value, label) in [("active", "Active"), ("needs_reauth", "Needs re-auth")] {+ content.push_str(&format!(+ "<option value=\"{value}\"{}>{label}</option>",+ if query.status.as_deref() == Some(value) {+ " selected"+ } else {+ ""+ }+ ));+ }+ content.push_str("</select></label><button>Filter</button></form>");+ if users.items.is_empty() {+ content.push_str("<p>No connected users match these filters.</p>");+ } else {+ content.push_str("<table><thead><tr><th>User</th><th>Apps</th><th>First connected</th><th>Next token expiry</th></tr></thead><tbody>");+ let now = chrono::Utc::now();+ for listed_user in &users.items {+ let id = &listed_user.external_user_id;+ let connections = &listed_user.connections;+ let short: String = id.chars().take(12).collect();+ let marker = if id == &user.0 {+ " <span class=\"badge\">you</span>"+ } else {+ ""+ };+ let expiry = connections+ .iter()+ .filter_map(|connection| connection.access_token_expires_at)+ .filter(|expiry| *expiry > now)+ .min();+ let badges = connections+ .iter()+ .map(|connection| {+ format!(+ "<span class=\"status-badge\">{}: {}</span>",+ escape(+ apps.iter()+ .find(|app| app.id == connection.app_id)+ .map_or(connection.app_id.as_str(), |app| app.name.as_str())+ ),+ match connection.status {+ ConnectionStatus::Active => "active",+ ConnectionStatus::NeedsReauth => "needs re-auth",+ }+ )+ })+ .collect::<Vec<_>>()+ .join(" ");+ content.push_str(&format!("<tr><td data-label=\"User\"><span title=\"{}\">{}</span>{marker}</td><td data-label=\"Apps\">{badges}</td><td data-label=\"First connected\">{}</td><td data-label=\"Next token expiry\">{}</td></tr>", escape(id), escape(&short), listed_user.first_connected_at.format("%Y-%m-%d"), expiry.map_or_else(|| "—".to_owned(), |time| time.format("%Y-%m-%d %H:%M UTC").to_string())));+ }+ content.push_str("</tbody></table>");+ }+ if let Some(cursor) = users.next_cursor.as_deref() {+ content.push_str(&format!(+ "<p><a href=\"{}\">More users</a></p>",+ escape(&dashboard_url(&query, Some(cursor)))+ ));+ }+ page("Dashboard", &content).into_response()+}+async fn icon(State(state): State<AppState>, Path(app_id): Path<String>) -> Response {match state.client.catalog_icon(&app_id).await {Ok(bytes) => (@@ -317,6 +480,7 @@ fn expand_text_json(mut value: Value) -> Value {fn router(state: AppState) -> Router {let browser = Router::new().route("/demo", get(catalog))+ .route("/demo/dashboard", get(dashboard)).route("/demo/icons/{app_id}", get(icon)).route("/demo/connect/{app_id}", post(connect)).route("/demo/connected", get(connected))diff --git a/connect/services/connect_demo/src/style.css b/connect/services/connect_demo/src/style.cssindex 0b9d3c090e..373193092a 100644--- a/connect/services/connect_demo/src/style.css+++ b/connect/services/connect_demo/src/style.css@@ -1,6 +1,8 @@:root { color-scheme: light; font-family: system-ui, sans-serif; background: #f7f7f6; color: #242424; }body { max-width: 980px; margin: 2rem auto; padding: 0 1rem; }h1 { font-size: 2rem; margin-bottom: .3rem; }+nav { display: flex; gap: 1rem; margin: .5rem 0 1.5rem; }+nav a { color: inherit; }p { line-height: 1.45; }.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 1rem; }.card, .panel { background: white; border: 1px solid #dededb; border-radius: 12px; padding: 1rem; }@@ -14,3 +16,25 @@ pre { overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; padding: 1.error { color: #a22; }#workspace { margin-top: 1.5rem; }#workspace .panel { margin: .75rem 0; }+.tiles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem; }+.tiles .card { display: flex; flex-direction: column; gap: .3rem; }+.tiles strong { font-size: 1.8rem; }+.tiles span { color: #555; }+table { width: 100%; border-collapse: collapse; background: white; margin-bottom: 1.5rem; }+th, td { padding: .7rem; border-bottom: 1px solid #dededb; text-align: left; vertical-align: top; }+.app-icon { width: 24px; height: 24px; vertical-align: middle; margin-right: .5rem; }+.filters { display: flex; flex-wrap: wrap; align-items: end; gap: .7rem; margin-bottom: 1rem; }+.filters label { display: flex; flex-direction: column; gap: .25rem; }+.filters select { padding: .4rem; font: inherit; max-width: 100%; }+.status-badge { display: inline-block; margin: .1rem; padding: .2rem .4rem; border-radius: 5px; background: #f1f1ef; font-size: .8rem; }+@media (max-width: 600px) {+ body { margin: 1rem auto; }+ .tiles { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .35rem; }+ .tiles .card { padding: .6rem; }+ .tiles strong { font-size: 1.3rem; }+ table, tbody, tr, td { display: block; }+ thead { display: none; }+ tr { border: 1px solid #dededb; border-radius: 8px; margin: .5rem 0; padding: .35rem; background: white; }+ td { display: flex; gap: .5rem; justify-content: space-between; overflow-wrap: anywhere; border: 0; padding: .3rem; }+ td::before { content: attr(data-label); color: #555; flex: 0 0 35%; }+}diff --git a/connect/services/connect_demo/src/test.rs b/connect/services/connect_demo/src/test.rsindex 82e6924e97..43dbade0ad 100644--- a/connect/services/connect_demo/src/test.rs+++ b/connect/services/connect_demo/src/test.rs@@ -5,7 +5,7 @@ use serde_json::json;use tower::ServiceExt as _;use wiremock::{Mock, MockServer, ResponseTemplate,- matchers::{method, path, path_regex},+ matchers::{method, path, path_regex, query_param},};fn state(server: &MockServer) -> AppState {@@ -16,6 +16,81 @@ fn state(server: &MockServer) -> AppState {}}+#[tokio::test]+async fn dashboard_renders_counts_users_filters_and_empty_state() {+ let server = MockServer::start().await;+ Mock::given(method("GET")).and(path("/v1/catalog"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!([+ {"id":"notion","name":"<Notes>","description":"Notes","access":["mcp"],"mcp_url":"https://vendor.test/mcp","icon_url":"/v1/catalog/notion/icon.svg"},+ {"id":"linear","name":"Linear","description":"Tasks","access":["mcp"],"mcp_url":"https://vendor.test/mcp","icon_url":null}+ ]))).mount(&server).await;+ Mock::given(method("GET")).and(path("/v1/connections/summary"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"users":2,"connections":2,"needsReauth":1,"apps":[{"appId":"notion","active":1,"needsReauth":1}]})))+ .mount(&server).await;+ Mock::given(method("GET"))+ .and(path("/v1/users"))+ .and(query_param("app_id", "linear"))+ .and(query_param("status", "active"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(json!({"items":[],"nextCursor":null})),+ )+ .with_priority(1)+ .mount(&server)+ .await;+ Mock::given(method("GET")).and(path("/v1/users"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"items":[+ {"externalUserId":"123e4567-e89b-42d3-a456-426614174000","firstConnectedAt":"2026-10-30T09:00:00Z","connections":[+ {"externalUserId":"123e4567-e89b-42d3-a456-426614174000","appId":"linear","status":"needs_reauth","scopes":[],"createdAt":"2026-10-31T09:00:00Z","updatedAt":"2026-10-31T09:00:00Z","accessTokenExpiresAt":null},+ {"externalUserId":"123e4567-e89b-42d3-a456-426614174000","appId":"notion","status":"active","scopes":[],"createdAt":"2026-10-30T09:00:00Z","updatedAt":"2026-10-30T09:00:00Z","accessTokenExpiresAt":"2099-10-30T10:00:00Z"}+ ]},+ {"externalUserId":"<bad-user>","firstConnectedAt":"2026-10-29T09:00:00Z","connections":[+ {"externalUserId":"<bad-user>","appId":"notion","status":"needs_reauth","scopes":[],"createdAt":"2026-10-29T09:00:00Z","updatedAt":"2026-10-29T09:00:00Z","accessTokenExpiresAt":null}+ ]}+ ],"nextCursor":"next+page"}))).mount(&server).await;+ let app = router(state(&server));+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .uri("/demo/dashboard")+ .header(+ header::COOKIE,+ "connect_demo_user=123e4567-e89b-42d3-a456-426614174000",+ )+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let html = body(response).await;+ assert!(html.contains("<strong>2</strong><span>Users</span>"));+ assert!(html.contains("<strong>2</strong><span>Connections</span>"));+ assert!(html.contains("<strong>1</strong><span>Needs re-auth</span>"));+ assert!(html.contains("<span class=\"badge\">you</span>"));+ assert!(html.contains("<Notes>"));+ assert!(html.contains("title=\"<bad-user>\""));+ assert!(!html.contains("title=\"<bad-user>\""));+ assert!(html.contains("/demo/icons/notion"));+ assert!(html.contains("More users"));+ assert!(html.contains("Linear: needs re-auth"));+ assert!(html.contains("cursor=next%2Bpage"));+ assert!(html.contains("data-label=\"Active\">0</td>"));+ let response = app+ .oneshot(+ Request::builder()+ .uri("/demo/dashboard?app_id=linear&status=active")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let html = body(response).await;+ assert!(html.contains("No connected users match these filters."));+ assert!(html.contains("value=\"linear\" selected"));+ assert!(html.contains("value=\"active\" selected"));+}+async fn body(response: Response) -> String {let bytes = response.into_body().collect().await.unwrap().to_bytes();String::from_utf8(bytes.to_vec()).unwrap()diff --git a/connect/tasks/T020-users-dashboard.md b/connect/tasks/T020-users-dashboard.mdnew file mode 100644index 0000000000..4111d51617--- /dev/null+++ b/connect/tasks/T020-users-dashboard.md@@ -0,0 +1,180 @@+# T020: List a customer's users and connections, and a dashboard++Base: `eric/macro-connect-demo` (PR #9269). Branch for review:+`eric/macro-connect-dashboard`.++## Goal++A customer can see every user who has connected anything, and what each one+connected, without knowing user ids in advance: one paginated API listing and+one summary, exposed in `connect_client`, and a dashboard at+`https://connect-dev.macro.com/demo/dashboard` built on them. Everything is+scoped to the calling customer; no customer ever sees another's users.++## Context++- `connect/services/connect_api` (`list_connections`, `ConnectService::list`,+ `Repository`, `outbound.rs`, migrations, OpenAPI), `connect/crates/connect_client`+ (`wire.rs`, methods, tests), `connect/services/connect_demo` (page+ rendering, styles, tests).+- Today `GET /v1/users/{external_user_id}/connections` needs the user id.+- The dev stack is deployed by the planner; do not run `pulumi` against AWS.++## Do++1. **API** (hexagonal: handler maps wire types; customer scoping and limits+ live in the domain service; SQL in the outbound adapter):+ - `GET /v1/connections?limit=&cursor=&app_id=&status=`: the customer's+ connections, newest first (`created_at DESC, id DESC`), keyset-paginated+ with an opaque `next_cursor` (null on the last page). `limit` defaults to+ 100, max 500; a bad cursor or filter is a documented 400. Each item:+ `external_user_id`, `app_id`, `status`, `scopes`, `created_at`,+ `updated_at`, `access_token_expires_at` (from `grants`, nullable). Never+ any grant material.+ - `GET /v1/connections/summary`: `users` (distinct external user ids),+ `connections`, `needs_reauth`, and `apps`: per app id `active` and+ `needs_reauth` counts.+ - Migration: index `connections (customer_id, created_at DESC, id DESC)`.+ - Both routes behind customer auth, in OpenAPI, spanned per the+ observability rule (customer id, counts; no user ids in span names).+2. **`connect_client`**: `list_connections(ConnectionsQuery) -> ConnectionsPage`+ and `connections_summary() -> ConnectionsSummary`, wire types shared with+ the API as today, plus a convenience stream or loop helper for all pages.+3. **Dashboard** in `connect_demo` at `GET /demo/dashboard`, linked from the+ `/demo` header (and `/demo` linked back):+ - Tiles: users, connections, needs re-auth.+ - Per-app table: icon, name, active, needs re-auth (every catalog app,+ zeros included).+ - Users table, one row per user: user id (shortened, full in `title`), a+ "you" marker for this browser's cookie user, each app as a status badge,+ first connected, earliest upcoming token expiry. Filters by app and+ status (query parameters, server-rendered). Up to 500 users with a+ "more" link that follows `next_cursor`.+ - Server-rendered, escaped, readable at 390 px (tables become stacked+ rows). Same styling as `/demo`.+4. **Tests**: API tests on `template0` databases covering customer isolation+ (two customers, neither sees the other), ordering and pagination across+ pages, filters, bad cursor, summary counts, and no grant fields in the+ JSON. Client tests for both methods. Demo handler tests for the dashboard+ (counts, "you" marker, escaping, filters, empty state).+5. **Integration**: a `connections_listing` scenario in+ `connect/tests/connect_integration` (fresh user appears with zero+ connections nowhere; summary responds; pagination params accepted).+6. **Docs**: API and demo `AGENTS.md`, `connect_client` `AGENTS.md`,+ `connect/docs/plan.md` if it lists the API surface.++## Done when++- `cargo nextest run --all-features -p connect_api -p connect_client -p connect_demo`,+ clippy (`-D warnings`) for those plus `connect_integration`,+ `cargo x deps --check`, `just check` pass.+- Compose run: after creating a customer and seeding two connections directly+ in the local database (document the SQL you used), `/demo/dashboard` shows+ them; paste the tile values.+- Nothing outside `connect/` changes except generated Cargo artifacts.++## Out of scope++Cross-customer operator views; user names or emails (Connect only knows+opaque ids); deploying; real vendor consent.++## Result++### Changed++- API: `connect/services/connect_api/src/{domain.rs,main.rs,outbound.rs,test.rs}`,+ `migrations/20261031170401_list_customer_connections.sql`, and `AGENTS.md`.+ Added customer-scoped connection, summary, and user routes. The user route+ pages by `MIN(created_at), external_user_id`, then returns every connection+ for each selected user in one SQL query. Filters select users with a matching+ connection without trimming their returned connections. Added OpenAPI,+ spans, a concurrent connection index, and template0 database tests.+- Client: `connect/crates/connect_client/src/{lib.rs,wire.rs,test.rs}` and+ `AGENTS.md`. Added shared wire types, `list_connections`,+ `connections_summary`, `list_users`, and all-pages helpers with HTTP tests.+- Demo: `connect/services/connect_demo/{Cargo.toml,AGENTS.md}` and+ `src/{main.rs,style.css,test.rs}`. Added the dashboard, complete user rows+ from `/v1/users`, filters, pagination, responsive styles, and handler tests.+- Integration: `connect/tests/connect_integration/src/main.rs` and `AGENTS.md`.+ Extended `connections_listing` to exercise both customer listing routes.+- Docs and generated artifacts: `connect/docs/plan.md`, this Result, and+ `Cargo.lock`. No other files outside `connect/` changed.++### Checks++| Check | Exact outcome |+| --- | --- |+| `cargo nextest run --all-features -p connect_api -p connect_client -p connect_demo` | Passed: 36 tests, 0 skipped. |+| `cargo clippy -p connect_api -p connect_client -p connect_demo -p connect_integration --all-features --all-targets -- -D warnings` | Passed with no warnings. |+| `cargo x deps --check` | Passed. |+| `just hakari` | Passed; generated dependency artifacts remained in sync. |+| `just check` | Passed, including format, ast-grep, PII scan, and scanner tests. |+| Local integration runner in a fresh Compose project | Passed: health, catalog, auth, empty connections, `connections_listing` including `/v1/users`, client metadata, session rules, four authorize checks, and unconnected gateway. `integration.sh local` first hit occupied port 8080, then an old migration checksum in its existing volume; the fresh project ran the same runner successfully. |+| Isolated Compose dashboard smoke test | Passed. One user with two directly seeded connections appeared in one row with both app badges. Tiles: `users=1`, `connections=2`, `needs_reauth=1`. Containers were stopped without removing the volume. |+| `git diff --check` | Passed. |+| SQLx query review | Passed: both listings have customer predicates, stable keyset orders, limits, bound filters, and select only expiry metadata from grants. The user route uses one SQL query per page. Summary queries are customer-scoped. `just prepare_db` was skipped because Connect uses runtime-checked queries by its settled decision in `connect/docs/decisions.md`. |+| Browser and Tempo trace checks | Not run: no browser tool or binary was available, and the isolated Compose stack did not configure an OTLP exporter. The HTTP dashboard response and integration routes were exercised locally. |+| Repository audit | Passed: the auditor found no remaining code or documentation issue. |++The smoke test created a local customer using `create-customer` and selected its+ID through its temporary key ID. The direct seed SQL was:++```sql+INSERT INTO connections (id, customer_id, external_user_id, app_id, status, scopes, created_at)+SELECT '019a0000-0000-7000-8000-000000000001'::uuid, customer_id, 'dashboard-user', 'notion',+ 'active', ARRAY[]::text[], '2026-10-20T09:00:00Z'::timestamptz+FROM customer_api_keys WHERE id = :'key_id'::uuid+ON CONFLICT (id) DO NOTHING;+INSERT INTO connections (id, customer_id, external_user_id, app_id, status, scopes, created_at)+SELECT '019a0000-0000-7000-8000-000000000002'::uuid, customer_id, 'dashboard-user', 'linear',+ 'needs_reauth', ARRAY[]::text[], '2026-10-30T09:00:00Z'::timestamptz+FROM customer_api_keys WHERE id = :'key_id'::uuid+ON CONFLICT (id) DO NOTHING;+```++### Open questions++None.++### Proposed commits++1. `feat(connect): list customer connections and summary counts`++ Why: Customers need to discover connections without knowing user IDs.++ What: Add scoped paginated connection and complete user routes, summary,+ client contracts, index, integration scenario, tests, and API documentation.++2. `feat(connect-demo): add customer dashboard`++ Why: The demo needs a view of customer connection activity.++ What: Render summary tiles, per-app counts, complete paginated user rows,+ filters, responsive styles, and handler tests.++## Review (planner)++Good work; the pagination question was the right catch. Decision: add a+user-keyed listing and build the dashboard on it. Keep `/v1/connections` and+the summary as they are.++1. **`GET /v1/users?limit=&cursor=&app_id=&status=`**: the customer's users,+ one item per `external_user_id`: `external_user_id`, `first_connected_at`+ (min `created_at`), and `connections` (every connection of that user, same+ fields as `/v1/connections` items, ordered by `app_id`). Ordered by+ `first_connected_at DESC, external_user_id DESC`, keyset-paginated with an+ opaque cursor; `limit` counts users (default 100, max 500). `app_id` and+ `status` select users having at least one matching connection, and those+ users still return all their connections. Same layering, OpenAPI, spans,+ and errors as the other routes; one query per page (aggregate in SQL,+ e.g. `json_agg` or two bounded queries), not N+1.+2. **Client**: `list_users(UsersQuery) -> UsersPage` plus an all-pages helper.+3. **Dashboard**: user rows come from `/v1/users`, so each row is complete;+ "more" follows its cursor. Remove the grouping-of-connection-pages logic.+4. **Tests**: users never split across pages (a user with connections created+ far apart in time stays whole), ordering, filters keep all of a matching+ user's connections, customer isolation, bad cursor. Extend+ `connections_listing` (or add `users_listing`) in the integration runner.++Then finish and replace the Result with final outcomes, including the Compose+smoke with a user who has two connections.diff --git a/connect/tests/connect_integration/AGENTS.md b/connect/tests/connect_integration/AGENTS.mdindex 353b7fff9e..8a023b9832 100644--- a/connect/tests/connect_integration/AGENTS.md+++ b/connect/tests/connect_integration/AGENTS.md@@ -7,6 +7,8 @@ An opt-in binary that checks a running Connect service through the public Rust c## Start here- `src/main.rs`: scenarios and PASS/FAIL reporting.+- `connections_listing` checks summary, connection listing, and user listing+ parameters for a fresh user.- `../../tooling/integration.sh`: local Compose and dev entry points.## Scopediff --git a/connect/tests/connect_integration/src/main.rs b/connect/tests/connect_integration/src/main.rsindex 05c4db2ca7..1988a3fda8 100644--- a/connect/tests/connect_integration/src/main.rs+++ b/connect/tests/connect_integration/src/main.rs@@ -208,6 +208,96 @@ async fn main() -> ExitCode {.await,);+ record(+ &mut failures,+ "connections_listing",+ async {+ let _summary = client+ .connections_summary()+ .await+ .map_err(|e| e.to_string())?;+ let all = client+ .all_connections(connect_client::wire::ConnectionsQuery {+ limit: Some(500),+ cursor: None,+ app_id: None,+ status: None,+ })+ .await+ .map_err(|e| e.to_string())?;+ if all.iter().any(|item| item.external_user_id == user_id) {+ return Err("fresh user appeared in customer connections".into());+ }+ let first = client+ .list_connections(connect_client::wire::ConnectionsQuery {+ limit: Some(1),+ cursor: None,+ app_id: None,+ status: None,+ })+ .await+ .map_err(|e| e.to_string())?;+ let filtered = client+ .list_connections(connect_client::wire::ConnectionsQuery {+ limit: Some(1),+ cursor: first.next_cursor,+ app_id: Some("notion".into()),+ status: Some(connect_client::wire::ConnectionStatus::Active),+ })+ .await+ .map_err(|e| e.to_string())?;+ if filtered+ .items+ .iter()+ .any(|item| item.external_user_id == user_id)+ {+ return Err("fresh user appeared in filtered connections".into());+ }+ let all_users = client+ .all_users(connect_client::wire::UsersQuery {+ limit: Some(500),+ cursor: None,+ app_id: None,+ status: None,+ })+ .await+ .map_err(|e| e.to_string())?;+ if all_users+ .iter()+ .any(|item| item.external_user_id == user_id)+ {+ return Err("fresh user appeared in customer users".into());+ }+ let first_users = client+ .list_users(connect_client::wire::UsersQuery {+ limit: Some(1),+ cursor: None,+ app_id: None,+ status: None,+ })+ .await+ .map_err(|e| e.to_string())?;+ let filtered_users = client+ .list_users(connect_client::wire::UsersQuery {+ limit: Some(1),+ cursor: first_users.next_cursor,+ app_id: Some("notion".into()),+ status: Some(connect_client::wire::ConnectionStatus::Active),+ })+ .await+ .map_err(|e| e.to_string())?;+ if filtered_users+ .items+ .iter()+ .any(|item| item.external_user_id == user_id)+ {+ return Err("fresh user appeared in filtered users".into());+ }+ Ok(())+ }+ .await,+ );+record(&mut failures,"client_metadata",