| 1 | //! A repository's lifecycle after it is made: renaming it, archiving it, |
| 2 | //! making it public or private, changing or renaming its default branch, |
| 3 | //! and deleting it with a window to restore it. |
| 4 | //! |
| 5 | //! Deleting is soft. The row gets `deleted_at` and `purge_after` |
| 6 | //! ([`RESTORE_DAYS`] on), every read in the registry leaves it out, git |
| 7 | //! refuses it, and `repo.deleted` tells every service to stop what runs for |
| 8 | //! it and hide it. Restoring clears the columns (`repo.restored`). Purging, |
| 9 | //! by an owner from the Recently deleted list or by the hourly sweep once |
| 10 | //! `purge_after` has passed, removes the git data from the store, then the |
| 11 | //! rows (its pull requests' working copies with it) and its redirects, and |
| 12 | //! announces `repo.purged`, on which services drop what they keep for it. |
| 13 | //! Until then its name stays taken, so a restore always has its path back. |
| 14 | //! |
| 15 | //! A rename is a path change like a transfer: the old path is kept in |
| 16 | //! `repo_redirects`, the git store key never changes, the tokens of agents |
| 17 | //! at work on it are moved with identity, and `repo.renamed` is handled by |
| 18 | //! services with the same helper as `repo.transferred` |
| 19 | //! (`g1t_kit::transfer`). |
| 20 | |
| 21 | use g1t_contracts::audit::{ |
| 22 | AuditActor, AuditOutcome, AuditTarget, NewAuditEntry, RecordAuditArgs, Surface, |
| 23 | }; |
| 24 | use g1t_contracts::events::{ |
| 25 | BranchRenamed, NewEvent, RepoArchived, RepoDefaultBranchChanged, RepoDeleted, RepoPurged, |
| 26 | RepoRenamed, RepoRestored, RepoUpdated, RepoVisibilityChanged, WorkspaceDeleted, |
| 27 | WorkspaceDeleting, WorkspaceRestored, |
| 28 | }; |
| 29 | use g1t_contracts::identity::TransferRepoScopesArgs; |
| 30 | use g1t_contracts::repos::{ |
| 31 | ArchiveArgs, DeleteArgs, DeletedArgs, DeletedRepo, DeletedRepoArgs, PurgeDueArgs, |
| 32 | RESTORE_DAYS, RenameArgs, RenameBranchArgs, Repo, RepoPath, RepoStatus, ResolveBranchArgs, |
| 33 | SetDefaultBranchArgs, SetVisibilityArgs, StatusByIdArgs, archived_message, |
| 34 | is_valid_branch_name, |
| 35 | }; |
| 36 | use g1t_contracts::access::{self, Capability, RepoRole}; |
| 37 | use g1t_contracts::time::rfc3339; |
| 38 | use g1t_contracts::{FailureCode, Outcome, PrincipalKind, Role, User, is_valid_repo_name, new_id}; |
| 39 | use g1t_kit::now_ms; |
| 40 | use serde::Deserialize; |
| 41 | use worker::Result; |
| 42 | use worker::wasm_bindgen::JsValue; |
| 43 | |
| 44 | use crate::registry::{Registry, remember_store, store_key}; |
| 45 | use crate::store::{GitRepo, GitStore, Scope}; |
| 46 | use crate::{Repos, SOURCE, UNVERIFIED, git_ops, land, not_found}; |
| 47 | |
| 48 | use crate::land::EMPTY_PACK; |
| 49 | |
| 50 | /// How many pull request working copies follow a change of the default |
| 51 | /// branch (newest first). Older ones keep the branch they were made with. |
| 52 | const FORKS_FOLLOWING: u32 = 100; |
| 53 | |
| 54 | /// How many deleted repositories one sweep purges. |
| 55 | const PURGES_PER_SWEEP: u32 = 25; |
| 56 | |
| 57 | type Refusal = (FailureCode, String); |
| 58 | |
| 59 | /// Who is asking, as far as an owner's or an admin's action cares. |
| 60 | #[derive(Clone, Copy, Debug)] |
| 61 | pub struct Asker { |
| 62 | /// A person, not a workspace's or an agent's token. |
| 63 | pub person: bool, |
| 64 | pub verified: bool, |
| 65 | /// Their role in the repository's workspace. |
| 66 | pub role: Option<Role>, |
| 67 | /// Their role on the repository itself (see g1t_contracts::access). |
| 68 | /// None where only the workspace is known, as for deleted ones. |
| 69 | pub repo_role: Option<RepoRole>, |
| 70 | } |
| 71 | |
| 72 | impl Asker { |
| 73 | pub fn of(user: &User, namespace: &str) -> Self { |
| 74 | Asker { |
| 75 | person: user.kind == PrincipalKind::User, |
| 76 | verified: user.verified, |
| 77 | role: user.role_in(&namespace.to_lowercase()), |
| 78 | repo_role: None, |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// The asker, with their role on `repo`. |
| 83 | pub fn on(user: &User, repo: &Repo) -> Self { |
| 84 | Asker { |
| 85 | repo_role: crate::registry::role(repo, &Some(user.clone())), |
| 86 | ..Asker::of(user, &repo.namespace) |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// Whether `asker` may `what` ("rename", "archive"...) a repository of |
| 92 | /// `namespace` that takes `capability`: a verified person with the role |
| 93 | /// the permission table asks (Admin), and for transferring and deleting, |
| 94 | /// an owner of the workspace as well. |
| 95 | pub fn admin_only(asker: Asker, namespace: &str, what: &str, capability: Capability) -> std::result::Result<(), Refusal> { |
| 96 | if access::OWNER_ONLY.contains(&capability) { |
| 97 | // Someone who can see the repository is told why, not that it is missing. |
| 98 | if asker.role.is_none() && asker.repo_role.is_some() && asker.person { |
| 99 | return Err(( |
| 100 | FailureCode::Forbidden, |
| 101 | format!("Only an owner of {namespace} can {what} its repositories."), |
| 102 | )); |
| 103 | } |
| 104 | return owner_only(asker, namespace, what); |
| 105 | } |
| 106 | if asker.role.is_none() && asker.repo_role.is_none() { |
| 107 | return Err((FailureCode::NotFound, "Repository not found.".into())); |
| 108 | } |
| 109 | if !asker.person { |
| 110 | return Err(( |
| 111 | FailureCode::Forbidden, |
| 112 | format!("Only a person can {what} a repository. Sign in, or use a personal access token."), |
| 113 | )); |
| 114 | } |
| 115 | if !asker.repo_role.is_some_and(|role| access::allows(role, capability)) { |
| 116 | return Err(( |
| 117 | FailureCode::Forbidden, |
| 118 | format!( |
| 119 | "You need the {} role on a repository of {namespace} to {what} it.", |
| 120 | access::least_role(capability).label() |
| 121 | ), |
| 122 | )); |
| 123 | } |
| 124 | if !asker.verified { |
| 125 | return Err((FailureCode::Forbidden, UNVERIFIED.into())); |
| 126 | } |
| 127 | Ok(()) |
| 128 | } |
| 129 | |
| 130 | /// Whether `asker` may `what` ("delete", "rename"...) a repository of |
| 131 | /// `namespace`: a verified person who owns the workspace. |
| 132 | pub fn owner_only(asker: Asker, namespace: &str, what: &str) -> std::result::Result<(), Refusal> { |
| 133 | if asker.role.is_none() { |
| 134 | return Err((FailureCode::NotFound, "Repository not found.".into())); |
| 135 | } |
| 136 | if !asker.person { |
| 137 | return Err(( |
| 138 | FailureCode::Forbidden, |
| 139 | format!("Only a person can {what} a repository. Sign in, or use a personal access token."), |
| 140 | )); |
| 141 | } |
| 142 | if asker.role != Some(Role::Owner) { |
| 143 | return Err(( |
| 144 | FailureCode::Forbidden, |
| 145 | format!("Only an owner of {namespace} can {what} its repositories."), |
| 146 | )); |
| 147 | } |
| 148 | if !asker.verified { |
| 149 | return Err((FailureCode::Forbidden, UNVERIFIED.into())); |
| 150 | } |
| 151 | Ok(()) |
| 152 | } |
| 153 | |
| 154 | /// Whether what was typed to confirm names the repository: its full name, |
| 155 | /// `namespace/name`, in any case. |
| 156 | pub fn confirmed(path: &RepoPath, typed: &str) -> bool { |
| 157 | typed.trim().to_lowercase() == format!("{}/{}", path.namespace, path.name).to_lowercase() |
| 158 | } |
| 159 | |
| 160 | fn confirm_refusal(path: &RepoPath) -> Refusal { |
| 161 | ( |
| 162 | FailureCode::Invalid, |
| 163 | format!("Type {}/{} to confirm.", path.namespace, path.name), |
| 164 | ) |
| 165 | } |
| 166 | |
| 167 | /// When a repository deleted at `now_ms` is purged. |
| 168 | pub fn purge_after(now_ms: u64) -> String { |
| 169 | rfc3339(now_ms + RESTORE_DAYS * 86_400_000) |
| 170 | } |
| 171 | |
| 172 | /// Whether a repository to be purged at `purge_after` can still be |
| 173 | /// restored at `now` (both RFC 3339, which compare as text). |
| 174 | pub fn restorable(purge_after: &str, now: &str) -> bool { |
| 175 | now < purge_after |
| 176 | } |
| 177 | |
| 178 | /// Whether a workspace's repositories may go with it: never a protected |
| 179 | /// workspace's (`protected` is `g1t_contracts::identity::protected_names`), |
| 180 | /// however the event came to be published. |
| 181 | pub fn may_go_with_workspace(namespace: &str, protected: &[String]) -> std::result::Result<(), String> { |
| 182 | if protected.iter().any(|name| name.eq_ignore_ascii_case(namespace)) { |
| 183 | return Err(g1t_contracts::identity::protected_refusal(namespace)); |
| 184 | } |
| 185 | Ok(()) |
| 186 | } |
| 187 | |
| 188 | /// Whether a deleted repository comes back when the workspace |
| 189 | /// `workspace_id` is restored: only if it went with that workspace |
| 190 | /// (`deleted_with`), not if it was deleted on its own before. |
| 191 | pub fn comes_back_with(deleted_with: Option<&str>, workspace_id: &str) -> bool { |
| 192 | deleted_with == Some(workspace_id) |
| 193 | } |
| 194 | |
| 195 | /// Where a repository is in its life, from its row. |
| 196 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 197 | pub enum State { |
| 198 | Active, |
| 199 | Archived, |
| 200 | /// Deleted, and restorable until purged. |
| 201 | Deleted, |
| 202 | /// Deleted, and due to be purged by the next sweep. |
| 203 | Due, |
| 204 | } |
| 205 | |
| 206 | pub fn state(archived_at: Option<&str>, deleted: Option<(&str, &str)>, now: &str) -> State { |
| 207 | match deleted { |
| 208 | Some((_, purge_after)) if !restorable(purge_after, now) => State::Due, |
| 209 | Some(_) => State::Deleted, |
| 210 | None if archived_at.is_some() => State::Archived, |
| 211 | None => State::Active, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// What holds a name in a workspace. |
| 216 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 217 | pub enum Held { |
| 218 | Free, |
| 219 | ByRepo, |
| 220 | /// A repository deleted but not yet purged. |
| 221 | ByDeleted, |
| 222 | } |
| 223 | |
| 224 | /// The name a repository at `current` can be renamed to, tidied, or why |
| 225 | /// not. |
| 226 | pub fn new_name(namespace: &str, current: &str, wanted: &str, held: Held) -> std::result::Result<String, Refusal> { |
| 227 | let name = wanted.trim().to_lowercase(); |
| 228 | if !is_valid_repo_name(&name) { |
| 229 | return Err(( |
| 230 | FailureCode::Invalid, |
| 231 | "Use letters, digits, dots, hyphens and underscores only.".into(), |
| 232 | )); |
| 233 | } |
| 234 | if name == current { |
| 235 | return Err((FailureCode::Invalid, format!("It is already called {name}."))); |
| 236 | } |
| 237 | match held { |
| 238 | Held::Free => Ok(name), |
| 239 | Held::ByRepo => Err(( |
| 240 | FailureCode::Conflict, |
| 241 | format!("{namespace} already has a repository named {name}."), |
| 242 | )), |
| 243 | Held::ByDeleted => Err(( |
| 244 | FailureCode::Conflict, |
| 245 | format!( |
| 246 | "{namespace}/{name} was deleted recently and can still be restored. Restore it and rename it, or delete it permanently from the workspace's Recently deleted list first." |
| 247 | ), |
| 248 | )), |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /// Why a write to `repo` is refused because it is archived, if it is. |
| 253 | pub fn archived_refusal(repo: &Repo) -> Option<Refusal> { |
| 254 | repo.archived() |
| 255 | .then(|| (FailureCode::Forbidden, archived_message(&repo.namespace, &repo.name))) |
| 256 | } |
| 257 | |
| 258 | /// Everything that decides whether a repository may go private or public. |
| 259 | #[derive(Debug, Default)] |
| 260 | pub struct VisibilityFacts { |
| 261 | pub to_private: bool, |
| 262 | /// The workspace is on no plan, so its private storage is capped. |
| 263 | pub free: bool, |
| 264 | /// What its private repositories hold now. |
| 265 | pub private_bytes: i64, |
| 266 | /// What this repository holds. |
| 267 | pub bytes: i64, |
| 268 | /// What a free workspace's private repositories may hold. |
| 269 | pub free_private_bytes: i64, |
| 270 | } |
| 271 | |
| 272 | /// Whether the visibility change `facts` describe may happen. |
| 273 | pub fn visibility_check(namespace: &str, facts: &VisibilityFacts) -> std::result::Result<(), Refusal> { |
| 274 | if facts.to_private |
| 275 | && facts.free |
| 276 | && git_ops::storage_full(facts.private_bytes + facts.bytes, facts.free_private_bytes) |
| 277 | { |
| 278 | return Err(( |
| 279 | FailureCode::PaymentRequired, |
| 280 | format!( |
| 281 | "{namespace}'s private repositories would hold {:.2} GB, more than the {:.0} GB a free workspace has. Start the g1t plan in {namespace}, or keep the repository public.", |
| 282 | (facts.private_bytes + facts.bytes) as f64 / 1e9, |
| 283 | facts.free_private_bytes as f64 / 1e9, |
| 284 | ), |
| 285 | )); |
| 286 | } |
| 287 | Ok(()) |
| 288 | } |
| 289 | |
| 290 | /// Whether `from` can be renamed to `to` in a repository whose branches |
| 291 | /// are `branches`. `to` is tidied of surrounding space. |
| 292 | pub fn branch_rename(from: &str, to: &str, branches: &[String]) -> std::result::Result<String, Refusal> { |
| 293 | let to = to.trim().to_owned(); |
| 294 | if !branches.iter().any(|branch| branch == from) { |
| 295 | return Err((FailureCode::NotFound, format!("There is no branch named {from}."))); |
| 296 | } |
| 297 | if !is_valid_branch_name(&to) { |
| 298 | return Err(( |
| 299 | FailureCode::Invalid, |
| 300 | format!("{to:?} cannot be a branch name. Use letters, digits, '/', '-', '_' and '.', and no spaces."), |
| 301 | )); |
| 302 | } |
| 303 | if to == from { |
| 304 | return Err((FailureCode::Invalid, format!("It is already called {to}."))); |
| 305 | } |
| 306 | if branches.contains(&to) { |
| 307 | return Err((FailureCode::Conflict, format!("There is already a branch named {to}."))); |
| 308 | } |
| 309 | Ok(to) |
| 310 | } |
| 311 | |
| 312 | /// The row of a deleted repository. |
| 313 | #[derive(Deserialize)] |
| 314 | struct DeletedRow { |
| 315 | id: String, |
| 316 | namespace: String, |
| 317 | name: String, |
| 318 | description: Option<String>, |
| 319 | is_private: u8, |
| 320 | deleted_at: String, |
| 321 | #[serde(default)] |
| 322 | deleted_by: Option<String>, |
| 323 | purge_after: String, |
| 324 | #[serde(default)] |
| 325 | deleted_with: Option<String>, |
| 326 | } |
| 327 | |
| 328 | impl From<DeletedRow> for DeletedRepo { |
| 329 | fn from(row: DeletedRow) -> Self { |
| 330 | DeletedRepo { |
| 331 | id: row.id, |
| 332 | namespace: row.namespace, |
| 333 | name: row.name, |
| 334 | description: row.description, |
| 335 | is_private: row.is_private != 0, |
| 336 | deleted_at: row.deleted_at, |
| 337 | deleted_by: row.deleted_by.unwrap_or_default(), |
| 338 | purge_after: row.purge_after, |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | const DELETED_COLUMNS: &str = |
| 344 | "id, namespace, name, description, is_private, deleted_at, deleted_by, purge_after, deleted_with"; |
| 345 | |
| 346 | impl Registry { |
| 347 | /// Deletes a repository and its pull requests' working copies, softly. |
| 348 | pub async fn soft_delete(&self, id: &str, by: &str, at: &str, purge_after: &str) -> Result<()> { |
| 349 | self.db |
| 350 | .prepare( |
| 351 | "UPDATE repos SET deleted_at = ?1, deleted_by = ?2, purge_after = ?3 |
| 352 | WHERE (id = ?4 OR fork_of = ?4) AND deleted_at IS NULL", |
| 353 | ) |
| 354 | .bind(&[at.into(), by.into(), purge_after.into(), id.into()])? |
| 355 | .run() |
| 356 | .await?; |
| 357 | Ok(()) |
| 358 | } |
| 359 | |
| 360 | /// Brings a deleted repository and its working copies back. |
| 361 | pub async fn undelete(&self, id: &str) -> Result<()> { |
| 362 | self.db |
| 363 | .prepare( |
| 364 | "UPDATE repos SET deleted_at = NULL, deleted_by = NULL, purge_after = NULL |
| 365 | WHERE id = ?1 OR fork_of = ?1", |
| 366 | ) |
| 367 | .bind(&[id.into()])? |
| 368 | .run() |
| 369 | .await?; |
| 370 | Ok(()) |
| 371 | } |
| 372 | |
| 373 | /// Deletes every live repository of `namespace`, and the working |
| 374 | /// copies of its repositories, softly, each marked as gone with the |
| 375 | /// workspace `workspace_id`. Those already deleted are left as they |
| 376 | /// are. Returns every repository so marked, this time or before, so a |
| 377 | /// delivery again tells services again. |
| 378 | pub async fn delete_with_workspace( |
| 379 | &self, |
| 380 | namespace: &str, |
| 381 | workspace_id: &str, |
| 382 | by: &str, |
| 383 | at: &str, |
| 384 | purge_after: &str, |
| 385 | ) -> Result<Vec<DeletedRepo>> { |
| 386 | self.db |
| 387 | .prepare( |
| 388 | "UPDATE repos SET deleted_at = ?1, deleted_by = ?2, purge_after = ?3, deleted_with = ?4 |
| 389 | WHERE deleted_at IS NULL |
| 390 | AND (namespace = ?5 OR fork_of IN (SELECT id FROM repos WHERE namespace = ?5))", |
| 391 | ) |
| 392 | .bind(&[at.into(), by.into(), purge_after.into(), workspace_id.into(), namespace.into()])? |
| 393 | .run() |
| 394 | .await?; |
| 395 | self.deleted_with(workspace_id).await |
| 396 | } |
| 397 | |
| 398 | /// The repositories deleted with the workspace `workspace_id`. |
| 399 | pub async fn deleted_with(&self, workspace_id: &str) -> Result<Vec<DeletedRepo>> { |
| 400 | Ok(self |
| 401 | .db |
| 402 | .prepare(format!( |
| 403 | "SELECT {DELETED_COLUMNS} FROM repos WHERE deleted_with = ? AND fork_of IS NULL" |
| 404 | )) |
| 405 | .bind(&[workspace_id.into()])? |
| 406 | .all() |
| 407 | .await? |
| 408 | .results::<DeletedRow>()? |
| 409 | .into_iter() |
| 410 | .filter(|row| comes_back_with(row.deleted_with.as_deref(), workspace_id)) |
| 411 | .map(DeletedRepo::from) |
| 412 | .collect()) |
| 413 | } |
| 414 | |
| 415 | /// Brings back the repositories, and their working copies, deleted |
| 416 | /// with the workspace `workspace_id`, and only those. |
| 417 | pub async fn undelete_with_workspace(&self, workspace_id: &str) -> Result<()> { |
| 418 | self.db |
| 419 | .prepare( |
| 420 | "UPDATE repos SET deleted_at = NULL, deleted_by = NULL, purge_after = NULL, deleted_with = NULL |
| 421 | WHERE deleted_with = ?", |
| 422 | ) |
| 423 | .bind(&[workspace_id.into()])? |
| 424 | .run() |
| 425 | .await?; |
| 426 | Ok(()) |
| 427 | } |
| 428 | |
| 429 | /// A workspace's deleted repositories, newest first. |
| 430 | pub async fn deleted_in(&self, namespace: &str) -> Result<Vec<DeletedRepo>> { |
| 431 | Ok(self |
| 432 | .db |
| 433 | .prepare(format!( |
| 434 | "SELECT {DELETED_COLUMNS} FROM repos |
| 435 | WHERE namespace = ? AND deleted_at IS NOT NULL AND fork_of IS NULL |
| 436 | ORDER BY deleted_at DESC LIMIT 200" |
| 437 | )) |
| 438 | .bind(&[namespace.to_lowercase().into()])? |
| 439 | .all() |
| 440 | .await? |
| 441 | .results::<DeletedRow>()? |
| 442 | .into_iter() |
| 443 | .map(DeletedRepo::from) |
| 444 | .collect()) |
| 445 | } |
| 446 | |
| 447 | /// The deleted repository at `path`, if that is what holds it. |
| 448 | pub async fn deleted_at(&self, path: &RepoPath) -> Result<Option<DeletedRepo>> { |
| 449 | Ok(self |
| 450 | .db |
| 451 | .prepare(format!( |
| 452 | "SELECT {DELETED_COLUMNS} FROM repos |
| 453 | WHERE namespace = ? AND name = ? AND deleted_at IS NOT NULL AND fork_of IS NULL" |
| 454 | )) |
| 455 | .bind(&[ |
| 456 | path.namespace.to_lowercase().into(), |
| 457 | path.name.to_lowercase().into(), |
| 458 | ])? |
| 459 | .first::<DeletedRow>(None) |
| 460 | .await? |
| 461 | .map(DeletedRepo::from)) |
| 462 | } |
| 463 | |
| 464 | /// Deleted repositories whose time to be restored has passed. |
| 465 | pub async fn due(&self, now: &str, limit: u32) -> Result<Vec<DeletedRepo>> { |
| 466 | Ok(self |
| 467 | .db |
| 468 | .prepare(format!( |
| 469 | "SELECT {DELETED_COLUMNS} FROM repos |
| 470 | WHERE deleted_at IS NOT NULL AND purge_after <= ? AND fork_of IS NULL |
| 471 | ORDER BY purge_after LIMIT ?" |
| 472 | )) |
| 473 | .bind(&[now.into(), limit.into()])? |
| 474 | .all() |
| 475 | .await? |
| 476 | .results::<DeletedRow>()? |
| 477 | .into_iter() |
| 478 | .map(DeletedRepo::from) |
| 479 | .collect()) |
| 480 | } |
| 481 | |
| 482 | /// Every deleted repository left in a workspace, for when the |
| 483 | /// workspace itself is deleted. |
| 484 | pub async fn deleted_ids_in(&self, namespace: &str) -> Result<Vec<DeletedRepo>> { |
| 485 | self.deleted_in(namespace).await |
| 486 | } |
| 487 | |
| 488 | /// The git store keys of a repository and of its working copies. |
| 489 | pub async fn store_keys(&self, id: &str) -> Result<Vec<String>> { |
| 490 | #[derive(Deserialize)] |
| 491 | struct Row { |
| 492 | namespace: String, |
| 493 | name: String, |
| 494 | #[serde(default)] |
| 495 | store: Option<String>, |
| 496 | } |
| 497 | Ok(self |
| 498 | .db |
| 499 | .prepare("SELECT namespace, name, store FROM repos WHERE id = ?1 OR fork_of = ?1") |
| 500 | .bind(&[id.into()])? |
| 501 | .all() |
| 502 | .await? |
| 503 | .results::<Row>()? |
| 504 | .into_iter() |
| 505 | .map(|row| row.store.unwrap_or_else(|| format!("{}--{}", row.namespace, row.name))) |
| 506 | .collect()) |
| 507 | } |
| 508 | |
| 509 | /// Forgets a purged repository: its rows, its working copies' rows and |
| 510 | /// every redirect to it. |
| 511 | pub async fn erase(&self, id: &str) -> Result<()> { |
| 512 | self.db |
| 513 | .batch(vec![ |
| 514 | self.db.prepare("DELETE FROM repos WHERE fork_of = ?1").bind(&[id.into()])?, |
| 515 | self.db.prepare("DELETE FROM repos WHERE id = ?1").bind(&[id.into()])?, |
| 516 | self.db |
| 517 | .prepare("DELETE FROM repo_redirects WHERE repo_id = ?1") |
| 518 | .bind(&[id.into()])?, |
| 519 | self.db |
| 520 | .prepare("DELETE FROM branch_redirects WHERE repo_id = ?1") |
| 521 | .bind(&[id.into()])?, |
| 522 | ]) |
| 523 | .await?; |
| 524 | Ok(()) |
| 525 | } |
| 526 | |
| 527 | /// Renames a repository, keeping its old path as a redirect. Any |
| 528 | /// redirect held by the new path gives way. |
| 529 | pub async fn rename(&self, repo: &Repo, name: &str) -> Result<()> { |
| 530 | let now = rfc3339(now_ms()); |
| 531 | self.db |
| 532 | .batch(vec![ |
| 533 | self.db |
| 534 | .prepare("UPDATE repos SET name = ? WHERE id = ? AND name = ?") |
| 535 | .bind(&[name.into(), repo.id.as_str().into(), repo.name.as_str().into()])?, |
| 536 | self.db |
| 537 | .prepare("DELETE FROM repo_redirects WHERE namespace = ? AND name = ?") |
| 538 | .bind(&[repo.namespace.as_str().into(), name.into()])?, |
| 539 | self.db |
| 540 | .prepare( |
| 541 | "INSERT OR REPLACE INTO repo_redirects (namespace, name, repo_id, created_at) |
| 542 | VALUES (?, ?, ?, ?)", |
| 543 | ) |
| 544 | .bind(&[ |
| 545 | repo.namespace.as_str().into(), |
| 546 | repo.name.as_str().into(), |
| 547 | repo.id.as_str().into(), |
| 548 | now.as_str().into(), |
| 549 | ])?, |
| 550 | ]) |
| 551 | .await?; |
| 552 | Ok(()) |
| 553 | } |
| 554 | |
| 555 | pub async fn set_archived(&self, id: &str, at: Option<&str>) -> Result<()> { |
| 556 | self.db |
| 557 | .prepare("UPDATE repos SET archived_at = ? WHERE id = ?") |
| 558 | .bind(&[at.map_or(JsValue::NULL, JsValue::from), id.into()])? |
| 559 | .run() |
| 560 | .await?; |
| 561 | Ok(()) |
| 562 | } |
| 563 | |
| 564 | /// Makes a repository and its working copies public or private. |
| 565 | pub async fn set_private(&self, id: &str, private: bool) -> Result<()> { |
| 566 | self.db |
| 567 | .prepare("UPDATE repos SET is_private = ?1 WHERE id = ?2 OR fork_of = ?2") |
| 568 | .bind(&[u32::from(private).into(), id.into()])? |
| 569 | .run() |
| 570 | .await?; |
| 571 | Ok(()) |
| 572 | } |
| 573 | |
| 574 | pub async fn set_default_branch(&self, id: &str, branch: &str) -> Result<()> { |
| 575 | self.db |
| 576 | .prepare("UPDATE repos SET default_branch = ? WHERE id = ?") |
| 577 | .bind(&[branch.into(), id.into()])? |
| 578 | .run() |
| 579 | .await?; |
| 580 | Ok(()) |
| 581 | } |
| 582 | |
| 583 | /// Working copies of a repository, newest first, at most `limit`. |
| 584 | pub async fn forks_of(&self, id: &str, limit: u32) -> Result<Vec<Repo>> { |
| 585 | let rows = self |
| 586 | .db |
| 587 | .prepare( |
| 588 | "SELECT * FROM repos WHERE fork_of = ? AND deleted_at IS NULL AND retired_at IS NULL |
| 589 | ORDER BY created_at DESC LIMIT ?", |
| 590 | ) |
| 591 | .bind(&[id.into(), limit.into()])? |
| 592 | .all() |
| 593 | .await? |
| 594 | .results::<crate::registry::RepoRow>()?; |
| 595 | Ok(rows.into_iter().map(Repo::from).collect()) |
| 596 | } |
| 597 | |
| 598 | /// Records that `from` is now called `to`. Redirects that pointed at |
| 599 | /// `from` point at `to`, and one held by `to` itself ends. |
| 600 | pub async fn add_branch_redirect(&self, repo_id: &str, from: &str, to: &str) -> Result<()> { |
| 601 | let now = rfc3339(now_ms()); |
| 602 | self.db |
| 603 | .batch(vec![ |
| 604 | self.db |
| 605 | .prepare("DELETE FROM branch_redirects WHERE repo_id = ? AND branch = ?") |
| 606 | .bind(&[repo_id.into(), to.into()])?, |
| 607 | self.db |
| 608 | .prepare("UPDATE branch_redirects SET now = ? WHERE repo_id = ? AND now = ?") |
| 609 | .bind(&[to.into(), repo_id.into(), from.into()])?, |
| 610 | self.db |
| 611 | .prepare( |
| 612 | "INSERT OR REPLACE INTO branch_redirects (repo_id, branch, now, created_at) |
| 613 | VALUES (?, ?, ?, ?)", |
| 614 | ) |
| 615 | .bind(&[repo_id.into(), from.into(), to.into(), now.as_str().into()])?, |
| 616 | ]) |
| 617 | .await?; |
| 618 | Ok(()) |
| 619 | } |
| 620 | |
| 621 | pub async fn branch_redirect(&self, repo_id: &str, branch: &str) -> Result<Option<String>> { |
| 622 | #[derive(Deserialize)] |
| 623 | struct Row { |
| 624 | now: String, |
| 625 | } |
| 626 | Ok(self |
| 627 | .db |
| 628 | .prepare("SELECT now FROM branch_redirects WHERE repo_id = ? AND branch = ?") |
| 629 | .bind(&[repo_id.into(), branch.into()])? |
| 630 | .first::<Row>(None) |
| 631 | .await? |
| 632 | .map(|row| row.now)) |
| 633 | } |
| 634 | |
| 635 | /// Whether a repository is archived or deleted; unknown is deleted. |
| 636 | pub async fn status(&self, id: &str) -> Result<RepoStatus> { |
| 637 | #[derive(Deserialize)] |
| 638 | struct Row { |
| 639 | #[serde(default)] |
| 640 | archived_at: Option<String>, |
| 641 | #[serde(default)] |
| 642 | deleted_at: Option<String>, |
| 643 | } |
| 644 | Ok(self |
| 645 | .db |
| 646 | .prepare("SELECT archived_at, deleted_at FROM repos WHERE id = ?") |
| 647 | .bind(&[id.into()])? |
| 648 | .first::<Row>(None) |
| 649 | .await? |
| 650 | .map_or( |
| 651 | RepoStatus { |
| 652 | archived: false, |
| 653 | deleted: true, |
| 654 | }, |
| 655 | |row| RepoStatus { |
| 656 | archived: row.archived_at.is_some(), |
| 657 | deleted: row.deleted_at.is_some(), |
| 658 | }, |
| 659 | )) |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | /// An audit entry for something done to a repository. |
| 664 | fn entry(actor: AuditActor, action: &str, surface: Option<Surface>, path: &RepoPath, rule: &str, message: String) -> NewAuditEntry { |
| 665 | NewAuditEntry { |
| 666 | actor, |
| 667 | action: action.to_owned(), |
| 668 | surface: surface.unwrap_or(Surface::Web), |
| 669 | target: AuditTarget { |
| 670 | workspace: path.namespace.clone(), |
| 671 | repo: Some(format!("{}/{}", path.namespace, path.name)), |
| 672 | ..AuditTarget::default() |
| 673 | }, |
| 674 | outcome: AuditOutcome::Allowed, |
| 675 | rule: rule.to_owned(), |
| 676 | result: Some("ok".to_owned()), |
| 677 | message: Some(message), |
| 678 | request_id: new_id("req", now_ms()), |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | /// g1t itself, as the actor of what its schedule does. |
| 683 | fn g1t_actor() -> AuditActor { |
| 684 | AuditActor::system() |
| 685 | } |
| 686 | |
| 687 | fn fail<T>((code, message): Refusal) -> Outcome<T> { |
| 688 | Outcome::fail(code, message) |
| 689 | } |
| 690 | |
| 691 | fn path_of(repo: &Repo) -> RepoPath { |
| 692 | RepoPath { |
| 693 | namespace: repo.namespace.clone(), |
| 694 | name: repo.name.clone(), |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | impl<S: GitStore> Repos<S> { |
| 699 | pub(crate) async fn record(&self, entries: Vec<NewAuditEntry>) { |
| 700 | let recorded: Result<u32> = |
| 701 | g1t_kit::call(&self.events, "audit_record", &RecordAuditArgs { entries }).await; |
| 702 | if let Err(error) = recorded { |
| 703 | worker::console_error!("audit entries not recorded: {error}"); |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | /// The repository at `path` an admin is acting on: found, not a |
| 708 | /// working copy, and the actor allowed `capability` on it (Admin, and |
| 709 | /// for deleting, an owner of its workspace). |
| 710 | async fn owned( |
| 711 | &self, |
| 712 | actor: &User, |
| 713 | path: &RepoPath, |
| 714 | what: &str, |
| 715 | capability: Capability, |
| 716 | ) -> Result<std::result::Result<Repo, Refusal>> { |
| 717 | let viewer = Some(actor.clone()); |
| 718 | let Some(repo) = self.readable(path, &viewer).await? else { |
| 719 | return Ok(Err((FailureCode::NotFound, "Repository not found.".into()))); |
| 720 | }; |
| 721 | if repo.fork_of.is_some() { |
| 722 | return Ok(Err((FailureCode::NotFound, "Repository not found.".into()))); |
| 723 | } |
| 724 | if let Err(refusal) = admin_only(Asker::on(actor, &repo), &repo.namespace, what, capability) { |
| 725 | return Ok(Err(refusal)); |
| 726 | } |
| 727 | Ok(Ok(repo)) |
| 728 | } |
| 729 | |
| 730 | /// `delete`: see `g1t_contracts::repos::DeleteArgs`. |
| 731 | pub(crate) async fn delete(&self, a: DeleteArgs) -> Result<Outcome<DeletedRepo>> { |
| 732 | let repo = match self.owned(&a.actor, &a.path, "delete", Capability::Delete).await? { |
| 733 | Ok(repo) => repo, |
| 734 | Err(refusal) => return Ok(fail(refusal)), |
| 735 | }; |
| 736 | let path = path_of(&repo); |
| 737 | if !confirmed(&path, &a.confirm) { |
| 738 | return Ok(fail(confirm_refusal(&path))); |
| 739 | } |
| 740 | let now = now_ms(); |
| 741 | let at = rfc3339(now); |
| 742 | let purge = purge_after(now); |
| 743 | self.registry |
| 744 | .soft_delete(&repo.id, &a.actor.username, &at, &purge) |
| 745 | .await?; |
| 746 | self.publish(NewEvent { |
| 747 | kind: "repo.deleted", |
| 748 | source: SOURCE, |
| 749 | repo_id: Some(repo.id.clone()), |
| 750 | actor: Some(a.actor.id.clone()), |
| 751 | data: RepoDeleted { |
| 752 | repo_id: repo.id.clone(), |
| 753 | namespace: repo.namespace.clone(), |
| 754 | name: repo.name.clone(), |
| 755 | is_private: repo.is_private, |
| 756 | purge_after: purge.clone(), |
| 757 | with_workspace: false, |
| 758 | }, |
| 759 | }) |
| 760 | .await?; |
| 761 | self.record(vec![entry( |
| 762 | AuditActor::of(&a.actor), |
| 763 | "repo.deleted", |
| 764 | a.surface, |
| 765 | &path, |
| 766 | "owner", |
| 767 | format!("Deleted; restorable until {purge}"), |
| 768 | )]) |
| 769 | .await; |
| 770 | Ok(Outcome::Ok(DeletedRepo { |
| 771 | id: repo.id, |
| 772 | namespace: repo.namespace, |
| 773 | name: repo.name, |
| 774 | description: repo.description, |
| 775 | is_private: repo.is_private, |
| 776 | deleted_at: at, |
| 777 | deleted_by: a.actor.username, |
| 778 | purge_after: purge, |
| 779 | })) |
| 780 | } |
| 781 | |
| 782 | /// `deleted`: see `g1t_contracts::repos::DeletedArgs`. |
| 783 | pub(crate) async fn deleted(&self, a: DeletedArgs) -> Result<Vec<DeletedRepo>> { |
| 784 | let namespace = a.namespace.to_lowercase(); |
| 785 | let owner = a |
| 786 | .viewer |
| 787 | .as_ref() |
| 788 | .is_some_and(|user| user.role_in(&namespace) == Some(Role::Owner)); |
| 789 | if !owner { |
| 790 | return Ok(Vec::new()); |
| 791 | } |
| 792 | self.registry.deleted_in(&namespace).await |
| 793 | } |
| 794 | |
| 795 | /// The deleted repository an owner is acting on. |
| 796 | async fn owned_deleted( |
| 797 | &self, |
| 798 | actor: &User, |
| 799 | path: &RepoPath, |
| 800 | what: &str, |
| 801 | ) -> Result<std::result::Result<DeletedRepo, Refusal>> { |
| 802 | if let Err(refusal) = owner_only(Asker::of(actor, &path.namespace), &path.namespace.to_lowercase(), what) { |
| 803 | return Ok(Err(refusal)); |
| 804 | } |
| 805 | Ok(match self.registry.deleted_at(path).await? { |
| 806 | Some(deleted) => Ok(deleted), |
| 807 | None => Err(( |
| 808 | FailureCode::NotFound, |
| 809 | format!( |
| 810 | "{}/{} is not among the workspace's recently deleted repositories.", |
| 811 | path.namespace, path.name |
| 812 | ), |
| 813 | )), |
| 814 | }) |
| 815 | } |
| 816 | |
| 817 | /// `restore`: see `g1t_contracts::repos::DeletedRepoArgs`. |
| 818 | pub(crate) async fn restore(&self, a: DeletedRepoArgs) -> Result<Outcome<Repo>> { |
| 819 | let deleted = match self.owned_deleted(&a.actor, &a.path, "restore").await? { |
| 820 | Ok(deleted) => deleted, |
| 821 | Err(refusal) => return Ok(fail(refusal)), |
| 822 | }; |
| 823 | let deleted_state = state( |
| 824 | None, |
| 825 | Some((&deleted.deleted_at, &deleted.purge_after)), |
| 826 | &rfc3339(now_ms()), |
| 827 | ); |
| 828 | if deleted_state == State::Due { |
| 829 | return Ok(Outcome::fail( |
| 830 | FailureCode::Conflict, |
| 831 | format!("{}/{} is being purged and can no longer be restored.", deleted.namespace, deleted.name), |
| 832 | )); |
| 833 | } |
| 834 | self.registry.undelete(&deleted.id).await?; |
| 835 | let Some(repo) = self.registry.by_id(&deleted.id).await? else { |
| 836 | return Ok(not_found()); |
| 837 | }; |
| 838 | self.publish(NewEvent { |
| 839 | kind: "repo.restored", |
| 840 | source: SOURCE, |
| 841 | repo_id: Some(repo.id.clone()), |
| 842 | actor: Some(a.actor.id.clone()), |
| 843 | data: RepoRestored { |
| 844 | repo_id: repo.id.clone(), |
| 845 | namespace: repo.namespace.clone(), |
| 846 | name: repo.name.clone(), |
| 847 | is_private: repo.is_private, |
| 848 | with_workspace: false, |
| 849 | }, |
| 850 | }) |
| 851 | .await?; |
| 852 | self.record(vec![entry( |
| 853 | AuditActor::of(&a.actor), |
| 854 | "repo.restored", |
| 855 | a.surface, |
| 856 | &path_of(&repo), |
| 857 | "owner", |
| 858 | format!("Restored; deleted by {} at {}", deleted.deleted_by, deleted.deleted_at), |
| 859 | )]) |
| 860 | .await; |
| 861 | Ok(Outcome::Ok(repo)) |
| 862 | } |
| 863 | |
| 864 | /// `purge`: see `g1t_contracts::repos::DeletedRepoArgs`. |
| 865 | pub(crate) async fn purge(&self, a: DeletedRepoArgs) -> Result<Outcome<bool>> { |
| 866 | let deleted = match self.owned_deleted(&a.actor, &a.path, "permanently delete").await? { |
| 867 | Ok(deleted) => deleted, |
| 868 | Err(refusal) => return Ok(fail(refusal)), |
| 869 | }; |
| 870 | let path = RepoPath { |
| 871 | namespace: deleted.namespace.clone(), |
| 872 | name: deleted.name.clone(), |
| 873 | }; |
| 874 | if !confirmed(&path, a.confirm.as_deref().unwrap_or_default()) { |
| 875 | return Ok(fail(confirm_refusal(&path))); |
| 876 | } |
| 877 | self.purge_now(&deleted, Some(&a.actor.id)).await?; |
| 878 | self.record(vec![entry( |
| 879 | AuditActor::of(&a.actor), |
| 880 | "repo.purged", |
| 881 | a.surface, |
| 882 | &path, |
| 883 | "owner", |
| 884 | "Permanently deleted, with its git data".to_owned(), |
| 885 | )]) |
| 886 | .await; |
| 887 | Ok(Outcome::Ok(true)) |
| 888 | } |
| 889 | |
| 890 | /// Removes a deleted repository for good: git data first, so a failure |
| 891 | /// leaves it to the next sweep, then its rows; then says so. |
| 892 | async fn purge_now(&self, deleted: &DeletedRepo, actor: Option<&str>) -> Result<()> { |
| 893 | for key in self.registry.store_keys(&deleted.id).await? { |
| 894 | self.store.delete(&key).await?; |
| 895 | } |
| 896 | self.registry.erase(&deleted.id).await?; |
| 897 | // Who had access to it goes with it. |
| 898 | if let Some(identity) = &self.identity { |
| 899 | let forgotten: Result<bool> = g1t_kit::call( |
| 900 | identity, |
| 901 | "forget_repo_access", |
| 902 | &g1t_contracts::access::ForgetRepoAccessArgs { |
| 903 | repo_id: deleted.id.clone(), |
| 904 | }, |
| 905 | ) |
| 906 | .await; |
| 907 | if let Err(error) = forgotten { |
| 908 | worker::console_error!("access to {} not forgotten: {error}", deleted.id); |
| 909 | } |
| 910 | } |
| 911 | self.publish(NewEvent { |
| 912 | kind: "repo.purged", |
| 913 | source: SOURCE, |
| 914 | repo_id: Some(deleted.id.clone()), |
| 915 | actor: actor.map(str::to_owned), |
| 916 | data: RepoPurged { |
| 917 | repo_id: deleted.id.clone(), |
| 918 | namespace: deleted.namespace.clone(), |
| 919 | name: deleted.name.clone(), |
| 920 | }, |
| 921 | }) |
| 922 | .await |
| 923 | } |
| 924 | |
| 925 | /// `purge_due`: see `g1t_contracts::repos::PurgeDueArgs`. |
| 926 | pub(crate) async fn purge_due(&self, a: PurgeDueArgs) -> Result<u32> { |
| 927 | let limit = a.limit.unwrap_or(PURGES_PER_SWEEP).clamp(1, 100); |
| 928 | let due = self.registry.due(&rfc3339(now_ms()), limit).await?; |
| 929 | let mut purged = 0; |
| 930 | for deleted in due { |
| 931 | match self.purge_now(&deleted, None).await { |
| 932 | Ok(()) => { |
| 933 | purged += 1; |
| 934 | let path = RepoPath { |
| 935 | namespace: deleted.namespace.clone(), |
| 936 | name: deleted.name.clone(), |
| 937 | }; |
| 938 | self.record(vec![entry( |
| 939 | g1t_actor(), |
| 940 | "repo.purged", |
| 941 | None, |
| 942 | &path, |
| 943 | "schedule", |
| 944 | format!("Purged {RESTORE_DAYS} days after {} deleted it", deleted.deleted_by), |
| 945 | )]) |
| 946 | .await; |
| 947 | } |
| 948 | Err(error) => worker::console_error!("{} not purged: {error}", deleted.id), |
| 949 | } |
| 950 | } |
| 951 | Ok(purged) |
| 952 | } |
| 953 | |
| 954 | /// `workspace.deleting`: every live repository of the workspace is |
| 955 | /// deleted with it, marked so its restore brings back exactly these, |
| 956 | /// and `repo.deleted` (with `with_workspace`) tells services to stop |
| 957 | /// what runs for each and hide it. They are purged with the workspace, |
| 958 | /// or by the sweep at the same `purge_after`. Never for a protected |
| 959 | /// workspace, whoever published it. |
| 960 | pub(crate) async fn delete_with_workspace(&self, deleting: &WorkspaceDeleting, protected: &[String]) -> Result<()> { |
| 961 | let namespace = deleting.slug.to_lowercase(); |
| 962 | if let Err(why) = may_go_with_workspace(&namespace, protected) { |
| 963 | worker::console_error!("workspace.deleting for {namespace} ignored: {why}"); |
| 964 | return Ok(()); |
| 965 | } |
| 966 | let marked = self |
| 967 | .registry |
| 968 | .delete_with_workspace( |
| 969 | &namespace, |
| 970 | &deleting.workspace_id, |
| 971 | &deleting.by, |
| 972 | &rfc3339(now_ms()), |
| 973 | &deleting.purge_after, |
| 974 | ) |
| 975 | .await?; |
| 976 | for repo in marked { |
| 977 | self.publish(NewEvent { |
| 978 | kind: "repo.deleted", |
| 979 | source: SOURCE, |
| 980 | repo_id: Some(repo.id.clone()), |
| 981 | actor: None, |
| 982 | data: RepoDeleted { |
| 983 | repo_id: repo.id.clone(), |
| 984 | namespace: repo.namespace.clone(), |
| 985 | name: repo.name.clone(), |
| 986 | is_private: repo.is_private, |
| 987 | purge_after: repo.purge_after.clone(), |
| 988 | with_workspace: true, |
| 989 | }, |
| 990 | }) |
| 991 | .await?; |
| 992 | } |
| 993 | Ok(()) |
| 994 | } |
| 995 | |
| 996 | /// `workspace.restored`: the repositories deleted with the workspace |
| 997 | /// come back, and `repo.restored` (with `with_workspace`) says so for |
| 998 | /// each. Ones deleted on their own before stay deleted. |
| 999 | pub(crate) async fn restore_with_workspace(&self, restored: &WorkspaceRestored) -> Result<()> { |
| 1000 | let marked = self.registry.deleted_with(&restored.workspace_id).await?; |
| 1001 | self.registry.undelete_with_workspace(&restored.workspace_id).await?; |
| 1002 | for deleted in marked { |
| 1003 | let Some(repo) = self.registry.by_id(&deleted.id).await? else { |
| 1004 | continue; |
| 1005 | }; |
| 1006 | self.publish(NewEvent { |
| 1007 | kind: "repo.restored", |
| 1008 | source: SOURCE, |
| 1009 | repo_id: Some(repo.id.clone()), |
| 1010 | actor: None, |
| 1011 | data: RepoRestored { |
| 1012 | repo_id: repo.id.clone(), |
| 1013 | namespace: repo.namespace.clone(), |
| 1014 | name: repo.name.clone(), |
| 1015 | is_private: repo.is_private, |
| 1016 | with_workspace: true, |
| 1017 | }, |
| 1018 | }) |
| 1019 | .await?; |
| 1020 | } |
| 1021 | Ok(()) |
| 1022 | } |
| 1023 | |
| 1024 | /// `workspace.deleted`: the workspace is purged, and every repository |
| 1025 | /// it had goes with it: those deleted with it, those deleted before, |
| 1026 | /// and any still live (a `workspace.deleting` that never arrived). |
| 1027 | pub(crate) async fn purge_workspace(&self, deleted: &WorkspaceDeleted, protected: &[String]) -> Result<()> { |
| 1028 | let namespace = deleted.slug.to_lowercase(); |
| 1029 | if let Err(why) = may_go_with_workspace(&namespace, protected) { |
| 1030 | worker::console_error!("workspace.deleted for {namespace} ignored: {why}"); |
| 1031 | return Ok(()); |
| 1032 | } |
| 1033 | let now = rfc3339(now_ms()); |
| 1034 | self.registry |
| 1035 | .delete_with_workspace(&namespace, &deleted.workspace_id, "g1t", &now, &now) |
| 1036 | .await?; |
| 1037 | // A page at a time; one that fails is left to the hourly sweep. |
| 1038 | loop { |
| 1039 | let page = self.registry.deleted_ids_in(&namespace).await?; |
| 1040 | let mut purged = 0; |
| 1041 | for repo in &page { |
| 1042 | match self.purge_now(repo, None).await { |
| 1043 | Ok(()) => purged += 1, |
| 1044 | Err(error) => worker::console_error!("{} not purged with its workspace: {error}", repo.id), |
| 1045 | } |
| 1046 | } |
| 1047 | if purged == 0 { |
| 1048 | break; |
| 1049 | } |
| 1050 | } |
| 1051 | Ok(()) |
| 1052 | } |
| 1053 | |
| 1054 | /// `rename`: see `g1t_contracts::repos::RenameArgs`. |
| 1055 | pub(crate) async fn rename(&self, a: RenameArgs) -> Result<Outcome<Repo>> { |
| 1056 | let repo = match self.owned(&a.actor, &a.path, "rename", Capability::Administer).await? { |
| 1057 | Ok(repo) => repo, |
| 1058 | Err(refusal) => return Ok(fail(refusal)), |
| 1059 | }; |
| 1060 | let wanted = RepoPath { |
| 1061 | namespace: repo.namespace.clone(), |
| 1062 | name: a.name.trim().to_lowercase(), |
| 1063 | }; |
| 1064 | let held = match self.registry.by_path_any(&wanted).await? { |
| 1065 | None => Held::Free, |
| 1066 | Some((_, None)) => Held::ByRepo, |
| 1067 | Some((_, Some(_))) => Held::ByDeleted, |
| 1068 | }; |
| 1069 | let name = match new_name(&repo.namespace, &repo.name, &a.name, held) { |
| 1070 | Ok(name) => name, |
| 1071 | Err(refusal) => return Ok(fail(refusal)), |
| 1072 | }; |
| 1073 | // The git store key stays what it was; the new path must not |
| 1074 | // change where it is read from. |
| 1075 | let key = store_key(&repo); |
| 1076 | self.registry.rename(&repo, &name).await?; |
| 1077 | let renamed = Repo { |
| 1078 | name: name.clone(), |
| 1079 | ..repo.clone() |
| 1080 | }; |
| 1081 | remember_store(&renamed, &key); |
| 1082 | let from = path_of(&repo); |
| 1083 | let to = path_of(&renamed); |
| 1084 | if let Some(identity) = &self.identity { |
| 1085 | let moved: Result<bool> = g1t_kit::call( |
| 1086 | identity, |
| 1087 | "transfer_repo_scopes", |
| 1088 | &TransferRepoScopesArgs { |
| 1089 | from: from.clone(), |
| 1090 | to: to.clone(), |
| 1091 | }, |
| 1092 | ) |
| 1093 | .await; |
| 1094 | if let Err(error) = moved { |
| 1095 | worker::console_error!("agent scopes for {} not moved: {error}", repo.id); |
| 1096 | } |
| 1097 | } |
| 1098 | self.publish(NewEvent { |
| 1099 | kind: "repo.renamed", |
| 1100 | source: SOURCE, |
| 1101 | repo_id: Some(repo.id.clone()), |
| 1102 | actor: Some(a.actor.id.clone()), |
| 1103 | data: RepoRenamed { |
| 1104 | repo_id: repo.id.clone(), |
| 1105 | namespace: repo.namespace.clone(), |
| 1106 | from: repo.name.clone(), |
| 1107 | to: name.clone(), |
| 1108 | }, |
| 1109 | }) |
| 1110 | .await?; |
| 1111 | self.record(vec![entry( |
| 1112 | AuditActor::of(&a.actor), |
| 1113 | "repo.renamed", |
| 1114 | a.surface, |
| 1115 | &to, |
| 1116 | "owner", |
| 1117 | format!("Renamed from {}/{}", from.namespace, from.name), |
| 1118 | )]) |
| 1119 | .await; |
| 1120 | Ok(Outcome::Ok(renamed)) |
| 1121 | } |
| 1122 | |
| 1123 | /// `archive`: see `g1t_contracts::repos::ArchiveArgs`. |
| 1124 | pub(crate) async fn archive(&self, a: ArchiveArgs) -> Result<Outcome<Repo>> { |
| 1125 | let what = if a.archived { "archive" } else { "unarchive" }; |
| 1126 | let repo = match self.owned(&a.actor, &a.path, what, Capability::Administer).await? { |
| 1127 | Ok(repo) => repo, |
| 1128 | Err(refusal) => return Ok(fail(refusal)), |
| 1129 | }; |
| 1130 | if repo.archived() == a.archived { |
| 1131 | return Ok(Outcome::Ok(repo)); |
| 1132 | } |
| 1133 | let at = a.archived.then(|| rfc3339(now_ms())); |
| 1134 | self.registry.set_archived(&repo.id, at.as_deref()).await?; |
| 1135 | let changed = Repo { |
| 1136 | archived_at: at, |
| 1137 | ..repo |
| 1138 | }; |
| 1139 | let kind = if a.archived { "repo.archived" } else { "repo.unarchived" }; |
| 1140 | self.publish(NewEvent { |
| 1141 | kind, |
| 1142 | source: SOURCE, |
| 1143 | repo_id: Some(changed.id.clone()), |
| 1144 | actor: Some(a.actor.id.clone()), |
| 1145 | data: RepoArchived { |
| 1146 | repo_id: changed.id.clone(), |
| 1147 | namespace: changed.namespace.clone(), |
| 1148 | name: changed.name.clone(), |
| 1149 | archived: a.archived, |
| 1150 | }, |
| 1151 | }) |
| 1152 | .await?; |
| 1153 | self.record(vec![entry( |
| 1154 | AuditActor::of(&a.actor), |
| 1155 | kind, |
| 1156 | a.surface, |
| 1157 | &path_of(&changed), |
| 1158 | "owner", |
| 1159 | if a.archived { |
| 1160 | "Archived: read-only".to_owned() |
| 1161 | } else { |
| 1162 | "Unarchived".to_owned() |
| 1163 | }, |
| 1164 | )]) |
| 1165 | .await; |
| 1166 | Ok(Outcome::Ok(changed)) |
| 1167 | } |
| 1168 | |
| 1169 | /// `set_visibility`: see `g1t_contracts::repos::SetVisibilityArgs`. |
| 1170 | pub(crate) async fn set_visibility(&self, a: SetVisibilityArgs) -> Result<Outcome<Repo>> { |
| 1171 | let repo = match self.owned(&a.actor, &a.path, "change the visibility of", Capability::Administer).await? { |
| 1172 | Ok(repo) => repo, |
| 1173 | Err(refusal) => return Ok(fail(refusal)), |
| 1174 | }; |
| 1175 | if !confirmed(&path_of(&repo), &a.confirm) { |
| 1176 | return Ok(fail(confirm_refusal(&path_of(&repo)))); |
| 1177 | } |
| 1178 | self.change_visibility(repo, a.is_private, &a.actor, a.surface).await |
| 1179 | } |
| 1180 | |
| 1181 | /// Makes `repo` public or private, if the workspace's storage allows, |
| 1182 | /// and says so: `repo.updated` and `repo.visibility_changed`. The |
| 1183 | /// caller has checked the actor may. |
| 1184 | pub(crate) async fn change_visibility( |
| 1185 | &self, |
| 1186 | repo: Repo, |
| 1187 | private: bool, |
| 1188 | actor: &User, |
| 1189 | surface: Option<Surface>, |
| 1190 | ) -> Result<Outcome<Repo>> { |
| 1191 | if repo.is_private == private { |
| 1192 | return Ok(Outcome::Ok(repo)); |
| 1193 | } |
| 1194 | let facts = if private { |
| 1195 | VisibilityFacts { |
| 1196 | to_private: true, |
| 1197 | free: git_ops::is_free(self.billing.as_ref(), &repo.namespace).await, |
| 1198 | private_bytes: self.registry.private_bytes(&repo.namespace).await.unwrap_or(0), |
| 1199 | bytes: self.registry.stored_bytes(&repo.id).await?, |
| 1200 | free_private_bytes: self.free_private_bytes, |
| 1201 | } |
| 1202 | } else { |
| 1203 | VisibilityFacts::default() |
| 1204 | }; |
| 1205 | if let Err(refusal) = visibility_check(&repo.namespace, &facts) { |
| 1206 | return Ok(fail(refusal)); |
| 1207 | } |
| 1208 | self.registry.set_private(&repo.id, private).await?; |
| 1209 | let changed = Repo { |
| 1210 | is_private: private, |
| 1211 | ..repo |
| 1212 | }; |
| 1213 | self.publish(NewEvent { |
| 1214 | kind: "repo.updated", |
| 1215 | source: SOURCE, |
| 1216 | repo_id: Some(changed.id.clone()), |
| 1217 | actor: Some(actor.id.clone()), |
| 1218 | data: RepoUpdated { |
| 1219 | repo_id: changed.id.clone(), |
| 1220 | namespace: changed.namespace.clone(), |
| 1221 | name: changed.name.clone(), |
| 1222 | is_private: private, |
| 1223 | visibility_changed: true, |
| 1224 | }, |
| 1225 | }) |
| 1226 | .await?; |
| 1227 | self.publish(NewEvent { |
| 1228 | kind: "repo.visibility_changed", |
| 1229 | source: SOURCE, |
| 1230 | repo_id: Some(changed.id.clone()), |
| 1231 | actor: Some(actor.id.clone()), |
| 1232 | data: RepoVisibilityChanged { |
| 1233 | repo_id: changed.id.clone(), |
| 1234 | is_private: private, |
| 1235 | }, |
| 1236 | }) |
| 1237 | .await?; |
| 1238 | self.record(vec![entry( |
| 1239 | AuditActor::of(actor), |
| 1240 | "repo.visibility_changed", |
| 1241 | surface, |
| 1242 | &path_of(&changed), |
| 1243 | "owner", |
| 1244 | if private { "Made private".to_owned() } else { "Made public".to_owned() }, |
| 1245 | )]) |
| 1246 | .await; |
| 1247 | Ok(Outcome::Ok(changed)) |
| 1248 | } |
| 1249 | |
| 1250 | /// The repository at `path` someone is changing the branches of: |
| 1251 | /// found, not a working copy, the actor allowed `capability` on it |
| 1252 | /// (Push to rename a branch, Administer to change the default), |
| 1253 | /// verified, and not archived. |
| 1254 | async fn writable_by( |
| 1255 | &self, |
| 1256 | actor: &User, |
| 1257 | path: &RepoPath, |
| 1258 | capability: Capability, |
| 1259 | ) -> Result<std::result::Result<Repo, Refusal>> { |
| 1260 | let viewer = Some(actor.clone()); |
| 1261 | let Some(repo) = self.readable(path, &viewer).await? else { |
| 1262 | return Ok(Err((FailureCode::NotFound, "Repository not found.".into()))); |
| 1263 | }; |
| 1264 | if repo.fork_of.is_some() || !crate::registry::can(&repo, &viewer, capability) { |
| 1265 | return Ok(Err(( |
| 1266 | FailureCode::Forbidden, |
| 1267 | access::needs(capability, &format!("{}/{}", repo.namespace, repo.name)), |
| 1268 | ))); |
| 1269 | } |
| 1270 | if !actor.verified { |
| 1271 | return Ok(Err((FailureCode::Forbidden, UNVERIFIED.into()))); |
| 1272 | } |
| 1273 | if let Some(refusal) = archived_refusal(&repo) { |
| 1274 | return Ok(Err(refusal)); |
| 1275 | } |
| 1276 | // Moving between namespaces: wait for it (moves.rs). |
| 1277 | self.unpaused(repo).await |
| 1278 | } |
| 1279 | |
| 1280 | /// `set_default_branch`: see `g1t_contracts::repos::SetDefaultBranchArgs`. |
| 1281 | pub(crate) async fn set_default_branch(&self, a: SetDefaultBranchArgs) -> Result<Outcome<Repo>> { |
| 1282 | let repo = match self.writable_by(&a.actor, &a.path, Capability::Administer).await? { |
| 1283 | Ok(repo) => repo, |
| 1284 | Err(refusal) => return Ok(fail(refusal)), |
| 1285 | }; |
| 1286 | let branch = a.branch.trim().to_owned(); |
| 1287 | if branch == repo.default_branch { |
| 1288 | return Ok(Outcome::Ok(repo)); |
| 1289 | } |
| 1290 | let git = self.store.open(&store_key(&repo)).await?; |
| 1291 | if !git.branches().await?.iter().any(|b| b.name == branch) { |
| 1292 | return Ok(Outcome::fail( |
| 1293 | FailureCode::Invalid, |
| 1294 | format!("There is no branch named {branch}. Push it first."), |
| 1295 | )); |
| 1296 | } |
| 1297 | self.registry.set_default_branch(&repo.id, &branch).await?; |
| 1298 | // HEAD in what git is told follows it. |
| 1299 | self.refs_moved(&repo.id).await; |
| 1300 | let from = repo.default_branch.clone(); |
| 1301 | let changed = Repo { |
| 1302 | default_branch: branch.clone(), |
| 1303 | ..repo |
| 1304 | }; |
| 1305 | self.forks_follow(&changed, &from, &branch, false).await; |
| 1306 | self.publish(NewEvent { |
| 1307 | kind: "repo.default_branch_changed", |
| 1308 | source: SOURCE, |
| 1309 | repo_id: Some(changed.id.clone()), |
| 1310 | actor: Some(a.actor.id.clone()), |
| 1311 | data: RepoDefaultBranchChanged { |
| 1312 | repo_id: changed.id.clone(), |
| 1313 | from: from.clone(), |
| 1314 | to: branch.clone(), |
| 1315 | renamed: false, |
| 1316 | }, |
| 1317 | }) |
| 1318 | .await?; |
| 1319 | self.record(vec![entry( |
| 1320 | AuditActor::of(&a.actor), |
| 1321 | "repo.default_branch_changed", |
| 1322 | a.surface, |
| 1323 | &path_of(&changed), |
| 1324 | "member", |
| 1325 | format!("Default branch changed from {from} to {branch}"), |
| 1326 | )]) |
| 1327 | .await; |
| 1328 | Ok(Outcome::Ok(changed)) |
| 1329 | } |
| 1330 | |
| 1331 | /// `rename_branch`: see `g1t_contracts::repos::RenameBranchArgs`. |
| 1332 | pub(crate) async fn rename_branch(&self, a: RenameBranchArgs) -> Result<Outcome<Repo>> { |
| 1333 | let repo = match self.writable_by(&a.actor, &a.path, Capability::Push).await? { |
| 1334 | Ok(repo) => repo, |
| 1335 | Err(refusal) => return Ok(fail(refusal)), |
| 1336 | }; |
| 1337 | let from = a.from.trim().to_owned(); |
| 1338 | let is_default = from == repo.default_branch; |
| 1339 | if is_default |
| 1340 | && let Err(refusal) = admin_only( |
| 1341 | Asker::on(&a.actor, &repo), |
| 1342 | &repo.namespace, |
| 1343 | "rename the default branch of", |
| 1344 | Capability::Administer, |
| 1345 | ) |
| 1346 | { |
| 1347 | return Ok(fail(refusal)); |
| 1348 | } |
| 1349 | let git = self.store.open(&store_key(&repo)).await?; |
| 1350 | let branches = git.branches().await?; |
| 1351 | let names: Vec<String> = branches.iter().map(|b| b.name.clone()).collect(); |
| 1352 | let to = match branch_rename(&from, &a.to, &names) { |
| 1353 | Ok(to) => to, |
| 1354 | Err(refusal) => return Ok(fail(refusal)), |
| 1355 | }; |
| 1356 | let Some(head) = branches.iter().find(|b| b.name == from).map(|b| b.hash.clone()) else { |
| 1357 | return Ok(not_found()); |
| 1358 | }; |
| 1359 | let access = git.access(Scope::Write).await?; |
| 1360 | let made = land::push_pack(&access, &to, None, &head, EMPTY_PACK.to_vec()).await?; |
| 1361 | self.refs_moved(&repo.id).await; |
| 1362 | if let Err(reason) = made { |
| 1363 | return Ok(Outcome::fail(FailureCode::Conflict, format!("{to} could not be made: {reason}"))); |
| 1364 | } |
| 1365 | // The default moves before the old name goes, so it never names a |
| 1366 | // branch that is not there. |
| 1367 | if is_default { |
| 1368 | self.registry.set_default_branch(&repo.id, &to).await?; |
| 1369 | } |
| 1370 | let removed = land::delete_ref(&access, &from, &head).await; |
| 1371 | self.refs_moved(&repo.id).await; |
| 1372 | if let Err(reason) = removed? { |
| 1373 | worker::console_error!("{from} not removed after renaming it to {to}: {reason}"); |
| 1374 | } |
| 1375 | self.registry.add_branch_redirect(&repo.id, &from, &to).await?; |
| 1376 | let changed = if is_default { |
| 1377 | Repo { |
| 1378 | default_branch: to.clone(), |
| 1379 | ..repo |
| 1380 | } |
| 1381 | } else { |
| 1382 | repo |
| 1383 | }; |
| 1384 | if is_default { |
| 1385 | self.forks_follow(&changed, &from, &to, true).await; |
| 1386 | } |
| 1387 | self.publish(NewEvent { |
| 1388 | kind: "branch.renamed", |
| 1389 | source: SOURCE, |
| 1390 | repo_id: Some(changed.id.clone()), |
| 1391 | actor: Some(a.actor.id.clone()), |
| 1392 | data: BranchRenamed { |
| 1393 | repo_id: changed.id.clone(), |
| 1394 | from: from.clone(), |
| 1395 | to: to.clone(), |
| 1396 | default_branch: is_default, |
| 1397 | }, |
| 1398 | }) |
| 1399 | .await?; |
| 1400 | if is_default { |
| 1401 | self.publish(NewEvent { |
| 1402 | kind: "repo.default_branch_changed", |
| 1403 | source: SOURCE, |
| 1404 | repo_id: Some(changed.id.clone()), |
| 1405 | actor: Some(a.actor.id.clone()), |
| 1406 | data: RepoDefaultBranchChanged { |
| 1407 | repo_id: changed.id.clone(), |
| 1408 | from: from.clone(), |
| 1409 | to: to.clone(), |
| 1410 | renamed: true, |
| 1411 | }, |
| 1412 | }) |
| 1413 | .await?; |
| 1414 | } |
| 1415 | self.record(vec![entry( |
| 1416 | AuditActor::of(&a.actor), |
| 1417 | "branch.renamed", |
| 1418 | a.surface, |
| 1419 | &path_of(&changed), |
| 1420 | if is_default { "owner" } else { "member" }, |
| 1421 | format!("Branch {from} renamed to {to}"), |
| 1422 | )]) |
| 1423 | .await; |
| 1424 | Ok(Outcome::Ok(changed)) |
| 1425 | } |
| 1426 | |
| 1427 | /// Pull requests' working copies name their branch after the default |
| 1428 | /// branch of the repository they came from. When it changes, the |
| 1429 | /// newest of them get a branch of the new name at the same commit (and, |
| 1430 | /// for a rename, lose the old one), so agents and merges find it. |
| 1431 | /// Best effort: a copy that cannot follow is logged and left. |
| 1432 | async fn forks_follow(&self, repo: &Repo, from: &str, to: &str, renamed: bool) { |
| 1433 | let forks = match self.registry.forks_of(&repo.id, FORKS_FOLLOWING).await { |
| 1434 | Ok(forks) => forks, |
| 1435 | Err(error) => { |
| 1436 | worker::console_error!("working copies of {} not listed: {error}", repo.id); |
| 1437 | return; |
| 1438 | } |
| 1439 | }; |
| 1440 | for fork in forks { |
| 1441 | let followed: Result<()> = async { |
| 1442 | let git = self.store.open(&store_key(&fork)).await?; |
| 1443 | let branches = git.branches().await?; |
| 1444 | let Some(head) = branches.iter().find(|b| b.name == from).map(|b| b.hash.clone()) else { |
| 1445 | return Ok(()); |
| 1446 | }; |
| 1447 | let access = git.access(Scope::Write).await?; |
| 1448 | if !branches.iter().any(|b| b.name == to) { |
| 1449 | let made = land::push_pack(&access, to, None, &head, EMPTY_PACK.to_vec()).await; |
| 1450 | self.refs_moved(&fork.id).await; |
| 1451 | if let Err(reason) = made? { |
| 1452 | worker::console_error!("working copy {} did not get {to}: {reason}", fork.id); |
| 1453 | return Ok(()); |
| 1454 | } |
| 1455 | } |
| 1456 | self.registry.set_default_branch(&fork.id, to).await?; |
| 1457 | if renamed { |
| 1458 | let removed = land::delete_ref(&access, from, &head).await; |
| 1459 | self.refs_moved(&fork.id).await; |
| 1460 | if let Err(reason) = removed? { |
| 1461 | worker::console_error!("working copy {} kept {from}: {reason}", fork.id); |
| 1462 | } |
| 1463 | } |
| 1464 | Ok(()) |
| 1465 | } |
| 1466 | .await; |
| 1467 | if let Err(error) = followed { |
| 1468 | worker::console_error!("working copy {} did not follow {from} → {to}: {error}", fork.id); |
| 1469 | } |
| 1470 | } |
| 1471 | } |
| 1472 | |
| 1473 | /// `resolve_branch`: see `g1t_contracts::repos::ResolveBranchArgs`. |
| 1474 | pub(crate) async fn resolve_branch(&self, a: ResolveBranchArgs) -> Result<Option<String>> { |
| 1475 | let Some(now) = self.registry.branch_redirect(&a.repo_id, &a.branch).await? else { |
| 1476 | return Ok(None); |
| 1477 | }; |
| 1478 | // A branch made again under the old name ends the redirect. |
| 1479 | let Some(repo) = self.registry.by_id(&a.repo_id).await? else { |
| 1480 | return Ok(None); |
| 1481 | }; |
| 1482 | let git = self.store.open(&store_key(&repo)).await?; |
| 1483 | let branches = git.branches().await?; |
| 1484 | if branches.iter().any(|b| b.name == a.branch) || !branches.iter().any(|b| b.name == now) { |
| 1485 | return Ok(None); |
| 1486 | } |
| 1487 | Ok(Some(now)) |
| 1488 | } |
| 1489 | |
| 1490 | /// `status_by_id`: see `g1t_contracts::repos::StatusByIdArgs`. |
| 1491 | pub(crate) async fn status_by_id(&self, a: StatusByIdArgs) -> Result<RepoStatus> { |
| 1492 | self.registry.status(&a.id).await |
| 1493 | } |
| 1494 | } |
| 1495 | |
| 1496 | #[cfg(test)] |
| 1497 | mod tests { |
| 1498 | use super::*; |
| 1499 | |
| 1500 | fn owner() -> Asker { |
| 1501 | Asker { |
| 1502 | person: true, |
| 1503 | verified: true, |
| 1504 | role: Some(Role::Owner), |
| 1505 | repo_role: Some(RepoRole::Admin), |
| 1506 | } |
| 1507 | } |
| 1508 | |
| 1509 | fn path() -> RepoPath { |
| 1510 | RepoPath { |
| 1511 | namespace: "acme".into(), |
| 1512 | name: "rocket".into(), |
| 1513 | } |
| 1514 | } |
| 1515 | |
| 1516 | #[test] |
| 1517 | fn only_a_verified_person_who_owns_the_workspace_may() { |
| 1518 | assert!(owner_only(owner(), "acme", "delete").is_ok()); |
| 1519 | let member = Asker { role: Some(Role::Member), ..owner() }; |
| 1520 | let (code, message) = owner_only(member, "acme", "delete").unwrap_err(); |
| 1521 | assert_eq!(code, FailureCode::Forbidden); |
| 1522 | assert_eq!(message, "Only an owner of acme can delete its repositories."); |
| 1523 | assert_eq!(owner_only(Asker { person: false, ..owner() }, "acme", "delete").unwrap_err().0, FailureCode::Forbidden); |
| 1524 | assert_eq!(owner_only(Asker { verified: false, ..owner() }, "acme", "delete").unwrap_err().0, FailureCode::Forbidden); |
| 1525 | // Outside the workspace, a private repository is not there at all. |
| 1526 | assert_eq!(owner_only(Asker { role: None, ..owner() }, "acme", "delete").unwrap_err().0, FailureCode::NotFound); |
| 1527 | } |
| 1528 | |
| 1529 | /// Renaming, archiving and changing visibility take Admin on the |
| 1530 | /// repository, which a direct grant can give; deleting and |
| 1531 | /// transferring still take an owner of the workspace. |
| 1532 | #[test] |
| 1533 | fn admin_on_the_repository_may_administer_but_not_delete() { |
| 1534 | let admin = Asker { role: None, repo_role: Some(RepoRole::Admin), ..owner() }; |
| 1535 | assert!(admin_only(admin, "acme", "rename", Capability::Administer).is_ok()); |
| 1536 | let (code, message) = admin_only(admin, "acme", "delete", Capability::Delete).unwrap_err(); |
| 1537 | assert_eq!(code, FailureCode::Forbidden); |
| 1538 | assert_eq!(message, "Only an owner of acme can delete its repositories."); |
| 1539 | let member_admin = Asker { role: Some(Role::Member), ..admin }; |
| 1540 | assert_eq!(admin_only(member_admin, "acme", "delete", Capability::Delete).unwrap_err().0, FailureCode::Forbidden); |
| 1541 | // Write (the default base permission) cannot rename. |
| 1542 | let writer = Asker { role: Some(Role::Member), repo_role: Some(RepoRole::Write), ..owner() }; |
| 1543 | let (code, message) = admin_only(writer, "acme", "rename", Capability::Administer).unwrap_err(); |
| 1544 | assert_eq!(code, FailureCode::Forbidden); |
| 1545 | assert_eq!(message, "You need the Admin role on a repository of acme to rename it."); |
| 1546 | // Someone who can read a public repository is refused, not told it is missing. |
| 1547 | let reader = Asker { role: None, repo_role: Some(RepoRole::Read), ..owner() }; |
| 1548 | assert_eq!(admin_only(reader, "acme", "archive", Capability::Administer).unwrap_err().0, FailureCode::Forbidden); |
| 1549 | let stranger = Asker { role: None, repo_role: None, ..owner() }; |
| 1550 | assert_eq!(admin_only(stranger, "acme", "archive", Capability::Administer).unwrap_err().0, FailureCode::NotFound); |
| 1551 | assert_eq!(admin_only(Asker { person: false, ..owner() }, "acme", "rename", Capability::Administer).unwrap_err().0, FailureCode::Forbidden); |
| 1552 | } |
| 1553 | |
| 1554 | #[test] |
| 1555 | fn a_workspace_restore_brings_back_only_what_went_with_it() { |
| 1556 | assert!(comes_back_with(Some("wsp_1"), "wsp_1")); |
| 1557 | // Deleted on its own before the workspace was. |
| 1558 | assert!(!comes_back_with(None, "wsp_1")); |
| 1559 | // Went with another workspace (it was transferred since). |
| 1560 | assert!(!comes_back_with(Some("wsp_2"), "wsp_1")); |
| 1561 | } |
| 1562 | |
| 1563 | #[test] |
| 1564 | fn a_protected_workspace_keeps_its_repositories_whatever_is_published() { |
| 1565 | let protected = g1t_contracts::identity::protected_names(None); |
| 1566 | assert_eq!( |
| 1567 | may_go_with_workspace("flagon-io", &protected).unwrap_err(), |
| 1568 | "flagon-io is protected and can never be deleted." |
| 1569 | ); |
| 1570 | assert!(may_go_with_workspace("FLAGON-IO", &protected).is_err()); |
| 1571 | assert!(may_go_with_workspace("acme", &protected).is_ok()); |
| 1572 | let configured = g1t_contracts::identity::protected_names(Some("acme")); |
| 1573 | assert!(may_go_with_workspace("acme", &configured).is_err()); |
| 1574 | } |
| 1575 | |
| 1576 | #[test] |
| 1577 | fn the_full_name_confirms_in_any_case() { |
| 1578 | assert!(confirmed(&path(), "acme/rocket")); |
| 1579 | assert!(confirmed(&path(), " ACME/Rocket ")); |
| 1580 | assert!(!confirmed(&path(), "rocket")); |
| 1581 | assert!(!confirmed(&path(), "")); |
| 1582 | } |
| 1583 | |
| 1584 | #[test] |
| 1585 | fn a_deleted_repository_is_restorable_for_thirty_days_then_due() { |
| 1586 | let deleted_at = 1_790_000_000_000u64; |
| 1587 | let purge = purge_after(deleted_at); |
| 1588 | assert_eq!(purge, rfc3339(deleted_at + 30 * 86_400_000)); |
| 1589 | let day = 86_400_000u64; |
| 1590 | let at = |ms: u64| rfc3339(ms); |
| 1591 | assert_eq!(state(None, None, &at(deleted_at)), State::Active); |
| 1592 | assert_eq!(state(Some("2026-10-01T00:00:00.000Z"), None, &at(deleted_at)), State::Archived); |
| 1593 | let deleted = Some((at(deleted_at), purge.clone())); |
| 1594 | let deleted = deleted.as_ref().map(|(a, b)| (a.as_str(), b.as_str())); |
| 1595 | assert_eq!(state(None, deleted, &at(deleted_at + day)), State::Deleted); |
| 1596 | assert_eq!(state(None, deleted, &at(deleted_at + 30 * day - 1)), State::Deleted); |
| 1597 | assert_eq!(state(None, deleted, &at(deleted_at + 30 * day)), State::Due); |
| 1598 | // Archived and then deleted: deleted is what counts. |
| 1599 | assert_eq!(state(Some("x"), deleted, &at(deleted_at + day)), State::Deleted); |
| 1600 | assert!(restorable(&purge, &at(deleted_at + 29 * day))); |
| 1601 | assert!(!restorable(&purge, &at(deleted_at + 31 * day))); |
| 1602 | } |
| 1603 | |
| 1604 | #[test] |
| 1605 | fn a_rename_needs_a_valid_free_name() { |
| 1606 | assert_eq!(new_name("acme", "rocket", " Booster ", Held::Free).unwrap(), "booster"); |
| 1607 | assert_eq!(new_name("acme", "rocket", "rocket", Held::Free).unwrap_err().0, FailureCode::Invalid); |
| 1608 | assert_eq!(new_name("acme", "rocket", "no spaces", Held::Free).unwrap_err().0, FailureCode::Invalid); |
| 1609 | assert_eq!(new_name("acme", "rocket", "x.git", Held::Free).unwrap_err().0, FailureCode::Invalid); |
| 1610 | let (code, message) = new_name("acme", "rocket", "booster", Held::ByRepo).unwrap_err(); |
| 1611 | assert_eq!(code, FailureCode::Conflict); |
| 1612 | assert_eq!(message, "acme already has a repository named booster."); |
| 1613 | let (code, message) = new_name("acme", "rocket", "booster", Held::ByDeleted).unwrap_err(); |
| 1614 | assert_eq!(code, FailureCode::Conflict); |
| 1615 | assert!(message.contains("deleted recently")); |
| 1616 | } |
| 1617 | |
| 1618 | fn repo(archived: bool) -> Repo { |
| 1619 | Repo { |
| 1620 | id: "rep_1".into(), |
| 1621 | namespace: "acme".into(), |
| 1622 | name: "rocket".into(), |
| 1623 | description: None, |
| 1624 | is_private: false, |
| 1625 | owner_id: "usr_1".into(), |
| 1626 | default_branch: "main".into(), |
| 1627 | fork_of: None, |
| 1628 | protected: false, |
| 1629 | created_at: String::new(), |
| 1630 | topics: Vec::new(), |
| 1631 | website: None, |
| 1632 | archived_at: archived.then(|| "2026-10-05T00:00:00.000Z".to_owned()), |
| 1633 | } |
| 1634 | } |
| 1635 | |
| 1636 | #[test] |
| 1637 | fn an_archived_repository_refuses_writes_with_the_reason() { |
| 1638 | assert!(archived_refusal(&repo(false)).is_none()); |
| 1639 | let (code, message) = archived_refusal(&repo(true)).unwrap(); |
| 1640 | assert_eq!(code, FailureCode::Forbidden); |
| 1641 | assert_eq!(message, "acme/rocket is archived, so it is read-only. An owner can unarchive it in its settings."); |
| 1642 | } |
| 1643 | |
| 1644 | #[test] |
| 1645 | fn going_private_on_a_free_workspace_needs_room() { |
| 1646 | let full = VisibilityFacts { |
| 1647 | to_private: true, |
| 1648 | free: true, |
| 1649 | private_bytes: 900_000_000, |
| 1650 | bytes: 200_000_000, |
| 1651 | free_private_bytes: 1_000_000_000, |
| 1652 | }; |
| 1653 | assert_eq!(visibility_check("acme", &full).unwrap_err().0, FailureCode::PaymentRequired); |
| 1654 | assert!(visibility_check("acme", &VisibilityFacts { free: false, ..full }).is_ok()); |
| 1655 | let full = VisibilityFacts { |
| 1656 | to_private: true, |
| 1657 | free: true, |
| 1658 | private_bytes: 900_000_000, |
| 1659 | bytes: 200_000_000, |
| 1660 | free_private_bytes: 1_000_000_000, |
| 1661 | }; |
| 1662 | // Going public is never refused. |
| 1663 | assert!(visibility_check("acme", &VisibilityFacts { to_private: false, ..full }).is_ok()); |
| 1664 | let light = VisibilityFacts { |
| 1665 | to_private: true, |
| 1666 | free: true, |
| 1667 | private_bytes: 1_000, |
| 1668 | bytes: 1_000, |
| 1669 | free_private_bytes: 1_000_000_000, |
| 1670 | }; |
| 1671 | assert!(visibility_check("acme", &light).is_ok()); |
| 1672 | } |
| 1673 | |
| 1674 | #[test] |
| 1675 | fn a_branch_is_renamed_to_a_free_valid_name() { |
| 1676 | let branches = vec!["main".to_owned(), "dev".to_owned()]; |
| 1677 | assert_eq!(branch_rename("main", " trunk ", &branches).unwrap(), "trunk"); |
| 1678 | assert_eq!(branch_rename("nope", "trunk", &branches).unwrap_err().0, FailureCode::NotFound); |
| 1679 | assert_eq!(branch_rename("main", "dev", &branches).unwrap_err().0, FailureCode::Conflict); |
| 1680 | assert_eq!(branch_rename("main", "main", &branches).unwrap_err().0, FailureCode::Invalid); |
| 1681 | assert_eq!(branch_rename("main", "a b", &branches).unwrap_err().0, FailureCode::Invalid); |
| 1682 | assert_eq!(branch_rename("main", "g1t-queue", &branches).unwrap_err().0, FailureCode::Invalid); |
| 1683 | } |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn the_empty_pack_is_well_formed() { |
| 1687 | assert_eq!(EMPTY_PACK.len(), 32); |
| 1688 | assert!(EMPTY_PACK.starts_with(b"PACK\0\0\0\x02\0\0\0\0")); |
| 1689 | } |
| 1690 | } |