Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
crates_io_client: Add endpoints for listing, adding, and removing crate owners (#66524)
Finn Evers0018500a6a6d
diff --git a/tooling/crates_io_client/src/crates_io_client.rs b/tooling/crates_io_client/src/crates_io_client.rsindex 27a2d759cde..d110a822a79 100644--- a/tooling/crates_io_client/src/crates_io_client.rs+++ b/tooling/crates_io_client/src/crates_io_client.rs@@ -30,6 +30,25 @@ pub trait CratesIoClient: Send + Sync {/// belongs to an owner of the crate.async fn update_crate(&self, name: &CrateName, update: &CrateUpdate) -> Result<Crate>;+ /// Lists both user and team owners.+ async fn list_owners(&self, name: &CrateName) -> Result<Vec<Owner>>;++ /// Returns one outcome per requested owner.+ ///+ /// Requires a token with the `change-owners` endpoint scope that belongs+ /// to a user owner of the crate. crates.io accepts at most ten owners per+ /// request.+ async fn add_owners(+ &self,+ name: &CrateName,+ owners: &[OwnerLogin],+ ) -> Result<Vec<OwnerAddition>>;++ /// Requires a token with the `change-owners` endpoint scope that belongs+ /// to a user owner of the crate. crates.io rejects removing the last user+ /// owner.+ async fn remove_owners(&self, name: &CrateName, owners: &[OwnerLogin]) -> Result<()>;+/// Requires a token with the `trusted-publishing` endpoint scope that/// belongs to an owner of the crate.async fn list_github_configs(&self, crate_name: &CrateName) -> Result<Vec<GitHubConfig>>;diff --git a/tooling/crates_io_client/src/real_crates_io_client.rs b/tooling/crates_io_client/src/real_crates_io_client.rsindex 3449c9320d8..5389e32e90f 100644--- a/tooling/crates_io_client/src/real_crates_io_client.rs+++ b/tooling/crates_io_client/src/real_crates_io_client.rs@@ -61,11 +61,12 @@ impl RealCratesIoClient {Ok(Url::parse(&format!("{BASE_URL}{path}")).context("Invalid crates.io URL")?)}- fn crate_url(name: &CrateName) -> Result<Url> {+ fn crate_url(name: &CrateName, subpath: &[&str]) -> Result<Url> {let mut url = Self::url("/crates")?;url.path_segments_mut().map_err(|()| anyhow::anyhow!("crates.io URL cannot have path segments"))?- .push(name.as_str());+ .push(name.as_str())+ .extend(subpath);Ok(url)}@@ -126,6 +127,67 @@ impl RealCratesIoClient {Ok(serde_json::from_slice(&body).with_context(|| format!("Failed to parse crates.io response from {url}"))?)}++ /// Adding and removing owners share their request and response bodies.+ async fn change_owners(+ &self,+ method: Method,+ name: &CrateName,+ owners: &[OwnerLogin],+ ) -> Result<String> {+ #[derive(Serialize)]+ struct ChangeOwnersRequest<'a> {+ owners: &'a [OwnerLogin],+ }++ #[derive(Deserialize)]+ struct ChangeOwnersResponse {+ msg: String,+ }++ let body = serde_json::to_vec(&ChangeOwnersRequest { owners })+ .context("Failed to serialize crate owners")?;+ let response: ChangeOwnersResponse = self+ .request_json(method, Self::crate_url(name, &["owners"])?, Some(body))+ .await?;+ Ok(response.msg)+ }+}++/// crates.io joins one sentence per added owner with commas, which crate+/// names, usernames, and team logins cannot contain.+fn parse_owner_additions(message: &str, crate_name: &CrateName) -> Vec<OwnerAddition> {+ let invited_suffix = format!(" has been invited to be an owner of crate {crate_name}");+ let already_invited_suffix =+ format!(" already has a pending invitation to be an owner of crate {crate_name}");+ let team_suffix = format!(" has been added as an owner of crate {crate_name}");++ message+ .split(',')+ .map(|sentence| {+ let user = sentence.strip_prefix("Crates.io user ");+ if let Some(username) = user.and_then(|rest| rest.strip_suffix(&invited_suffix)) {+ OwnerAddition::UserInvited {+ username: username.to_owned(),+ }+ } else if let Some(username) =+ user.and_then(|rest| rest.strip_suffix(&already_invited_suffix))+ {+ OwnerAddition::UserAlreadyInvited {+ username: username.to_owned(),+ }+ } else if let Some(login) = sentence+ .strip_prefix("team ")+ .and_then(|rest| rest.strip_suffix(&team_suffix))+ {+ OwnerAddition::TeamAdded {+ login: login.to_owned(),+ }+ } else {+ OwnerAddition::Other(sentence.to_owned())+ }+ })+ .collect()}#[async_trait]@@ -192,7 +254,7 @@ impl CratesIoClient for RealCratesIoClient {versions: Option<Vec<Version>>,}- let mut url = Self::crate_url(name)?;+ let mut url = Self::crate_url(name, &[])?;url.query_pairs_mut().append_pair("include", "versions,keywords,categories");let response: CrateResponse = self.request_json(Method::GET, url, None).await?;@@ -218,11 +280,36 @@ impl CratesIoClient for RealCratesIoClient {let body = serde_json::to_vec(&UpdateRequest { krate: update }).context("Failed to serialize crate update")?;let response: UpdateResponse = self- .request_json(Method::PATCH, Self::crate_url(name)?, Some(body))+ .request_json(Method::PATCH, Self::crate_url(name, &[])?, Some(body)).await?;Ok(response.krate)}+ async fn list_owners(&self, name: &CrateName) -> Result<Vec<Owner>> {+ #[derive(Deserialize)]+ struct OwnersResponse {+ users: Vec<Owner>,+ }++ let url = Self::crate_url(name, &["owners"])?;+ let response: OwnersResponse = self.request_json(Method::GET, url, None).await?;+ Ok(response.users)+ }++ async fn add_owners(+ &self,+ name: &CrateName,+ owners: &[OwnerLogin],+ ) -> Result<Vec<OwnerAddition>> {+ let message = self.change_owners(Method::PUT, name, owners).await?;+ Ok(parse_owner_additions(&message, name))+ }++ async fn remove_owners(&self, name: &CrateName, owners: &[OwnerLogin]) -> Result<()> {+ self.change_owners(Method::DELETE, name, owners).await?;+ Ok(())+ }+async fn list_github_configs(&self, crate_name: &CrateName) -> Result<Vec<GitHubConfig>> {#[derive(Deserialize)]struct GitHubConfigListResponse {diff --git a/tooling/crates_io_client/src/simulated_crates_io_client.rs b/tooling/crates_io_client/src/simulated_crates_io_client.rsindex ed13bc566dc..6a8a26af5e6 100644--- a/tooling/crates_io_client/src/simulated_crates_io_client.rs+++ b/tooling/crates_io_client/src/simulated_crates_io_client.rs@@ -25,9 +25,55 @@ const MAX_GITHUB_CONFIGS_PER_CRATE: usize = 5;struct SimulatedCrate {krate: Crate,owners: Vec<UserId>,+ team_owners: Vec<Team>,+ invited_owners: Vec<OwnerLogin>,versions: Vec<Version>,}+impl SimulatedCrate {+ fn require_owner_rights(&self, user: UserId) -> Result<()> {+ if self.owners.contains(&user) {+ Ok(())+ } else {+ Err(CratesIoError::PermissionDenied {+ status: StatusCode::FORBIDDEN,+ message: "only owners have permission to modify owners".to_owned(),+ })+ }+ }++ fn matches(login: &OwnerLogin, owner: &Owner) -> bool {+ match (login, owner) {+ (+ OwnerLogin::Username(username)+ | OwnerLogin::CratesIoUser(username)+ | OwnerLogin::GitHubUser(username),+ Owner::User(user),+ ) => user.login.eq_ignore_ascii_case(username),+ (OwnerLogin::GitHubTeam { .. }, Owner::Team(team)) => {+ team.login.eq_ignore_ascii_case(&login.to_string())+ }+ _ => false,+ }+ }++ fn all_owners(&self) -> impl Iterator<Item = Owner> + '_ {+ let users = self+ .owners+ .iter()+ .map(|id| Owner::User(simulated_user(*id)));+ let teams = self.team_owners.iter().cloned().map(Owner::Team);+ users.chain(teams)+ }+}++fn bad_request(message: String) -> CratesIoError {+ CratesIoError::Upstream {+ status: StatusCode::BAD_REQUEST,+ message,+ }+}+impl CratesIoState {fn next_id(&mut self) -> i32 {self.latest_id += 1;@@ -66,6 +112,14 @@ fn listed(krate: &Crate) -> Crate {}}+fn simulated_user(id: UserId) -> User {+ User {+ id,+ login: format!("user-{}", id.0),+ name: None,+ }+}+fn test_timestamp() -> DateTime<Utc> {DateTime::from_timestamp(1_767_225_600, 0).unwrap_or_default()}@@ -126,12 +180,41 @@ impl SimulatedCratesIoClient {categories: Some(Vec::new()),},owners: vec![owner],+ team_owners: Vec::new(),+ invited_owners: Vec::new(),versions: Vec::new(),},);name}+ pub fn test_owner(&self, name: &CrateName, owner: UserId) -> Result<()> {+ self.state.lock().simulated_crate(name)?.owners.push(owner);+ Ok(())+ }++ pub fn test_team_owner(&self, name: &CrateName, login: &str) -> Result<TeamId> {+ let mut state = self.state.lock();+ let id = TeamId(state.next_id());+ state.simulated_crate(name)?.team_owners.push(Team {+ id,+ login: login.to_owned(),+ name: None,+ });+ Ok(id)+ }++ /// Users invited through [`CratesIoClient::add_owners`] that have not+ /// accepted yet.+ pub fn invited_owners(&self, name: &CrateName) -> Result<Vec<OwnerLogin>> {+ Ok(self+ .state+ .lock()+ .simulated_crate(name)?+ .invited_owners+ .clone())+ }+/// Changes crate fields that have no dedicated helper, such as its/// keywords or download counts.pub fn update_test_crate(@@ -166,11 +249,7 @@ impl SimulatedCratesIoClient {edition: None,crate_size: 0,checksum: String::new(),- published_by: Some(User {- id: publisher,- login: format!("user-{}", publisher.0),- name: None,- }),+ published_by: Some(simulated_user(publisher)),},);simulated_crate.krate.default_version = Some(num);@@ -250,6 +329,98 @@ impl CratesIoClient for SimulatedCratesIoClient {Ok(listed(&simulated_crate.krate))}+ async fn list_owners(&self, name: &CrateName) -> Result<Vec<Owner>> {+ let mut state = self.state.lock();+ Ok(state.simulated_crate(name)?.all_owners().collect())+ }++ async fn add_owners(+ &self,+ name: &CrateName,+ owners: &[OwnerLogin],+ ) -> Result<Vec<OwnerAddition>> {+ let mut state = self.state.lock();+ let token_user = state.token_user;+ let simulated_crate = state.simulated_crate(name)?;+ simulated_crate.require_owner_rights(token_user)?;+ if owners.len() > 10 {+ return Err(bad_request(+ "too many invites for this request - maximum 10".to_owned(),+ ));+ }+ if let Some(login) = owners.iter().find(|login| {+ simulated_crate+ .all_owners()+ .any(|owner| SimulatedCrate::matches(login, &owner))+ }) {+ return Err(bad_request(format!("`{login}` is already an owner")));+ }++ let mut additions = Vec::new();+ for login in owners {+ let team_id = TeamId(state.next_id());+ let simulated_crate = state.simulated_crate(name)?;+ let addition = match login {+ OwnerLogin::GitHubTeam { .. } => {+ simulated_crate.team_owners.push(Team {+ id: team_id,+ login: login.to_string(),+ name: None,+ });+ OwnerAddition::TeamAdded {+ login: login.to_string(),+ }+ }+ OwnerLogin::Username(username)+ | OwnerLogin::CratesIoUser(username)+ | OwnerLogin::GitHubUser(username) => {+ let username = username.clone();+ if simulated_crate.invited_owners.contains(login) {+ OwnerAddition::UserAlreadyInvited { username }+ } else {+ simulated_crate.invited_owners.push(login.clone());+ OwnerAddition::UserInvited { username }+ }+ }+ };+ additions.push(addition);+ }+ Ok(additions)+ }++ async fn remove_owners(&self, name: &CrateName, owners: &[OwnerLogin]) -> Result<()> {+ let mut state = self.state.lock();+ let token_user = state.token_user;+ let simulated_crate = state.simulated_crate(name)?;+ simulated_crate.require_owner_rights(token_user)?;++ let mut removed = Vec::new();+ for login in owners {+ let matching = simulated_crate+ .all_owners()+ .filter(|owner| SimulatedCrate::matches(login, owner))+ .collect::<Vec<_>>();+ if matching.is_empty() {+ return Err(bad_request(format!(+ "could not find owner with login `{login}`"+ )));+ }+ removed.extend(matching);+ }+ let is_removed_user = |id: &UserId| removed.contains(&Owner::User(simulated_user(*id)));+ if simulated_crate.owners.iter().all(is_removed_user) {+ return Err(bad_request(+ "cannot remove all individual owners of a crate. Team member don't have permission to modify owners, so at least one individual owner is required.".to_owned(),+ ));+ }++ simulated_crate.owners.retain(|id| !is_removed_user(id));+ simulated_crate+ .team_owners+ .retain(|team| !removed.contains(&Owner::Team(team.clone())));+ Ok(())+ }+async fn list_github_configs(&self, crate_name: &CrateName) -> Result<Vec<GitHubConfig>> {let mut state = self.state.lock();state.require_token_user_owns(crate_name)?;diff --git a/tooling/crates_io_client/src/tests.rs b/tooling/crates_io_client/src/tests.rsindex 7eecc2ebb24..942fb61cf39 100644--- a/tooling/crates_io_client/src/tests.rs+++ b/tooling/crates_io_client/src/tests.rs@@ -280,6 +280,111 @@ fn test_list_github_configs_rejects_full_page() {assert!(matches!(error, CratesIoError::Request(_)));}+#[test]+fn test_owner_endpoints_match_crates_io_api() {+ // Listing owners and changing them share a URL, so one response serves both.+ let (fake_http_client, requests) = recording_fake_http_client(|_| {+ let body = json!({+ "users": [+ {+ "kind": "user",+ "id": 436643,+ "login": "MrSubidubi",+ "url": "https://github.com/MrSubidubi",+ "name": "Finn Evers",+ "avatar": null,+ "github_username_matches": true,+ },+ {+ "kind": "team",+ "id": 12586,+ "login": "github:zed-industries:crates-io",+ "url": "https://github.com/zed-industries",+ "name": "crates-io",+ "avatar": null,+ },+ ],+ "msg": "Crates.io user maxbrunsfeld has been invited to be an owner of crate gpui,\+ Crates.io user mikayla-maki already has a pending invitation to be an owner of crate gpui,\+ team github:zed-industries:crates-io has been added as an owner of crate gpui,\+ owners changed",+ "ok": true,+ });+ (StatusCode::OK, body)+ });+ // Separate clients keep the test from waiting on the rate limit.+ let client = || RealCratesIoClient::new(fake_http_client.clone(), ApiToken::new("secret"));+ let gpui = CrateName::new("gpui");+ let owner_logins = [+ OwnerLogin::Username("maxbrunsfeld".to_owned()),+ OwnerLogin::CratesIoUser("maxbrunsfeld".to_owned()),+ OwnerLogin::GitHubUser("maxbrunsfeld".to_owned()),+ OwnerLogin::GitHubTeam {+ organization: "zed-industries".to_owned(),+ team: "crates-io".to_owned(),+ },+ ];++ let owners = smol::block_on(client().list_owners(&gpui)).unwrap();+ let additions = smol::block_on(client().add_owners(&gpui, &owner_logins)).unwrap();+ smol::block_on(client().remove_owners(&gpui, &owner_logins)).unwrap();++ assert_eq!(+ owners,+ [+ Owner::User(User {+ id: UserId(436643),+ login: "MrSubidubi".to_owned(),+ name: Some("Finn Evers".to_owned()),+ }),+ Owner::Team(Team {+ id: TeamId(12586),+ login: "github:zed-industries:crates-io".to_owned(),+ name: Some("crates-io".to_owned()),+ }),+ ]+ );+ assert_eq!(+ additions,+ [+ OwnerAddition::UserInvited {+ username: "maxbrunsfeld".to_owned(),+ },+ OwnerAddition::UserAlreadyInvited {+ username: "mikayla-maki".to_owned(),+ },+ OwnerAddition::TeamAdded {+ login: "github:zed-industries:crates-io".to_owned(),+ },+ OwnerAddition::Other("owners changed".to_owned()),+ ]+ );+ let requests = requests.lock();+ let expected_body = json!({+ "owners": [+ "maxbrunsfeld",+ "crates.io:maxbrunsfeld",+ "github:maxbrunsfeld",+ "github:zed-industries:crates-io",+ ]+ });+ for (request, method) in requests+ .iter()+ .zip([Method::GET, Method::PUT, Method::DELETE])+ {+ assert_eq!(request.method, method);+ assert_eq!(request.uri, "https://crates.io/api/v1/crates/gpui/owners");+ }+ assert_eq!(+ serde_json::from_str::<Value>(&requests[1].body).unwrap(),+ expected_body+ );+ assert_eq!(+ serde_json::from_str::<Value>(&requests[2].body).unwrap(),+ expected_body+ );+}+#[test]fn test_throttle_spaces_requests_by_minimum_interval() {let throttle = RequestThrottle::new();diff --git a/tooling/crates_io_client/src/types.rs b/tooling/crates_io_client/src/types.rsindex a03f7048acc..70096c0ab96 100644--- a/tooling/crates_io_client/src/types.rs+++ b/tooling/crates_io_client/src/types.rs@@ -8,6 +8,8 @@ use url::Url;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct UserId(pub i32);#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct TeamId(pub i32);+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct VersionId(pub i32);#[derive(Debug, Display, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,@@ -113,6 +115,60 @@ pub struct User {pub name: Option<String>,}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Team {+ pub id: TeamId,+ /// For example `github:zed-industries:crates-io`.+ pub login: String,+ pub name: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "lowercase")]+pub enum Owner {+ User(User),+ Team(Team),+}++/// Identifies an owner to add or remove.+#[derive(Debug, Display, Clone, PartialEq, Eq, Hash)]+pub enum OwnerLogin {+ /// A crates.io user, or a GitHub user when removing owners. crates.io+ /// rejects names that match different accounts.+ #[display("{_0}")]+ Username(String),+ #[display("crates.io:{_0}")]+ CratesIoUser(String),+ #[display("github:{_0}")]+ GitHubUser(String),+ #[display("github:{organization}:{team}")]+ GitHubTeam { organization: String, team: String },+}++/// The outcome of adding one owner, as crates.io describes it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum OwnerAddition {+ /// The user becomes an owner once they accept the invitation.+ UserInvited {+ username: String,+ },+ UserAlreadyInvited {+ username: String,+ },+ /// Teams become owners immediately.+ TeamAdded {+ login: String,+ },+ /// A message this client does not recognize.+ Other(String),+}++impl Serialize for OwnerLogin {+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.collect_str(self)+ }+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct CrateDetails {pub krate: Crate,