use super::*; impl PostgresRegistry { pub async fn list_platform_api_keys_for_agent( &self, workspace_id: &WorkspaceId, agent_id: &AgentId, ) -> Result, RegistryError> { let rows = sqlx::query( "select id, workspace_id, agent_id, key_kind, name, prefix, scopes_json, status, created_at, last_used_at, expires_at, allowed_origins_json from platform_api_keys where workspace_id = $1 and agent_id = $2 order by created_at desc", ) .bind(workspace_id.as_str()) .bind(agent_id.as_str()) .fetch_all(&self.pool) .await?; rows.into_iter() .map(|row| { Ok(PlatformApiKeyRecord { api_key: PlatformApiKey { id: PlatformApiKeyId::new(row.get::("id")), workspace_id: WorkspaceId::new(row.get::("workspace_id")), agent_id: row.get::, _>("agent_id").map(AgentId::new), key_kind: deserialize_enum_text( &row.get::("key_kind"), "key_kind", )?, name: row.get("name"), prefix: row.get("prefix"), scopes: deserialize_json_value(row.get::("scopes_json"))?, status: deserialize_enum_text(&row.get::("status"), "status")?, created_at: row.get("created_at"), last_used_at: row.get("last_used_at"), expires_at: row.get("expires_at"), allowed_origins: deserialize_json_value( row.get::("allowed_origins_json"), )?, }, }) }) .collect() } pub async fn list_platform_api_keys( &self, workspace_id: &WorkspaceId, ) -> Result, RegistryError> { let rows = sqlx::query( "select id, workspace_id, agent_id, key_kind, name, prefix, scopes_json, status, created_at, last_used_at, expires_at, allowed_origins_json from platform_api_keys where workspace_id = $1 order by created_at desc", ) .bind(workspace_id.as_str()) .fetch_all(&self.pool) .await?; rows.into_iter() .map(|row| { Ok(PlatformApiKeyRecord { api_key: PlatformApiKey { id: PlatformApiKeyId::new(row.get::("id")), workspace_id: WorkspaceId::new(row.get::("workspace_id")), agent_id: row.get::, _>("agent_id").map(AgentId::new), key_kind: deserialize_enum_text( &row.get::("key_kind"), "key_kind", )?, name: row.get("name"), prefix: row.get("prefix"), scopes: deserialize_json_value(row.get::("scopes_json"))?, status: deserialize_enum_text(&row.get::("status"), "status")?, created_at: row.get("created_at"), last_used_at: row.get("last_used_at"), expires_at: row.get("expires_at"), allowed_origins: deserialize_json_value( row.get::("allowed_origins_json"), )?, }, }) }) .collect() } pub async fn get_platform_api_key_by_secret_for_agent_slug( &self, workspace_slug: &str, agent_slug: &str, secret_hash: &str, ) -> Result, RegistryError> { let row = sqlx::query( "select k.id, k.workspace_id, k.agent_id, k.key_kind, k.name, k.prefix, k.scopes_json, k.status, k.created_at, k.last_used_at, k.expires_at, k.allowed_origins_json from platform_api_keys k join workspaces w on w.id = k.workspace_id join agents a on a.id = k.agent_id where w.slug = $1 and a.slug = $2 and k.secret_hash = $3 and k.key_kind = 'mcp_client' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) limit 1", ) .bind(workspace_slug) .bind(agent_slug) .bind(secret_hash) .fetch_optional(&self.pool) .await?; row.map(|row| { Ok(PlatformApiKeyRecord { api_key: PlatformApiKey { id: PlatformApiKeyId::new(row.get::("id")), workspace_id: WorkspaceId::new(row.get::("workspace_id")), agent_id: row.get::, _>("agent_id").map(AgentId::new), key_kind: deserialize_enum_text(&row.get::("key_kind"), "key_kind")?, name: row.get("name"), prefix: row.get("prefix"), scopes: deserialize_json_value(row.get::("scopes_json"))?, status: deserialize_enum_text(&row.get::("status"), "status")?, created_at: row.get("created_at"), last_used_at: row.get("last_used_at"), expires_at: row.get("expires_at"), allowed_origins: deserialize_json_value( row.get::("allowed_origins_json"), )?, }, }) }) .transpose() } /// Authoritative revalidation of the Platform API key that authorized a durable Task (Story 4.3). /// /// The key is returned only when the exact immutable ID is still active, unexpired and bound to /// the same workspace and agent; otherwise `None`, so a worker fails closed. Only the immutable /// identity is supplied here — the bearer secret is never stored or re-read. pub async fn revalidate_platform_api_key( &self, workspace_id: &WorkspaceId, agent_id: &AgentId, key_id: &PlatformApiKeyId, ) -> Result, RegistryError> { let row = sqlx::query( "select k.id, k.workspace_id, k.agent_id, k.key_kind, k.name, k.prefix, k.scopes_json, k.status, k.created_at, k.last_used_at, k.expires_at, k.allowed_origins_json from platform_api_keys k where k.id = $1 and k.workspace_id = $2 and k.agent_id = $3 and k.key_kind = 'mcp_client' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) limit 1", ) .bind(key_id.as_str()) .bind(workspace_id.as_str()) .bind(agent_id.as_str()) .fetch_optional(&self.pool) .await?; row.map(|row| { Ok(PlatformApiKeyRecord { api_key: PlatformApiKey { id: PlatformApiKeyId::new(row.get::("id")), workspace_id: WorkspaceId::new(row.get::("workspace_id")), agent_id: row.get::, _>("agent_id").map(AgentId::new), key_kind: deserialize_enum_text(&row.get::("key_kind"), "key_kind")?, name: row.get("name"), prefix: row.get("prefix"), scopes: deserialize_json_value(row.get::("scopes_json"))?, status: deserialize_enum_text(&row.get::("status"), "status")?, created_at: row.get("created_at"), last_used_at: row.get("last_used_at"), expires_at: row.get("expires_at"), allowed_origins: deserialize_json_value( row.get::("allowed_origins_json"), )?, }, }) }) .transpose() } pub async fn get_approval_api_key_by_secret_for_agent_slug( &self, workspace_slug: &str, agent_slug: &str, secret_hash: &str, ) -> Result, RegistryError> { let row = sqlx::query( "select k.id, k.workspace_id, k.agent_id, k.key_kind, k.name, k.prefix, k.scopes_json, k.status, k.created_at, k.last_used_at, k.expires_at, k.allowed_origins_json from platform_api_keys k join workspaces w on w.id = k.workspace_id join agents a on a.id = k.agent_id where w.slug = $1 and a.slug = $2 and k.secret_hash = $3 and k.key_kind = 'approval' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) limit 1", ) .bind(workspace_slug) .bind(agent_slug) .bind(secret_hash) .fetch_optional(&self.pool) .await?; row.map(|row| { Ok(PlatformApiKeyRecord { api_key: PlatformApiKey { id: PlatformApiKeyId::new(row.get::("id")), workspace_id: WorkspaceId::new(row.get::("workspace_id")), agent_id: row.get::, _>("agent_id").map(AgentId::new), key_kind: deserialize_enum_text(&row.get::("key_kind"), "key_kind")?, name: row.get("name"), prefix: row.get("prefix"), scopes: deserialize_json_value(row.get::("scopes_json"))?, status: deserialize_enum_text(&row.get::("status"), "status")?, created_at: row.get("created_at"), last_used_at: row.get("last_used_at"), expires_at: row.get("expires_at"), allowed_origins: deserialize_json_value( row.get::("allowed_origins_json"), )?, }, }) }) .transpose() } pub async fn create_platform_api_key( &self, request: CreatePlatformApiKeyRequest<'_>, ) -> Result<(), RegistryError> { let result = sqlx::query( "insert into platform_api_keys ( id, workspace_id, agent_id, name, prefix, secret_hash, key_kind, scopes_json, status, created_at, last_used_at, revoked_at, expires_at, allowed_origins_json ) values ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::timestamptz, $11::timestamptz, $12::timestamptz, $13::timestamptz, $14 )", ) .bind(request.api_key.id.as_str()) .bind(request.api_key.workspace_id.as_str()) .bind(request.api_key.agent_id.as_ref().map(AgentId::as_str)) .bind(&request.api_key.name) .bind(&request.api_key.prefix) .bind(request.secret_hash) .bind(serialize_enum_text(&request.api_key.key_kind, "key_kind")?) .bind(Json(serialize_json_value(&request.api_key.scopes)?)) .bind(serialize_enum_text(&request.api_key.status, "status")?) .bind(request.api_key.created_at) .bind(request.api_key.last_used_at) .bind(Option::<&str>::None) .bind(request.api_key.expires_at) .bind(Json(serialize_json_value(&request.api_key.allowed_origins)?)) .execute(&self.pool) .await; match result { Ok(_) => Ok(()), Err(sqlx::Error::Database(error)) if matches!( error.constraint(), Some( "platform_api_keys_workspace_name_idx" | "platform_api_keys_workspace_name_active_idx" ) ) => { Err(RegistryError::PlatformApiKeyNameAlreadyExists { workspace_id: request.api_key.workspace_id.as_str().to_owned(), name: request.api_key.name.clone(), }) } Err(error) => Err(RegistryError::Storage(error)), } } pub async fn revoke_platform_api_key( &self, workspace_id: &WorkspaceId, key_id: &PlatformApiKeyId, revoked_at: &time::OffsetDateTime, ) -> Result<(), RegistryError> { let row = sqlx::query( "with target as ( select id from platform_api_keys where workspace_id = $3 and id = $4 ), updated as ( update platform_api_keys set status = $1, revoked_at = $2::timestamptz where workspace_id = $3 and id = $4 and status = 'active' returning id ) select exists(select 1 from target) as exists, exists(select 1 from updated) as updated", ) .bind(serialize_enum_text( &PlatformApiKeyStatus::Revoked, "status", )?) .bind(revoked_at) .bind(workspace_id.as_str()) .bind(key_id.as_str()) .fetch_one(&self.pool) .await?; if !row.get::("exists") { return Err(RegistryError::PlatformApiKeyNotFound { key_id: key_id.as_str().to_owned(), }); } if !row.get::("updated") { return Err(RegistryError::PlatformApiKeyInactive { key_id: key_id.as_str().to_owned(), }); } Ok(()) } pub async fn revoke_platform_api_key_for_agent( &self, workspace_id: &WorkspaceId, agent_id: &AgentId, key_id: &PlatformApiKeyId, revoked_at: &time::OffsetDateTime, ) -> Result<(), RegistryError> { let row = sqlx::query( "with target as ( select id from platform_api_keys where workspace_id = $3 and agent_id = $4 and id = $5 ), updated as ( update platform_api_keys set status = $1, revoked_at = $2::timestamptz where workspace_id = $3 and agent_id = $4 and id = $5 and status = 'active' returning id ) select exists(select 1 from target) as exists, exists(select 1 from updated) as updated", ) .bind(serialize_enum_text( &PlatformApiKeyStatus::Revoked, "status", )?) .bind(revoked_at) .bind(workspace_id.as_str()) .bind(agent_id.as_str()) .bind(key_id.as_str()) .fetch_one(&self.pool) .await?; if !row.get::("exists") { return Err(RegistryError::PlatformApiKeyNotFound { key_id: key_id.as_str().to_owned(), }); } if !row.get::("updated") { return Err(RegistryError::PlatformApiKeyInactive { key_id: key_id.as_str().to_owned(), }); } Ok(()) } pub async fn delete_platform_api_key( &self, workspace_id: &WorkspaceId, key_id: &PlatformApiKeyId, ) -> Result<(), RegistryError> { let row = sqlx::query( "with target as ( select id from platform_api_keys where workspace_id = $2 and id = $3 ), updated as ( update platform_api_keys set status = $1, revoked_at = coalesce(revoked_at, now()) where workspace_id = $2 and id = $3 and status <> 'deleted' returning id ) select exists(select 1 from target) as exists, exists(select 1 from updated) as updated", ) .bind(serialize_enum_text( &PlatformApiKeyStatus::Deleted, "status", )?) .bind(workspace_id.as_str()) .bind(key_id.as_str()) .fetch_one(&self.pool) .await?; if !row.get::("exists") { return Err(RegistryError::PlatformApiKeyNotFound { key_id: key_id.as_str().to_owned(), }); } if !row.get::("updated") { return Err(RegistryError::PlatformApiKeyInactive { key_id: key_id.as_str().to_owned(), }); } Ok(()) } pub async fn delete_platform_api_key_for_agent( &self, workspace_id: &WorkspaceId, agent_id: &AgentId, key_id: &PlatformApiKeyId, ) -> Result<(), RegistryError> { let row = sqlx::query( "with target as ( select id from platform_api_keys where workspace_id = $2 and agent_id = $3 and id = $4 ), updated as ( update platform_api_keys set status = $1, revoked_at = coalesce(revoked_at, now()) where workspace_id = $2 and agent_id = $3 and id = $4 and status <> 'deleted' returning id ) select exists(select 1 from target) as exists, exists(select 1 from updated) as updated", ) .bind(serialize_enum_text( &PlatformApiKeyStatus::Deleted, "status", )?) .bind(workspace_id.as_str()) .bind(agent_id.as_str()) .bind(key_id.as_str()) .fetch_one(&self.pool) .await?; if !row.get::("exists") { return Err(RegistryError::PlatformApiKeyNotFound { key_id: key_id.as_str().to_owned(), }); } if !row.get::("updated") { return Err(RegistryError::PlatformApiKeyInactive { key_id: key_id.as_str().to_owned(), }); } Ok(()) } pub async fn touch_platform_api_key( &self, workspace_id: &WorkspaceId, key_id: &PlatformApiKeyId, used_at: &time::OffsetDateTime, ) -> Result<(), RegistryError> { let row = sqlx::query( "with target as materialized ( select id, last_used_at, status = 'active' and (expires_at is null or expires_at > now()) as active from platform_api_keys where workspace_id = $1 and id = $2 for update ), updated as ( update platform_api_keys as api_key set last_used_at = $3::timestamptz from target where api_key.workspace_id = $1 and api_key.id = target.id and target.active and ( target.last_used_at is null or target.last_used_at < $3::timestamptz - interval '1 minute' ) returning api_key.id ) select exists(select 1 from target) as exists, coalesce((select active from target), false) as active", ) .bind(workspace_id.as_str()) .bind(key_id.as_str()) .bind(used_at) .fetch_one(&self.pool) .await?; if !row.get::("exists") { return Err(RegistryError::PlatformApiKeyNotFound { key_id: key_id.as_str().to_owned(), }); } if !row.get::("active") { return Err(RegistryError::PlatformApiKeyInactive { key_id: key_id.as_str().to_owned(), }); } Ok(()) } }