g1t/services/identity/src/workspaces.rs
| 1 | //! Workspaces and their members. |
| 2 | //! |
| 3 | //! A workspace owns repositories and is the first segment of their URLs. |
| 4 | //! There is one kind: a person's own space and a company's differ only in |
| 5 | //! how many members they have. Nothing can be created outside one. |
| 6 | |
| 7 | use g1t_contracts::access::BasePermission; |
| 8 | use g1t_contracts::identity::*; |
| 9 | use g1t_contracts::time::rfc3339; |
| 10 | use g1t_contracts::{ |
| 11 | FailureCode, Membership, Outcome, PrincipalKind, Role, User, is_valid_namespace, new_id, |
| 12 | }; |
| 13 | use g1t_kit::now_ms; |
| 14 | use serde::Deserialize; |
| 15 | use worker::Result; |
| 16 | |
| 17 | use crate::Identity; |
| 18 | |
| 19 | /// Enough for a person and their teams; stops one account claiming names in |
| 20 | /// bulk. |
| 21 | const MAX_WORKSPACES_PER_USER: usize = 10; |
| 22 | |
| 23 | const MAX_NAME_LENGTH: usize = 80; |
| 24 | const MAX_DESCRIPTION_LENGTH: usize = 160; |
| 25 | |
| 26 | const WORKSPACE_COLUMNS: &str = "workspaces.id, workspaces.slug, workspaces.name, |
| 27 | workspaces.description, workspaces.avatar, workspaces.created_at, workspaces.base_permission, |
| 28 | (SELECT count(*) FROM workspace_members |
| 29 | WHERE workspace_members.workspace_id = workspaces.id) AS member_count"; |
| 30 | |
| 31 | #[derive(Deserialize)] |
| 32 | struct WorkspaceRow { |
| 33 | id: String, |
| 34 | slug: String, |
| 35 | name: String, |
| 36 | description: Option<String>, |
| 37 | avatar: Option<String>, |
| 38 | created_at: String, |
| 39 | member_count: u32, |
| 40 | #[serde(default)] |
| 41 | base_permission: Option<String>, |
| 42 | } |
| 43 | |
| 44 | impl From<WorkspaceRow> for Workspace { |
| 45 | fn from(row: WorkspaceRow) -> Self { |
| 46 | Workspace { |
| 47 | id: row.id, |
| 48 | slug: row.slug, |
| 49 | name: row.name, |
| 50 | description: row.description, |
| 51 | created_at: row.created_at, |
| 52 | member_count: row.member_count, |
| 53 | avatar: row.avatar, |
| 54 | base_permission: row |
| 55 | .base_permission |
| 56 | .as_deref() |
| 57 | .and_then(BasePermission::parse) |
| 58 | .unwrap_or_default(), |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | #[derive(Deserialize)] |
| 64 | struct MemberRow { |
| 65 | username: String, |
| 66 | role: Role, |
| 67 | #[serde(default)] |
| 68 | name: Option<String>, |
| 69 | #[serde(default)] |
| 70 | avatar: Option<String>, |
| 71 | } |
| 72 | |
| 73 | impl Identity { |
| 74 | /// The workspaces a user belongs to, attached to every user resolved |
| 75 | /// from credentials, with what the site needs to show each one and |
| 76 | /// what members get on its repositories (access.rs). |
| 77 | pub async fn memberships(&self, user_id: &str) -> Result<Vec<Membership>> { |
| 78 | self.db |
| 79 | .prepare( |
| 80 | "SELECT workspaces.slug, workspace_members.role, workspaces.name, |
| 81 | workspaces.avatar, workspaces.base_permission |
| 82 | FROM workspace_members |
| 83 | JOIN workspaces ON workspaces.id = workspace_members.workspace_id |
| 84 | WHERE workspace_members.user_id = ? ORDER BY workspaces.slug", |
| 85 | ) |
| 86 | .bind(&[user_id.into()])? |
| 87 | .all() |
| 88 | .await? |
| 89 | .results::<Membership>() |
| 90 | } |
| 91 | |
| 92 | pub async fn create_workspace(&self, a: CreateWorkspaceArgs) -> Result<Outcome<Workspace>> { |
| 93 | if a.user.kind != PrincipalKind::User { |
| 94 | return Ok(Outcome::fail( |
| 95 | FailureCode::Forbidden, |
| 96 | "A workspace's access token cannot create workspaces. Sign in as a person.", |
| 97 | )); |
| 98 | } |
| 99 | if !a.user.verified { |
| 100 | return Ok(Outcome::fail( |
| 101 | FailureCode::Forbidden, |
| 102 | "Confirm your email address before creating a workspace.", |
| 103 | )); |
| 104 | } |
| 105 | let slug = a.slug.trim().to_lowercase(); |
| 106 | if !is_valid_namespace(&slug) { |
| 107 | return Ok(Outcome::fail( |
| 108 | FailureCode::Invalid, |
| 109 | "Workspace names use lowercase letters, digits and single hyphens, up to 39 characters.", |
| 110 | )); |
| 111 | } |
| 112 | if self.memberships(&a.user.id).await?.len() >= MAX_WORKSPACES_PER_USER { |
| 113 | return Ok(Outcome::fail( |
| 114 | FailureCode::Conflict, |
| 115 | "You belong to the maximum number of workspaces.", |
| 116 | )); |
| 117 | } |
| 118 | // Usernames and workspaces share one namespace: a person's username |
| 119 | // is theirs to use for a workspace, and nobody else's. |
| 120 | let someone_elses_username = self |
| 121 | .db |
| 122 | .prepare("SELECT id FROM users WHERE username = ? AND id != ?") |
| 123 | .bind(&[slug.as_str().into(), a.user.id.as_str().into()])? |
| 124 | .first::<serde_json::Value>(None) |
| 125 | .await? |
| 126 | .is_some(); |
| 127 | if someone_elses_username |
| 128 | || self |
| 129 | .get_workspace(SlugArgs { slug: slug.clone() }) |
| 130 | .await? |
| 131 | .is_some() |
| 132 | // A renamed workspace's old slug stays reserved for it a while. |
| 133 | || self.slug_held(&slug).await? |
| 134 | // A deleted workspace's slug is never given to anyone else; the |
| 135 | // person whose username it is may use it again. |
| 136 | || (self.slug_deleted(&slug).await? |
| 137 | && !crate::deletion::may_reclaim(&slug, &a.user.username)) |
| 138 | { |
| 139 | return Ok(Outcome::fail( |
| 140 | FailureCode::Conflict, |
| 141 | "That workspace name is taken.", |
| 142 | )); |
| 143 | } |
| 144 | let now = now_ms(); |
| 145 | let workspace = Workspace { |
| 146 | id: new_id("wsp", now), |
| 147 | name: match a.name.trim() { |
| 148 | "" => slug.clone(), |
| 149 | name => name.chars().take(MAX_NAME_LENGTH).collect(), |
| 150 | }, |
| 151 | description: None, |
| 152 | slug, |
| 153 | created_at: rfc3339(now), |
| 154 | member_count: 1, |
| 155 | avatar: None, |
| 156 | base_permission: BasePermission::default(), |
| 157 | }; |
| 158 | self.db |
| 159 | .batch(vec![ |
| 160 | self.db |
| 161 | .prepare( |
| 162 | "INSERT INTO workspaces (id, slug, name, created_by, created_at) |
| 163 | VALUES (?, ?, ?, ?, ?)", |
| 164 | ) |
| 165 | .bind(&[ |
| 166 | workspace.id.as_str().into(), |
| 167 | workspace.slug.as_str().into(), |
| 168 | workspace.name.as_str().into(), |
| 169 | a.user.id.as_str().into(), |
| 170 | workspace.created_at.as_str().into(), |
| 171 | ])?, |
| 172 | self.db |
| 173 | .prepare( |
| 174 | "INSERT INTO workspace_members (workspace_id, user_id, role, created_at) |
| 175 | VALUES (?, ?, 'owner', ?)", |
| 176 | ) |
| 177 | .bind(&[ |
| 178 | workspace.id.as_str().into(), |
| 179 | a.user.id.as_str().into(), |
| 180 | workspace.created_at.as_str().into(), |
| 181 | ])?, |
| 182 | ]) |
| 183 | .await?; |
| 184 | self.forget_deleted(&workspace.slug).await?; |
| 185 | Ok(Outcome::Ok(workspace)) |
| 186 | } |
| 187 | |
| 188 | pub async fn get_workspace(&self, a: SlugArgs) -> Result<Option<Workspace>> { |
| 189 | Ok(self |
| 190 | .db |
| 191 | .prepare(format!( |
| 192 | "SELECT {WORKSPACE_COLUMNS} FROM workspaces WHERE slug = ?" |
| 193 | )) |
| 194 | .bind(&[a.slug.to_lowercase().into()])? |
| 195 | .first::<WorkspaceRow>(None) |
| 196 | .await? |
| 197 | .map(Workspace::from)) |
| 198 | } |
| 199 | |
| 200 | pub async fn update_workspace(&self, a: UpdateWorkspaceArgs) -> Result<Outcome<Workspace>> { |
| 201 | let slug = a.slug.to_lowercase(); |
| 202 | if a.actor.kind != PrincipalKind::User || a.actor.role_in(&slug) != Some(Role::Owner) { |
| 203 | return Ok(Outcome::fail( |
| 204 | FailureCode::Forbidden, |
| 205 | "Only an owner can change a workspace's details.", |
| 206 | )); |
| 207 | } |
| 208 | let name: String = match a.name.trim() { |
| 209 | "" => slug.clone(), |
| 210 | name => name.chars().take(MAX_NAME_LENGTH).collect(), |
| 211 | }; |
| 212 | let description: String = a |
| 213 | .description |
| 214 | .trim() |
| 215 | .chars() |
| 216 | .take(MAX_DESCRIPTION_LENGTH) |
| 217 | .collect(); |
| 218 | self.db |
| 219 | .prepare("UPDATE workspaces SET name = ?, description = ? WHERE slug = ?") |
| 220 | .bind(&[ |
| 221 | name.into(), |
| 222 | if description.is_empty() { |
| 223 | worker::wasm_bindgen::JsValue::NULL |
| 224 | } else { |
| 225 | description.into() |
| 226 | }, |
| 227 | slug.as_str().into(), |
| 228 | ])? |
| 229 | .run() |
| 230 | .await?; |
| 231 | Ok(match self.get_workspace(SlugArgs { slug }).await? { |
| 232 | Some(workspace) => Outcome::Ok(workspace), |
| 233 | None => Outcome::fail(FailureCode::NotFound, "Workspace not found."), |
| 234 | }) |
| 235 | } |
| 236 | |
| 237 | pub async fn list_members(&self, a: ListMembersArgs) -> Result<Outcome<Vec<Member>>> { |
| 238 | let slug = a.slug.to_lowercase(); |
| 239 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&slug)) { |
| 240 | return Ok(Outcome::fail( |
| 241 | FailureCode::Forbidden, |
| 242 | "Only members can see who is in a workspace.", |
| 243 | )); |
| 244 | } |
| 245 | let rows = self |
| 246 | .db |
| 247 | .prepare( |
| 248 | "SELECT users.username, workspace_members.role, users.display_name AS name, users.avatar FROM workspace_members |
| 249 | JOIN users ON users.id = workspace_members.user_id |
| 250 | JOIN workspaces ON workspaces.id = workspace_members.workspace_id |
| 251 | WHERE workspaces.slug = ? |
| 252 | ORDER BY workspace_members.role DESC, users.username", |
| 253 | ) |
| 254 | .bind(&[slug.into()])? |
| 255 | .all() |
| 256 | .await? |
| 257 | .results::<MemberRow>()?; |
| 258 | Ok(Outcome::Ok( |
| 259 | rows.into_iter() |
| 260 | .map(|row| Member { |
| 261 | username: row.username, |
| 262 | role: row.role, |
| 263 | name: row.name, |
| 264 | avatar: row.avatar, |
| 265 | }) |
| 266 | .collect(), |
| 267 | )) |
| 268 | } |
| 269 | |
| 270 | /// The ids needed to change a workspace's members, if `actor` owns it |
| 271 | /// and `username` exists. |
| 272 | async fn member_target(&self, a: &MemberArgs) -> Result<Outcome<(String, User)>> { |
| 273 | let slug = a.slug.to_lowercase(); |
| 274 | if a.actor.kind != PrincipalKind::User || a.actor.role_in(&slug) != Some(Role::Owner) { |
| 275 | return Ok(Outcome::fail( |
| 276 | FailureCode::Forbidden, |
| 277 | "Only an owner can change a workspace's members.", |
| 278 | )); |
| 279 | } |
| 280 | let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else { |
| 281 | return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found.")); |
| 282 | }; |
| 283 | let Some(user) = self |
| 284 | .find_public_user( |
| 285 | "SELECT id, username, email_verified_at IS NOT NULL AS verified |
| 286 | FROM users WHERE username = ?", |
| 287 | &a.username.trim().to_lowercase(), |
| 288 | ) |
| 289 | .await? |
| 290 | else { |
| 291 | return Ok(Outcome::fail( |
| 292 | FailureCode::NotFound, |
| 293 | "There is no account with that username.", |
| 294 | )); |
| 295 | }; |
| 296 | Ok(Outcome::Ok((workspace.id, user))) |
| 297 | } |
| 298 | |
| 299 | pub async fn add_member(&self, a: MemberArgs) -> Result<Outcome<bool>> { |
| 300 | let (workspace_id, user) = match self.member_target(&a).await? { |
| 301 | Outcome::Ok(target) => target, |
| 302 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 303 | }; |
| 304 | // What the workspace asks of its members (security.rs); nothing yet. |
| 305 | if let Some(why) = self.policy_refusal(&user.id, &a.slug.to_lowercase()).await? { |
| 306 | return Ok(Outcome::fail(FailureCode::Forbidden, why)); |
| 307 | } |
| 308 | self.db |
| 309 | .prepare( |
| 310 | "INSERT OR IGNORE INTO workspace_members (workspace_id, user_id, role, created_at) |
| 311 | VALUES (?, ?, 'member', ?)", |
| 312 | ) |
| 313 | .bind(&[ |
| 314 | workspace_id.into(), |
| 315 | user.id.into(), |
| 316 | rfc3339(now_ms()).into(), |
| 317 | ])? |
| 318 | .run() |
| 319 | .await?; |
| 320 | Ok(Outcome::Ok(true)) |
| 321 | } |
| 322 | |
| 323 | pub async fn remove_member(&self, a: MemberArgs) -> Result<Outcome<bool>> { |
| 324 | let (workspace_id, user) = match self.member_target(&a).await? { |
| 325 | Outcome::Ok(target) => target, |
| 326 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 327 | }; |
| 328 | if user.id == a.actor.id { |
| 329 | return Ok(Outcome::fail( |
| 330 | FailureCode::Conflict, |
| 331 | "An owner cannot remove themselves.", |
| 332 | )); |
| 333 | } |
| 334 | // Leaving a workspace takes away every way into it: the person's |
| 335 | // roles on its repositories go too (access.rs). To keep someone on |
| 336 | // a repository, add them to it again as an outside collaborator. |
| 337 | self.db |
| 338 | .batch(vec![ |
| 339 | self.db |
| 340 | .prepare("DELETE FROM workspace_members WHERE workspace_id = ? AND user_id = ?") |
| 341 | .bind(&[workspace_id.as_str().into(), user.id.as_str().into()])?, |
| 342 | self.db |
| 343 | .prepare( |
| 344 | "DELETE FROM repo_grants |
| 345 | WHERE workspace_id = ? AND principal_kind = 'user' AND principal_id = ?", |
| 346 | ) |
| 347 | .bind(&[workspace_id.as_str().into(), user.id.as_str().into()])?, |
| 348 | ]) |
| 349 | .await?; |
| 350 | Ok(Outcome::Ok(true)) |
| 351 | } |
| 352 | } |