Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Fine-grained personal tokens, workspace token rules and approvals in identity | 1 | //! What a personal access token reaches, and the rules a workspace sets for |
| 2 | //! the tokens that reach it. See `g1t_contracts::tokens`. | |
| 3 | //! | |
| 4 | //! **Classic tokens** reach whatever their owner can, narrowed by their | |
| 5 | //! scopes. **Fine-grained tokens** (migration 0034) name one resource owner | |
| 6 | //! (their owner's own account, or one workspace), all, selected or only | |
| 7 | //! public repositories of it, and a level for each permission, stored as | |
| 8 | //! the scopes those give. Migration 0023 had retired a token's reach in | |
| 9 | //! favour of classic tokens only; the owner chose GitHub's model instead, | |
| 10 | //! with both kinds side by side. | |
| 11 | //! | |
| 12 | //! Each time a token is used, [`Identity::apply_reach`] cuts the person it | |
| 13 | //! resolves to down to what it reaches: a fine-grained token keeps only its | |
| 14 | //! resource owner's membership and grants (none while it waits for | |
| 15 | //! approval), and any personal token loses the workspaces whose rules keep | |
| 16 | //! it out (a kind they do not allow, a lifetime past their limit, or an | |
| 17 | //! owner revoking it there). Services then decide as for anyone, and | |
| 18 | //! `access::granted` holds a fine-grained token to its repositories. | |
| 19 | //! | |
| 20 | //! **Approval.** A fine-grained token naming a workspace that asks for | |
| 21 | //! approval starts pending, unless its owner is an owner there. The | |
| 22 | //! workspace's owners hear of it in their inbox (`token.approval_requested`) | |
| 23 | //! and approve or deny it; its owner hears back | |
| 24 | //! (`token.approval_reviewed`). Changing a token's repositories or | |
| 25 | //! permissions asks again. | |
| 26 | ||
| 27 | use std::collections::{BTreeMap, HashMap, HashSet}; | |
| 28 | ||
| 29 | use g1t_contracts::audit::Surface; | |
| 30 | use g1t_contracts::events::{NewEvent, Publish}; | |
| 31 | use g1t_contracts::fine_grained::{self, Access, MAX_LIFETIME_DAYS}; | |
| 32 | use g1t_contracts::identity::{AccessToken, CreatedAccessToken}; | |
| 33 | use g1t_contracts::repos::RepoPath; | |
| 34 | use g1t_contracts::scopes::{FineGrainedReach, RepositorySelection, scopes_text}; | |
| 35 | use g1t_contracts::time::{parse_rfc3339, rfc3339}; | |
| 36 | use g1t_contracts::tokens::*; | |
| 37 | use g1t_contracts::{FailureCode, Outcome, Role, User, Viewer}; | |
| 38 | use g1t_kit::now_ms; | |
| 39 | use serde::{Deserialize, Serialize}; | |
| 40 | use worker::Result; | |
| 41 | use worker::wasm_bindgen::JsValue; | |
| 42 | ||
| 43 | use crate::Identity; | |
| 44 | use crate::security::is_person; | |
| 45 | use crate::tokens::{Grant, Owner}; | |
| 46 | ||
| 47 | const FINE_GRAINED: &str = "fine_grained"; | |
| 48 | const DAY_SECONDS: u64 = 86_400; | |
| 49 | ||
| 50 | /// What a token row says about its reach, read with it when it is used. | |
| 51 | /// Numbers arrive from D1 as floats. | |
| 52 | #[derive(Clone, Debug, Default, Deserialize)] | |
| 53 | pub(crate) struct Facts { | |
| 54 | #[serde(default)] | |
| 55 | created_at: Option<String>, | |
| 56 | #[serde(default)] | |
| 57 | expires_at: Option<String>, | |
| 58 | #[serde(default)] | |
| 59 | kind: Option<String>, | |
| 60 | #[serde(default)] | |
| 61 | owner_workspace_id: Option<String>, | |
| 62 | #[serde(default)] | |
| 63 | repository_selection: Option<String>, | |
| 64 | #[serde(default)] | |
| 65 | status: Option<String>, | |
| 66 | #[serde(default)] | |
| 67 | admin: Option<f64>, | |
| 68 | } | |
| 69 | ||
| 70 | impl Facts { | |
| 71 | fn fine_grained(&self) -> bool { | |
| 72 | self.kind.as_deref() == Some(FINE_GRAINED) | |
| 73 | } | |
| 74 | ||
| 75 | fn lifetime(&self) -> (u64, Option<u64>) { | |
| 76 | let created = self.created_at.as_deref().and_then(parse_rfc3339).unwrap_or(0); | |
| 77 | (created, self.expires_at.as_deref().and_then(parse_rfc3339)) | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | /// What a listed token's row adds, for showing it. | |
| 82 | #[derive(Clone, Debug, Default, Deserialize)] | |
| 83 | pub(crate) struct TokenRowMore { | |
| 84 | #[serde(default)] | |
| 85 | kind: Option<String>, | |
| 86 | #[serde(default)] | |
| 87 | description: Option<String>, | |
| 88 | #[serde(default)] | |
| 89 | admin: Option<f64>, | |
| 90 | #[serde(default)] | |
| 91 | workspace_id: Option<String>, | |
| 92 | #[serde(default)] | |
| 93 | repository_selection: Option<String>, | |
| 94 | #[serde(default)] | |
| 95 | permissions: Option<String>, | |
| 96 | #[serde(default)] | |
| 97 | status: Option<String>, | |
| 98 | #[serde(default)] | |
| 99 | review_reason: Option<String>, | |
| 100 | #[serde(default)] | |
| 101 | owner_workspace: Option<String>, | |
| 102 | } | |
| 103 | ||
| 104 | impl TokenRowMore { | |
| 105 | /// Fills in what it adds to a token's details. Selected repositories | |
| 106 | /// are named later, by [`Identity::name_repositories`]. | |
| 107 | pub(crate) fn describe(&self, info: &mut AccessToken) { | |
| 108 | info.description = self.description.clone(); | |
| 109 | info.admin = self.admin.is_some_and(|admin| admin >= 1.0); | |
| 110 | info.kind = if self.kind.as_deref() == Some(FINE_GRAINED) { | |
| 111 | TokenKind::FineGrained | |
| 112 | } else if self.workspace_id.is_some() { | |
| 113 | TokenKind::Workspace | |
| 114 | } else { | |
| 115 | TokenKind::Classic | |
| 116 | }; | |
| 117 | if info.kind == TokenKind::FineGrained { | |
| 118 | info.fine_grained = Some(FineGrainedDetails { | |
| 119 | workspace: self.owner_workspace.clone(), | |
| 120 | repository_selection: self.repository_selection.as_deref().and_then(RepositorySelection::parse).unwrap_or_default(), | |
| 121 | repositories: Vec::new(), | |
| 122 | permissions: stored_permissions(self.permissions.as_deref()), | |
| 123 | status: TokenStatus::parse(self.status.as_deref().unwrap_or("active")), | |
| 124 | review_reason: self.review_reason.clone(), | |
| 125 | }); | |
| 126 | } | |
| 127 | } | |
| 128 | } | |
| 129 | ||
| 130 | /// A `permissions` column read back. | |
| 131 | fn stored_permissions(text: Option<&str>) -> BTreeMap<String, Access> { | |
| 132 | text.and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default() | |
| 133 | } | |
| 134 | ||
| 135 | /// A workspace whose rules apply to a token, as read for it. | |
| 136 | #[derive(Clone, Debug, Default, Deserialize)] | |
| 137 | struct RuleRow { | |
| 138 | id: String, | |
| 139 | slug: String, | |
| 140 | #[serde(default)] | |
| 141 | allow_classic: Option<f64>, | |
| 142 | #[serde(default)] | |
| 143 | allow_fine_grained: Option<f64>, | |
| 144 | #[serde(default)] | |
| 145 | require_approval: Option<f64>, | |
| 146 | #[serde(default)] | |
| 147 | max_lifetime_days: Option<f64>, | |
| 148 | #[serde(default)] | |
| 149 | forbid_no_expiry: Option<f64>, | |
| 150 | #[serde(default)] | |
| 151 | updated_by: Option<String>, | |
| 152 | #[serde(default)] | |
| 153 | updated_at: Option<String>, | |
| 154 | /// 1 when an owner revoked this token here. | |
| 155 | #[serde(default)] | |
| 156 | revoked: Option<f64>, | |
| 157 | } | |
| 158 | ||
| 159 | impl RuleRow { | |
| 160 | fn policy(&self) -> TokenPolicy { | |
| 161 | let flag = |value: Option<f64>, default: bool| value.map_or(default, |value| value >= 1.0); | |
| 162 | TokenPolicy { | |
| 163 | allow_classic: flag(self.allow_classic, true), | |
| 164 | allow_fine_grained: flag(self.allow_fine_grained, true), | |
| 165 | require_approval: flag(self.require_approval, true), | |
| 166 | max_lifetime_days: self.max_lifetime_days.filter(|days| *days >= 1.0).map(|days| days as u32), | |
| 167 | forbid_no_expiry: flag(self.forbid_no_expiry, false), | |
| 168 | updated_by: self.updated_by.clone(), | |
| 169 | updated_at: self.updated_at.clone(), | |
| 170 | } | |
| 171 | } | |
| 172 | } | |
| 173 | ||
| 174 | /// Why a token does not reach a workspace, as its owners are told; `None` | |
| 175 | /// when it does. `fine_grained` is whether the token is one aimed at this | |
| 176 | /// workspace, with `status`. | |
| 177 | pub(crate) fn blocked_by( | |
| 178 | policy: &TokenPolicy, | |
| 179 | fine_grained: bool, | |
| 180 | status: TokenStatus, | |
| 181 | revoked: bool, | |
| 182 | created_ms: u64, | |
| 183 | expires_ms: Option<u64>, | |
| 184 | ) -> Option<&'static str> { | |
| 185 | if revoked || status == TokenStatus::Revoked { | |
| 186 | return Some("revoked"); | |
| 187 | } | |
| 188 | if fine_grained { | |
| 189 | match status { | |
| 190 | TokenStatus::Pending => return Some("pending approval"), | |
| 191 | TokenStatus::Denied => return Some("denied"), | |
| 192 | _ => {} | |
| 193 | } | |
| 194 | if !policy.allow_fine_grained { | |
| 195 | return Some("fine-grained tokens not allowed"); | |
| 196 | } | |
| 197 | } else if !policy.allow_classic { | |
| 198 | return Some("classic tokens not allowed"); | |
| 199 | } | |
| 200 | if !policy.lifetime_allowed(created_ms, expires_ms) { | |
| 201 | return Some(if expires_ms.is_none() { "never expires" } else { "lasts too long" }); | |
| 202 | } | |
| 203 | None | |
| 204 | } | |
| 205 | ||
| 206 | /// `{"contents": "write"}`, as stored. | |
| 207 | fn permissions_column(permissions: &fine_grained::Permissions) -> String { | |
| 208 | serde_json::to_string(permissions).unwrap_or_else(|_| "{}".to_owned()) | |
| 209 | } | |
| 210 | ||
| 211 | fn text(value: Option<&str>) -> JsValue { | |
| 212 | value.map_or(JsValue::NULL, JsValue::from) | |
| 213 | } | |
| 214 | ||
| 215 | /// `token.approval_requested` and `token.approval_reviewed`: told in the | |
| 216 | /// inbox of the people named in `notify`, with a link (events' inbox.rs). | |
| 217 | #[derive(Serialize)] | |
| 218 | #[serde(rename_all = "camelCase")] | |
| 219 | struct TokenNotice<'a> { | |
| 220 | workspace: &'a str, | |
| 221 | token_id: &'a str, | |
| 222 | token_name: &'a str, | |
| 223 | notify: Vec<String>, | |
| 224 | title: String, | |
| 225 | body: String, | |
| 226 | link: String, | |
| 227 | } | |
| 228 | ||
| 229 | #[derive(Deserialize)] | |
| 230 | struct Owned { | |
| 231 | id: String, | |
| 232 | user_id: Option<String>, | |
| 233 | name: String, | |
| 234 | kind: Option<String>, | |
| 235 | owner_workspace_id: Option<String>, | |
| 236 | status: Option<String>, | |
| 237 | } | |
| 238 | ||
| 239 | impl Identity { | |
| 240 | /// Cuts `user`, resolved from the token `token_id`, down to what the | |
| 241 | /// token reaches. `personal` is whether it is a person's token (not a | |
| 242 | /// workspace's or a job's). See the module docs. | |
| 243 | pub(crate) async fn apply_reach(&self, user: &mut User, token_id: &str, personal: bool, facts: &Facts) -> Result<()> { | |
| 244 | let Some(access) = user.token.as_deref_mut() else { | |
| 245 | return Ok(()); | |
| 246 | }; | |
| 247 | if !personal { | |
| 248 | // A workspace's own token: Write on its repositories, or Admin | |
| 249 | // when an owner gave it that. | |
| 250 | access.admin = facts.admin.is_some_and(|admin| admin >= 1.0); | |
| 251 | return Ok(()); | |
| 252 | } | |
| 253 | let fine = facts.fine_grained(); | |
| 254 | // The workspaces it could reach, with their rules for it. | |
| 255 | let mut slugs: Vec<String> = user.workspaces.iter().map(|membership| membership.slug.clone()).collect(); | |
| 256 | slugs.extend(user.grants.iter().map(|grant| grant.workspace.to_lowercase())); | |
| 257 | slugs.sort(); | |
| 258 | slugs.dedup(); | |
| 259 | if slugs.is_empty() && !fine { | |
| 260 | return Ok(()); | |
| 261 | } | |
| 262 | let rules = self.rules_for(&slugs, token_id).await?; | |
| 263 | let (created, expires) = facts.lifetime(); | |
| 264 | let status = TokenStatus::parse(facts.status.as_deref().unwrap_or("active")); | |
| 265 | let mut keep: HashSet<String> = HashSet::new(); | |
| 266 | let mut owner_slug: Option<String> = None; | |
| 267 | for rule in &rules { | |
| 268 | if fine && facts.owner_workspace_id.as_deref() != Some(rule.id.as_str()) { | |
| 269 | continue; | |
| 270 | } | |
| 271 | if fine { | |
| 272 | owner_slug = Some(rule.slug.clone()); | |
| 273 | } | |
| 274 | let revoked = rule.revoked.is_some_and(|revoked| revoked >= 1.0); | |
| 275 | if blocked_by(&rule.policy(), fine, status, revoked, created, expires).is_none() { | |
| 276 | keep.insert(rule.slug.clone()); | |
| 277 | } | |
| 278 | } | |
| 279 | // Workspaces without a rules row: the defaults, which let a classic | |
| 280 | // token in, and a fine-grained one once it is active. | |
| 281 | for slug in &slugs { | |
| 282 | if rules.iter().any(|rule| &rule.slug == slug) { | |
| 283 | continue; | |
| 284 | } | |
| 285 | if !fine && blocked_by(&TokenPolicy::default(), false, status, false, created, expires).is_none() { | |
| 286 | keep.insert(slug.clone()); | |
| 287 | } | |
| 288 | } | |
| 289 | user.workspaces.retain(|membership| keep.contains(&membership.slug)); | |
| 290 | user.grants.retain(|grant| keep.contains(&grant.workspace.to_lowercase())); | |
| 291 | if fine { | |
| 292 | let selection = facts.repository_selection.as_deref().and_then(RepositorySelection::parse).unwrap_or_default(); | |
| 293 | let reaches = owner_slug.as_ref().is_some_and(|slug| keep.contains(slug)); | |
| 294 | let repo_ids = if reaches && selection == RepositorySelection::Selected { self.token_repo_ids(token_id).await? } else { Vec::new() }; | |
| 295 | if let Some(access) = user.token.as_deref_mut() { | |
| 296 | access.fine_grained = Some(FineGrainedReach { | |
| 297 | workspace: owner_slug, | |
| 298 | // Until it reaches its workspace, public repositories only. | |
| 299 | repositories: if reaches { selection } else { RepositorySelection::Public }, | |
| 300 | repo_ids, | |
| 301 | }); | |
| 302 | } | |
| 303 | } | |
| 304 | Ok(()) | |
| 305 | } | |
| 306 | ||
| 307 | /// The workspaces named by `slugs` that have rules, or that `token_id` | |
| 308 | /// was revoked in, with both. For a fine-grained token, its resource | |
| 309 | /// owner too, whatever its rules. | |
| 310 | async fn rules_for(&self, slugs: &[String], token_id: &str) -> Result<Vec<RuleRow>> { | |
| 311 | let mut binds: Vec<JsValue> = vec![token_id.into()]; | |
| 312 | binds.extend(slugs.iter().map(|slug| JsValue::from(slug.as_str()))); | |
| 313 | let marks = vec!["?"; slugs.len()].join(", "); | |
| 314 | let in_slugs = if slugs.is_empty() { "0".to_owned() } else { format!("w.slug IN ({marks})") }; | |
| 315 | let sql = format!( | |
| 316 | "SELECT w.id, w.slug, p.allow_classic, p.allow_fine_grained, p.require_approval, p.max_lifetime_days, | |
| 317 | p.forbid_no_expiry, p.updated_by, p.updated_at, | |
| 318 | (SELECT 1 FROM token_workspace_revocations r WHERE r.token_id = ?1 AND r.workspace_id = w.id) AS revoked | |
| 319 | FROM workspaces w LEFT JOIN token_policies p ON p.workspace_id = w.id | |
| 320 | WHERE w.deleted_at IS NULL | |
| 321 | AND (({in_slugs}) AND (p.workspace_id IS NOT NULL | |
| 322 | OR EXISTS (SELECT 1 FROM token_workspace_revocations r WHERE r.token_id = ?1 AND r.workspace_id = w.id)) | |
| 323 | OR w.id = (SELECT owner_workspace_id FROM access_tokens WHERE id = ?1))" | |
| 324 | ); | |
| 325 | self.db.prepare(sql).bind(&binds)?.all().await?.results::<RuleRow>() | |
| 326 | } | |
| 327 | ||
| 328 | async fn token_repo_ids(&self, token_id: &str) -> Result<Vec<String>> { | |
| 329 | #[derive(Deserialize)] | |
| 330 | struct Row { | |
| 331 | repo_id: String, | |
| 332 | } | |
| 333 | Ok(self | |
| 334 | .db | |
| 335 | .prepare("SELECT repo_id FROM token_repositories WHERE token_id = ? ORDER BY repo_id") | |
| 336 | .bind(&[token_id.into()])? | |
| 337 | .all() | |
| 338 | .await? | |
| 339 | .results::<Row>()? | |
| 340 | .into_iter() | |
| 341 | .map(|row| row.repo_id) | |
| 342 | .collect()) | |
| 343 | } | |
| 344 | ||
| 345 | /// A workspace's rules for tokens, by slug: the defaults when it has | |
| 346 | /// none. `None` when there is no such workspace. | |
| 347 | async fn policy_of(&self, slug: &str) -> Result<Option<(String, TokenPolicy)>> { | |
| 348 | let row = self | |
| 349 | .db | |
| 350 | .prepare( | |
| 351 | "SELECT w.id, w.slug, p.allow_classic, p.allow_fine_grained, p.require_approval, p.max_lifetime_days, | |
| 352 | p.forbid_no_expiry, p.updated_by, p.updated_at, NULL AS revoked | |
| 353 | FROM workspaces w LEFT JOIN token_policies p ON p.workspace_id = w.id | |
| 354 | WHERE w.slug = ? AND w.deleted_at IS NULL", | |
| 355 | ) | |
| 356 | .bind(&[slug.to_lowercase().into()])? | |
| 357 | .first::<RuleRow>(None) | |
| 358 | .await?; | |
| 359 | Ok(row.map(|row| (row.id.clone(), row.policy()))) | |
| 360 | } | |
| 361 | ||
| 362 | // --- Fine-grained tokens -------------------------------------------------- | |
| 363 | ||
| 364 | /// Repositories as asked for (`owner/name`, or a name in `slug`), as | |
| 365 | /// the person can see them: their ids, or why one cannot be chosen. | |
| 366 | async fn chosen_repositories(&self, user: &User, slug: &str, names: &[String]) -> Result<std::result::Result<Vec<String>, String>> { | |
| 367 | if names.is_empty() { | |
| 368 | return Ok(Err("Choose at least one repository, or all repositories.".to_owned())); | |
| 369 | } | |
| 370 | if names.len() > MAX_SELECTED_REPOSITORIES { | |
| 371 | return Ok(Err(format!("A token can reach at most {MAX_SELECTED_REPOSITORIES} selected repositories."))); | |
| 372 | } | |
| 373 | let mut ids = Vec::new(); | |
| 374 | for name in names { | |
| 375 | let name = name.trim().trim_start_matches('/'); | |
| 376 | let (namespace, repo) = name.split_once('/').unwrap_or((slug, name)); | |
| 377 | if !namespace.eq_ignore_ascii_case(slug) { | |
| 378 | return Ok(Err(format!("{name} is not a repository of {slug}, the token's resource owner."))); | |
| 379 | } | |
| 380 | let path = RepoPath { namespace: slug.to_owned(), name: repo.to_owned() }; | |
| 381 | match self.repo_for(&path, &Some(user.clone())).await? { | |
| 382 | Some(found) => ids.push(found.id), | |
| 383 | None => return Ok(Err(format!("There is no repository {slug}/{repo} that you can see."))), | |
| 384 | } | |
| 385 | } | |
| 386 | ids.sort(); | |
| 387 | ids.dedup(); | |
| 388 | Ok(Ok(ids)) | |
| 389 | } | |
| 390 | ||
| 391 | /// Whether `user` owns the workspace `slug`. | |
| 392 | fn owns(user: &User, slug: &str) -> bool { | |
| 393 | user.role_in(&slug.to_lowercase()) == Some(Role::Owner) | |
| 394 | } | |
| 395 | ||
| 396 | pub async fn create_fine_grained_token(&self, a: CreateFineGrainedTokenArgs) -> Result<Outcome<CreatedAccessToken>> { | |
| 397 | if !is_person(&a.user) || a.user.token.is_some() { | |
| 398 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only a person, signed in on g1t.sh, can make a personal access token.")); | |
| 399 | } | |
| 400 | if !a.user.verified { | |
| 401 | return Ok(Outcome::fail(FailureCode::Forbidden, "Confirm your email address before making a token.")); | |
| 402 | } | |
| 403 | if a.name.trim().is_empty() { | |
| 404 | return Ok(Outcome::fail(FailureCode::Invalid, "Name the token after what will use it.")); | |
| 405 | } | |
| 406 | if a.ttl_seconds < DAY_SECONDS || a.ttl_seconds > u64::from(MAX_LIFETIME_DAYS) * DAY_SECONDS { | |
| 407 | return Ok(Outcome::fail( | |
| 408 | FailureCode::Invalid, | |
| 409 | format!("A fine-grained token lasts between 1 and {MAX_LIFETIME_DAYS} days."), | |
| 410 | )); | |
| 411 | } | |
| 412 | let slug = a.workspace.as_deref().map(|slug| slug.trim().to_lowercase()).filter(|slug| !slug.is_empty()); | |
| 413 | let (permissions, scopes) = match fine_grained::resolve(&a.permissions, slug.is_some()) { | |
| 414 | Ok(resolved) => resolved, | |
| 415 | Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)), | |
| 416 | }; | |
| 417 | if permissions.is_empty() { | |
| 418 | return Ok(Outcome::fail(FailureCode::Invalid, "Give the token at least one permission.")); | |
| 419 | } | |
| 420 | let mut status = TokenStatus::Active; | |
| 421 | let mut workspace_id = None; | |
| 422 | let mut repo_ids = Vec::new(); | |
| 423 | let selection = if slug.is_some() { a.repository_selection } else { RepositorySelection::Public }; | |
| 424 | if let Some(slug) = &slug { | |
| 425 | if !a.user.is_member(slug) { | |
| 426 | return Ok(Outcome::fail(FailureCode::Forbidden, format!("You can only aim a token at a workspace you belong to, and {slug} is not one."))); | |
| 427 | } | |
| 428 | let Some((id, policy)) = self.policy_of(slug).await? else { | |
| 429 | return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found.")); | |
| 430 | }; | |
| 431 | if let Some(refusal) = policy.refusal(slug, TokenKind::FineGrained, Some(a.ttl_seconds)) { | |
| 432 | return Ok(Outcome::fail(FailureCode::Forbidden, refusal)); | |
| 433 | } | |
| 434 | if policy.require_approval && !Self::owns(&a.user, slug) { | |
| 435 | status = TokenStatus::Pending; | |
| 436 | } | |
| 437 | if selection == RepositorySelection::Selected { | |
| 438 | repo_ids = match self.chosen_repositories(&a.user, slug, &a.repositories).await? { | |
| 439 | Ok(ids) => ids, | |
| 440 | Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)), | |
| 441 | }; | |
| 442 | } | |
| 443 | workspace_id = Some(id); | |
| 444 | } | |
| 445 | let grant = Grant { scopes: Some(scopes.clone()) }; | |
| 446 | let mut created = self.mint(Owner::User(&a.user.id), &a.name, Some(a.ttl_seconds), &grant, true).await?; | |
| 447 | let description = a.description.as_deref().map(str::trim).filter(|text| !text.is_empty()).map(|text| text.chars().take(500).collect::<String>()); | |
| 448 | let mut statements = vec![self | |
| 449 | .db | |
| 450 | .prepare( | |
| 451 | "UPDATE access_tokens SET kind = ?, owner_workspace_id = ?, repository_selection = ?, permissions = ?, | |
| 452 | description = ?, status = ? | |
| 453 | WHERE id = ?", | |
| 454 | ) | |
| 455 | .bind(&[ | |
| 456 | FINE_GRAINED.into(), | |
| 457 | text(workspace_id.as_deref()), | |
| 458 | selection.as_str().into(), | |
| 459 | permissions_column(&permissions).into(), | |
| 460 | text(description.as_deref()), | |
| 461 | status.as_str().into(), | |
| 462 | created.info.id.as_str().into(), | |
| 463 | ])?]; | |
| 464 | for repo_id in &repo_ids { | |
| 465 | statements.push( | |
| 466 | self.db | |
| 467 | .prepare("INSERT OR IGNORE INTO token_repositories (token_id, repo_id) VALUES (?, ?)") | |
| 468 | .bind(&[created.info.id.as_str().into(), repo_id.as_str().into()])?, | |
| 469 | ); | |
| 470 | } | |
| 471 | self.db.batch(statements).await?; | |
| 472 | created.info.kind = TokenKind::FineGrained; | |
| 473 | created.info.description = description; | |
| 474 | created.info.fine_grained = Some(FineGrainedDetails { | |
| 475 | workspace: slug.clone(), | |
| 476 | repository_selection: selection, | |
| 477 | repositories: if repo_ids.is_empty() { Vec::new() } else { a.repositories.iter().map(|name| qualified(slug.as_deref(), name)).collect() }, | |
| 478 | permissions, | |
| 479 | status, | |
| 480 | review_reason: None, | |
| 481 | }); | |
| Merge main (membership, two-factor, GitHub repo roles) into tokens | 482 | // In the person's security log and their workspaces' audit logs, as |
| 483 | // a classic token is (tokens.rs). | |
| 484 | self.log_security(&a.user.id, "token_created", Some(&created.info.name), None).await; | |
| 485 | self.audit_account(&a.user, "token.created", &format!("Created fine-grained access token {}", created.info.name)).await; | |
| Fine-grained personal tokens, workspace token rules and approvals in identity | 486 | if let (Some(slug), TokenStatus::Pending) = (&slug, status) { |
| 487 | self.ask_owners(&a.user, slug, &created.info).await?; | |
| 488 | } | |
| 489 | Ok(Outcome::Ok(created)) | |
| 490 | } | |
| 491 | ||
| 492 | pub async fn update_fine_grained_token(&self, a: UpdateFineGrainedTokenArgs) -> Result<Outcome<AccessToken>> { | |
| 493 | if !is_person(&a.user) || a.user.token.is_some() { | |
| 494 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only you, signed in on g1t.sh, can change your tokens.")); | |
| 495 | } | |
| 496 | let Some(found) = self.owned_token(&a.id).await?.filter(|token| token.user_id.as_deref() == Some(a.user.id.as_str()) && token.kind.as_deref() == Some(FINE_GRAINED)) else { | |
| 497 | return Ok(Outcome::fail(FailureCode::NotFound, "No such token.")); | |
| 498 | }; | |
| 499 | let slug = match &found.owner_workspace_id { | |
| 500 | Some(id) => self.slug_of(id).await?, | |
| 501 | None => None, | |
| 502 | }; | |
| 503 | let mut sets: Vec<(&str, JsValue)> = Vec::new(); | |
| 504 | if let Some(name) = a.name.as_deref().map(str::trim).filter(|name| !name.is_empty()) { | |
| 505 | sets.push(("name", name.chars().take(100).collect::<String>().into())); | |
| 506 | } | |
| 507 | if let Some(description) = &a.description { | |
| 508 | let description = description.trim(); | |
| 509 | sets.push(("description", if description.is_empty() { JsValue::NULL } else { description.chars().take(500).collect::<String>().into() })); | |
| 510 | } | |
| 511 | let mut widened = false; | |
| 512 | if let Some(asked) = &a.permissions { | |
| 513 | let (permissions, scopes) = match fine_grained::resolve(asked, found.owner_workspace_id.is_some()) { | |
| 514 | Ok(resolved) => resolved, | |
| 515 | Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)), | |
| 516 | }; | |
| 517 | if permissions.is_empty() { | |
| 518 | return Ok(Outcome::fail(FailureCode::Invalid, "Give the token at least one permission.")); | |
| 519 | } | |
| 520 | sets.push(("permissions", permissions_column(&permissions).into())); | |
| 521 | sets.push(("scopes", scopes_text(&scopes).into())); | |
| 522 | widened = true; | |
| 523 | } | |
| 524 | let mut repo_ids: Option<Vec<String>> = None; | |
| 525 | if let Some(slug) = &slug { | |
| 526 | let selection = a.repository_selection; | |
| 527 | if let Some(selection) = selection { | |
| 528 | sets.push(("repository_selection", selection.as_str().into())); | |
| 529 | widened = true; | |
| 530 | } | |
| 531 | let selected = selection.unwrap_or_default() == RepositorySelection::Selected || (selection.is_none() && a.repositories.is_some()); | |
| 532 | if selected { | |
| 533 | let names = a.repositories.clone().unwrap_or_default(); | |
| 534 | repo_ids = Some(match self.chosen_repositories(&a.user, slug, &names).await? { | |
| 535 | Ok(ids) => ids, | |
| 536 | Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)), | |
| 537 | }); | |
| 538 | widened = true; | |
| 539 | } else if selection.is_some() { | |
| 540 | repo_ids = Some(Vec::new()); | |
| 541 | } | |
| 542 | } | |
| 543 | // Asking for more, of a workspace that approves tokens, asks again. | |
| 544 | let mut ask = false; | |
| 545 | if widened && let Some(slug) = &slug { | |
| 546 | let policy = self.policy_of(slug).await?.map(|(_, policy)| policy).unwrap_or_default(); | |
| 547 | if policy.require_approval && !Self::owns(&a.user, slug) && found.status.as_deref() != Some("revoked") { | |
| 548 | sets.push(("status", TokenStatus::Pending.as_str().into())); | |
| 549 | ask = true; | |
| 550 | } | |
| 551 | } | |
| 552 | let mut statements = Vec::new(); | |
| 553 | if !sets.is_empty() { | |
| 554 | let assignments: Vec<String> = sets.iter().map(|(column, _)| format!("{column} = ?")).collect(); | |
| 555 | let mut binds: Vec<JsValue> = sets.into_iter().map(|(_, value)| value).collect(); | |
| 556 | binds.push(a.id.as_str().into()); | |
| 557 | statements.push(self.db.prepare(format!("UPDATE access_tokens SET {} WHERE id = ?", assignments.join(", "))).bind(&binds)?); | |
| 558 | } | |
| 559 | if let Some(ids) = &repo_ids { | |
| 560 | statements.push(self.db.prepare("DELETE FROM token_repositories WHERE token_id = ?").bind(&[a.id.as_str().into()])?); | |
| 561 | for repo_id in ids { | |
| 562 | statements.push( | |
| 563 | self.db | |
| 564 | .prepare("INSERT OR IGNORE INTO token_repositories (token_id, repo_id) VALUES (?, ?)") | |
| 565 | .bind(&[a.id.as_str().into(), repo_id.as_str().into()])?, | |
| 566 | ); | |
| 567 | } | |
| 568 | } | |
| 569 | if !statements.is_empty() { | |
| 570 | self.db.batch(statements).await?; | |
| 571 | } | |
| 572 | let Some(mut info) = self.token_info(&a.id).await? else { | |
| 573 | return Ok(Outcome::fail(FailureCode::NotFound, "No such token.")); | |
| 574 | }; | |
| 575 | self.name_repositories(std::slice::from_mut(&mut info), &Some(a.user.clone())).await?; | |
| Merge main (membership, two-factor, GitHub repo roles) into tokens | 576 | if widened { |
| 577 | self.log_security(&a.user.id, "token_rescoped", Some(&info.name), None).await; | |
| 578 | self.audit_account(&a.user, "token.rescoped", &format!("Changed the permissions of fine-grained access token {}", info.name)).await; | |
| 579 | } | |
| Fine-grained personal tokens, workspace token rules and approvals in identity | 580 | if ask && let Some(slug) = &slug { |
| 581 | self.ask_owners(&a.user, slug, &info).await?; | |
| 582 | } | |
| 583 | Ok(Outcome::Ok(info)) | |
| 584 | } | |
| 585 | ||
| 586 | async fn owned_token(&self, id: &str) -> Result<Option<Owned>> { | |
| 587 | self.db | |
| 588 | .prepare("SELECT id, user_id, name, kind, owner_workspace_id, status FROM access_tokens WHERE id = ? AND agent_scope IS NULL") | |
| 589 | .bind(&[id.into()])? | |
| 590 | .first::<Owned>(None) | |
| 591 | .await | |
| 592 | } | |
| 593 | ||
| 594 | async fn slug_of(&self, workspace_id: &str) -> Result<Option<String>> { | |
| 595 | self.db | |
| 596 | .prepare("SELECT slug FROM workspaces WHERE id = ? AND deleted_at IS NULL") | |
| 597 | .bind(&[workspace_id.into()])? | |
| 598 | .first::<String>(Some("slug")) | |
| 599 | .await | |
| 600 | } | |
| 601 | ||
| 602 | /// One token's details, as listings show them. | |
| 603 | async fn token_info(&self, id: &str) -> Result<Option<AccessToken>> { | |
| 604 | let row = self | |
| 605 | .db | |
| 606 | .prepare(format!( | |
| 607 | "SELECT {} FROM access_tokens LEFT JOIN users ON users.id = access_tokens.created_by WHERE access_tokens.id = ?", | |
| 608 | crate::tokens::TOKEN_COLUMNS | |
| 609 | )) | |
| 610 | .bind(&[id.into()])? | |
| 611 | .first::<crate::tokens::TokenRow>(None) | |
| 612 | .await?; | |
| 613 | Ok(row.map(Identity::info)) | |
| 614 | } | |
| 615 | ||
| 616 | /// Names the selected repositories of fine-grained tokens, as `viewer` | |
| 617 | /// can see them. | |
| 618 | pub(crate) async fn name_repositories(&self, tokens: &mut [AccessToken], viewer: &Viewer) -> Result<()> { | |
| 619 | let selected: Vec<String> = tokens | |
| 620 | .iter() | |
| 621 | .filter(|token| token.fine_grained.as_ref().is_some_and(|details| details.repository_selection == RepositorySelection::Selected)) | |
| 622 | .map(|token| token.id.clone()) | |
| 623 | .collect(); | |
| 624 | if selected.is_empty() { | |
| 625 | return Ok(()); | |
| 626 | } | |
| 627 | #[derive(Deserialize)] | |
| 628 | struct Row { | |
| 629 | token_id: String, | |
| 630 | repo_id: String, | |
| 631 | } | |
| 632 | let marks = vec!["?"; selected.len()].join(", "); | |
| 633 | let binds: Vec<JsValue> = selected.iter().map(|id| JsValue::from(id.as_str())).collect(); | |
| 634 | let rows = self | |
| 635 | .db | |
| 636 | .prepare(format!("SELECT token_id, repo_id FROM token_repositories WHERE token_id IN ({marks})")) | |
| 637 | .bind(&binds)? | |
| 638 | .all() | |
| 639 | .await? | |
| 640 | .results::<Row>()?; | |
| 641 | let ids: Vec<String> = rows.iter().map(|row| row.repo_id.clone()).collect::<HashSet<_>>().into_iter().collect(); | |
| 642 | let readable: Vec<g1t_contracts::repos::Repo> = if ids.is_empty() { | |
| 643 | Vec::new() | |
| 644 | } else { | |
| 645 | g1t_kit::call(&self.env.service("REPOS")?, "readable", &g1t_contracts::repos::ReadableArgs { ids, viewer: viewer.clone() }).await? | |
| 646 | }; | |
| 647 | let names: HashMap<&str, String> = readable.iter().map(|repo| (repo.id.as_str(), format!("{}/{}", repo.namespace, repo.name))).collect(); | |
| 648 | for token in tokens.iter_mut() { | |
| 649 | if let Some(details) = token.fine_grained.as_mut() { | |
| 650 | details.repositories = rows | |
| 651 | .iter() | |
| 652 | .filter(|row| row.token_id == token.id) | |
| 653 | .filter_map(|row| names.get(row.repo_id.as_str()).cloned()) | |
| 654 | .collect(); | |
| 655 | details.repositories.sort(); | |
| 656 | } | |
| 657 | } | |
| 658 | Ok(()) | |
| 659 | } | |
| 660 | ||
| 661 | // --- A workspace's rules ---------------------------------------------------- | |
| 662 | ||
| 663 | pub async fn get_token_policy(&self, a: GetTokenPolicyArgs) -> Result<Outcome<TokenPolicy>> { | |
| 664 | let slug = a.slug.to_lowercase(); | |
| 665 | if !a.viewer.as_ref().is_some_and(|viewer| viewer.is_member(&slug)) { | |
| 666 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only members can see a workspace's rules for tokens.")); | |
| 667 | } | |
| 668 | Ok(match self.policy_of(&slug).await? { | |
| 669 | Some((_, policy)) => Outcome::Ok(policy), | |
| 670 | None => Outcome::fail(FailureCode::NotFound, "Workspace not found."), | |
| 671 | }) | |
| 672 | } | |
| 673 | ||
| 674 | /// The workspace's id, if `actor` is a person who owns it. | |
| 675 | async fn owner_of(&self, actor: &User, slug: &str) -> Result<Outcome<String>> { | |
| 676 | let slug = slug.to_lowercase(); | |
| 677 | if !is_person(actor) || !Self::owns(actor, &slug) { | |
| 678 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner of the workspace can manage its personal access tokens.")); | |
| 679 | } | |
| 680 | Ok(match self.policy_of(&slug).await? { | |
| 681 | Some((id, _)) => Outcome::Ok(id), | |
| 682 | None => Outcome::fail(FailureCode::NotFound, "Workspace not found."), | |
| 683 | }) | |
| 684 | } | |
| 685 | ||
| 686 | pub async fn set_token_policy(&self, a: SetTokenPolicyArgs) -> Result<Outcome<TokenPolicy>> { | |
| 687 | let slug = a.slug.to_lowercase(); | |
| 688 | let workspace_id = match self.owner_of(&a.actor, &slug).await? { | |
| 689 | Outcome::Ok(id) => id, | |
| 690 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 691 | }; | |
| 692 | let current = self.policy_of(&slug).await?.map(|(_, policy)| policy).unwrap_or_default(); | |
| 693 | if a.max_lifetime_days.is_some_and(|days| days > 3650) { | |
| 694 | return Ok(Outcome::fail(FailureCode::Invalid, "The longest lifetime a workspace can set is 3650 days; leave it empty for no limit.")); | |
| 695 | } | |
| 696 | let policy = TokenPolicy { | |
| 697 | allow_classic: a.allow_classic.unwrap_or(current.allow_classic), | |
| 698 | allow_fine_grained: a.allow_fine_grained.unwrap_or(current.allow_fine_grained), | |
| 699 | require_approval: a.require_approval.unwrap_or(current.require_approval), | |
| 700 | max_lifetime_days: match a.max_lifetime_days { | |
| 701 | Some(0) => None, | |
| 702 | Some(days) => Some(days), | |
| 703 | None => current.max_lifetime_days, | |
| 704 | }, | |
| 705 | forbid_no_expiry: a.forbid_no_expiry.unwrap_or(current.forbid_no_expiry), | |
| 706 | updated_by: Some(a.actor.username.clone()), | |
| 707 | updated_at: Some(rfc3339(now_ms())), | |
| 708 | }; | |
| 709 | self.db | |
| 710 | .prepare( | |
| 711 | "INSERT INTO token_policies (workspace_id, allow_classic, allow_fine_grained, require_approval, max_lifetime_days, | |
| 712 | forbid_no_expiry, updated_by, updated_at) | |
| 713 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) | |
| 714 | ON CONFLICT (workspace_id) DO UPDATE SET allow_classic = ?2, allow_fine_grained = ?3, require_approval = ?4, | |
| 715 | max_lifetime_days = ?5, forbid_no_expiry = ?6, updated_by = ?7, updated_at = ?8", | |
| 716 | ) | |
| 717 | .bind(&[ | |
| 718 | workspace_id.as_str().into(), | |
| 719 | JsValue::from(u8::from(policy.allow_classic)), | |
| 720 | JsValue::from(u8::from(policy.allow_fine_grained)), | |
| 721 | JsValue::from(u8::from(policy.require_approval)), | |
| 722 | policy.max_lifetime_days.map_or(JsValue::NULL, JsValue::from), | |
| 723 | JsValue::from(u8::from(policy.forbid_no_expiry)), | |
| 724 | a.actor.username.as_str().into(), | |
| 725 | text(policy.updated_at.as_deref()), | |
| 726 | ])? | |
| 727 | .run() | |
| 728 | .await?; | |
| 729 | self.audit_workspace(&a.actor, "token.policy_changed", &slug, a.surface.unwrap_or(Surface::Web), describe_policy(&policy)).await; | |
| 730 | Ok(Outcome::Ok(policy)) | |
| 731 | } | |
| 732 | ||
| 733 | // --- Members' tokens ------------------------------------------------------ | |
| 734 | ||
| 735 | pub async fn list_member_tokens(&self, a: ListMemberTokensArgs) -> Result<Outcome<Vec<MemberToken>>> { | |
| 736 | let slug = a.slug.to_lowercase(); | |
| 737 | let workspace_id = match self.owner_of(&a.actor, &slug).await? { | |
| 738 | Outcome::Ok(id) => id, | |
| 739 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 740 | }; | |
| 741 | let policy = self.policy_of(&slug).await?.map(|(_, policy)| policy).unwrap_or_default(); | |
| 742 | #[derive(Deserialize)] | |
| 743 | struct Row { | |
| 744 | owner: String, | |
| 745 | #[serde(default)] | |
| 746 | revoked: Option<f64>, | |
| 747 | #[serde(flatten)] | |
| 748 | token: crate::tokens::TokenRow, | |
| 749 | } | |
| 750 | // Fine-grained tokens naming the workspace, and the classic tokens of | |
| 751 | // its members and outside collaborators that have not expired. | |
| 752 | let rows = self | |
| 753 | .db | |
| 754 | .prepare(format!( | |
| 755 | "SELECT owners.username AS owner, | |
| 756 | (SELECT 1 FROM token_workspace_revocations r WHERE r.token_id = access_tokens.id AND r.workspace_id = ?1) AS revoked, | |
| 757 | {} | |
| 758 | FROM access_tokens | |
| 759 | JOIN users owners ON owners.id = access_tokens.user_id | |
| 760 | LEFT JOIN users ON users.id = access_tokens.created_by | |
| 761 | WHERE access_tokens.agent_scope IS NULL AND access_tokens.workspace_id IS NULL | |
| 762 | AND (access_tokens.expires_at IS NULL OR access_tokens.expires_at > strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) | |
| 763 | AND ( | |
| 764 | (access_tokens.kind = 'fine_grained' AND access_tokens.owner_workspace_id = ?1) | |
| 765 | OR (access_tokens.kind IS NULL AND (access_tokens.expires_at IS NULL OR access_tokens.listed = 1) | |
| 766 | AND (access_tokens.user_id IN (SELECT user_id FROM workspace_members WHERE workspace_id = ?1) | |
| 767 | OR access_tokens.user_id IN (SELECT principal_id FROM repo_grants WHERE workspace_id = ?1 AND principal_kind = 'user'))) | |
| 768 | ) | |
| 769 | ORDER BY access_tokens.id DESC | |
| 770 | LIMIT 500", | |
| 771 | crate::tokens::TOKEN_COLUMNS | |
| 772 | )) | |
| 773 | .bind(&[workspace_id.as_str().into()])? | |
| 774 | .all() | |
| 775 | .await? | |
| 776 | .results::<Row>()?; | |
| 777 | let mut listed: Vec<MemberToken> = Vec::new(); | |
| 778 | let mut infos: Vec<AccessToken> = Vec::new(); | |
| 779 | let mut owners: Vec<(String, bool)> = Vec::new(); | |
| 780 | for row in rows { | |
| 781 | owners.push((row.owner, row.revoked.is_some_and(|revoked| revoked >= 1.0))); | |
| 782 | infos.push(Identity::info(row.token)); | |
| 783 | } | |
| 784 | self.name_repositories(&mut infos, &Some(a.actor.clone())).await?; | |
| 785 | for ((owner, revoked), token) in owners.into_iter().zip(infos) { | |
| 786 | let fine = token.kind == TokenKind::FineGrained; | |
| 787 | let status = token.fine_grained.as_ref().map_or(TokenStatus::Active, |details| details.status); | |
| 788 | if a.status.is_some_and(|wanted| wanted != status) || a.kind.is_some_and(|kind| kind != token.kind) { | |
| 789 | continue; | |
| 790 | } | |
| 791 | let created = parse_rfc3339(&token.created_at).unwrap_or(0); | |
| 792 | let expires = token.expires_at.as_deref().and_then(parse_rfc3339); | |
| 793 | let blocked = blocked_by(&policy, fine, status, revoked, created, expires); | |
| 794 | listed.push(MemberToken { owner, token, reaches: blocked.is_none(), blocked_by: blocked.map(str::to_owned) }); | |
| 795 | } | |
| 796 | Ok(Outcome::Ok(listed)) | |
| 797 | } | |
| 798 | ||
| 799 | /// One member token, as `list_member_tokens` shows it. | |
| 800 | async fn member_token(&self, actor: &User, slug: &str, id: &str) -> Result<Option<MemberToken>> { | |
| 801 | let listed = self | |
| 802 | .list_member_tokens(ListMemberTokensArgs { actor: actor.clone(), slug: slug.to_owned(), status: None, kind: None }) | |
| 803 | .await?; | |
| 804 | Ok(match listed { | |
| 805 | Outcome::Ok(tokens) => tokens.into_iter().find(|member| member.token.id == id), | |
| 806 | Outcome::Fail(_) => None, | |
| 807 | }) | |
| 808 | } | |
| 809 | ||
| 810 | pub async fn review_token_request(&self, a: ReviewTokenRequestArgs) -> Result<Outcome<MemberToken>> { | |
| 811 | let slug = a.slug.to_lowercase(); | |
| 812 | let workspace_id = match self.owner_of(&a.actor, &slug).await? { | |
| 813 | Outcome::Ok(id) => id, | |
| 814 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 815 | }; | |
| 816 | let Some(found) = self.owned_token(&a.id).await?.filter(|token| token.owner_workspace_id.as_deref() == Some(workspace_id.as_str())) else { | |
| 817 | return Ok(Outcome::fail(FailureCode::NotFound, "There is no such token request in this workspace.")); | |
| 818 | }; | |
| 819 | if found.status.as_deref() != Some("pending") { | |
| 820 | return Ok(Outcome::fail(FailureCode::Conflict, "This token is not waiting for approval.")); | |
| 821 | } | |
| 822 | let status = if a.approve { TokenStatus::Active } else { TokenStatus::Denied }; | |
| 823 | let reason = a.reason.as_deref().map(str::trim).filter(|reason| !reason.is_empty()).map(|reason| reason.chars().take(500).collect::<String>()); | |
| 824 | self.db | |
| 825 | .prepare("UPDATE access_tokens SET status = ?, reviewed_by = ?, reviewed_at = ?, review_reason = ? WHERE id = ? AND status = 'pending'") | |
| 826 | .bind(&[ | |
| 827 | status.as_str().into(), | |
| 828 | a.actor.id.as_str().into(), | |
| 829 | rfc3339(now_ms()).into(), | |
| 830 | text(reason.as_deref()), | |
| 831 | a.id.as_str().into(), | |
| 832 | ])? | |
| 833 | .run() | |
| 834 | .await?; | |
| 835 | let owner = match &found.user_id { | |
| 836 | Some(id) => self.usernames_of(std::slice::from_ref(id)).await?.into_iter().next(), | |
| 837 | None => None, | |
| 838 | }; | |
| 839 | let verdict = if a.approve { "approved" } else { "denied" }; | |
| 840 | self.audit_workspace( | |
| 841 | &a.actor, | |
| 842 | if a.approve { "token.approved" } else { "token.denied" }, | |
| 843 | &slug, | |
| 844 | a.surface.unwrap_or(Surface::Web), | |
| 845 | format!( | |
| 846 | "{} the fine-grained token {} of {}{}", | |
| 847 | if a.approve { "Approved" } else { "Denied" }, | |
| 848 | found.name, | |
| 849 | owner.as_deref().unwrap_or("a former member"), | |
| 850 | reason.as_deref().map(|reason| format!(": {reason}")).unwrap_or_default() | |
| 851 | ), | |
| 852 | ) | |
| 853 | .await; | |
| 854 | if let Some(owner) = &owner { | |
| 855 | self.notify( | |
| 856 | "token.approval_reviewed", | |
| 857 | &a.actor, | |
| 858 | TokenNotice { | |
| 859 | workspace: &slug, | |
| 860 | token_id: &found.id, | |
| 861 | token_name: &found.name, | |
| 862 | notify: vec![owner.clone()], | |
| 863 | title: format!("Your token {} was {verdict} for {slug}", found.name), | |
| 864 | body: reason.clone().unwrap_or_else(|| { | |
| 865 | if a.approve { "It now reaches the workspace.".to_owned() } else { "It reaches public repositories only.".to_owned() } | |
| 866 | }), | |
| 867 | link: "/settings/tokens".to_owned(), | |
| 868 | }, | |
| 869 | ) | |
| 870 | .await; | |
| 871 | } | |
| 872 | Ok(match self.member_token(&a.actor, &slug, &a.id).await? { | |
| 873 | Some(member) => Outcome::Ok(member), | |
| 874 | None => Outcome::fail(FailureCode::NotFound, "There is no such token request in this workspace."), | |
| 875 | }) | |
| 876 | } | |
| 877 | ||
| 878 | pub async fn revoke_member_token(&self, a: RevokeMemberTokenArgs) -> Result<Outcome<bool>> { | |
| 879 | let slug = a.slug.to_lowercase(); | |
| 880 | let workspace_id = match self.owner_of(&a.actor, &slug).await? { | |
| 881 | Outcome::Ok(id) => id, | |
| 882 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 883 | }; | |
| 884 | let Some(member) = self.member_token(&a.actor, &slug, &a.id).await? else { | |
| 885 | return Ok(Outcome::fail(FailureCode::NotFound, "No token of a member reaches this workspace with that id.")); | |
| 886 | }; | |
| 887 | let reason = a.reason.as_deref().map(str::trim).filter(|reason| !reason.is_empty()).map(|reason| reason.chars().take(500).collect::<String>()); | |
| 888 | let now = rfc3339(now_ms()); | |
| 889 | if member.token.kind == TokenKind::FineGrained { | |
| 890 | self.db | |
| 891 | .prepare("UPDATE access_tokens SET status = 'revoked', reviewed_by = ?, reviewed_at = ?, review_reason = ? WHERE id = ? AND owner_workspace_id = ?") | |
| 892 | .bind(&[a.actor.id.as_str().into(), now.as_str().into(), text(reason.as_deref()), a.id.as_str().into(), workspace_id.as_str().into()])? | |
| 893 | .run() | |
| 894 | .await?; | |
| 895 | } else { | |
| 896 | self.db | |
| 897 | .prepare( | |
| 898 | "INSERT INTO token_workspace_revocations (token_id, workspace_id, revoked_by, revoked_at, reason) VALUES (?, ?, ?, ?, ?) | |
| 899 | ON CONFLICT (token_id, workspace_id) DO NOTHING", | |
| 900 | ) | |
| 901 | .bind(&[a.id.as_str().into(), workspace_id.as_str().into(), a.actor.id.as_str().into(), now.as_str().into(), text(reason.as_deref())])? | |
| 902 | .run() | |
| 903 | .await?; | |
| 904 | } | |
| 905 | self.audit_workspace( | |
| 906 | &a.actor, | |
| 907 | "token.revoked", | |
| 908 | &slug, | |
| 909 | a.surface.unwrap_or(Surface::Web), | |
| 910 | format!( | |
| 911 | "Revoked {} {} token {} in {slug}{}", | |
| 912 | member.owner, | |
| 913 | if member.token.kind == TokenKind::FineGrained { "fine-grained" } else { "classic" }, | |
| 914 | member.token.name, | |
| 915 | reason.as_deref().map(|reason| format!(": {reason}")).unwrap_or_default() | |
| 916 | ), | |
| 917 | ) | |
| 918 | .await; | |
| 919 | self.notify( | |
| 920 | "token.approval_reviewed", | |
| 921 | &a.actor, | |
| 922 | TokenNotice { | |
| 923 | workspace: &slug, | |
| 924 | token_id: &a.id, | |
| 925 | token_name: &member.token.name, | |
| 926 | notify: vec![member.owner.clone()], | |
| 927 | title: format!("Your token {} was revoked for {slug}", member.token.name), | |
| 928 | body: reason.unwrap_or_else(|| "An owner of the workspace revoked it there.".to_owned()), | |
| 929 | link: "/settings/tokens".to_owned(), | |
| 930 | }, | |
| 931 | ) | |
| 932 | .await; | |
| 933 | Ok(Outcome::Ok(true)) | |
| 934 | } | |
| 935 | ||
| 936 | // --- Telling people ------------------------------------------------------- | |
| 937 | ||
| 938 | /// Tells the workspace's owners that `requester`'s token waits for them. | |
| 939 | async fn ask_owners(&self, requester: &User, slug: &str, token: &AccessToken) -> Result<()> { | |
| 940 | #[derive(Deserialize)] | |
| 941 | struct Row { | |
| 942 | username: String, | |
| 943 | } | |
| 944 | let owners: Vec<String> = self | |
| 945 | .db | |
| 946 | .prepare( | |
| 947 | "SELECT users.username FROM workspace_members | |
| 948 | JOIN workspaces ON workspaces.id = workspace_members.workspace_id | |
| 949 | JOIN users ON users.id = workspace_members.user_id | |
| 950 | WHERE workspaces.slug = ? AND workspace_members.role = 'owner'", | |
| 951 | ) | |
| 952 | .bind(&[slug.into()])? | |
| 953 | .all() | |
| 954 | .await? | |
| 955 | .results::<Row>()? | |
| 956 | .into_iter() | |
| 957 | .map(|row| row.username) | |
| 958 | .collect(); | |
| 959 | self.audit_workspace( | |
| 960 | requester, | |
| 961 | "token.approval_requested", | |
| 962 | slug, | |
| 963 | Surface::Web, | |
| 964 | format!("Asked for approval of the fine-grained token {}", token.name), | |
| 965 | ) | |
| 966 | .await; | |
| 967 | if owners.is_empty() { | |
| 968 | return Ok(()); | |
| 969 | } | |
| 970 | let permissions = token | |
| 971 | .fine_grained | |
| 972 | .as_ref() | |
| 973 | .map(|details| details.permissions.iter().map(|(name, access)| format!("{name}: {}", access.as_str())).collect::<Vec<_>>().join(", ")) | |
| 974 | .unwrap_or_default(); | |
| 975 | self.notify( | |
| 976 | "token.approval_requested", | |
| 977 | requester, | |
| 978 | TokenNotice { | |
| 979 | workspace: slug, | |
| 980 | token_id: &token.id, | |
| 981 | token_name: &token.name, | |
| 982 | notify: owners, | |
| 983 | title: format!("{} asks to use a fine-grained token in {slug}", requester.username), | |
| 984 | body: format!("{}: {permissions}", token.name), | |
| Settings: fine-grained tokens, workspace token Admin, workspace personal access token rules | 985 | link: format!("/{slug}/-/personal-access-tokens"), |
| Fine-grained personal tokens, workspace token rules and approvals in identity | 986 | }, |
| 987 | ) | |
| 988 | .await; | |
| 989 | Ok(()) | |
| 990 | } | |
| 991 | ||
| 992 | async fn notify(&self, kind: &'static str, actor: &User, notice: TokenNotice<'_>) { | |
| 993 | let Ok(events) = self.env.service("EVENTS") else { | |
| 994 | return; | |
| 995 | }; | |
| 996 | let publish = Publish { | |
| 997 | events: vec![NewEvent { kind, source: "identity", repo_id: None, actor: Some(actor.id.clone()), data: notice }], | |
| 998 | }; | |
| 999 | if let Err(error) = g1t_kit::call::<_, serde_json::Value>(&events, "publish", &publish).await { | |
| 1000 | worker::console_error!("{kind} not published: {error}"); | |
| 1001 | } | |
| 1002 | } | |
| 1003 | ||
| 1004 | async fn usernames_of(&self, ids: &[String]) -> Result<Vec<String>> { | |
| 1005 | #[derive(Deserialize)] | |
| 1006 | struct Row { | |
| 1007 | username: String, | |
| 1008 | } | |
| 1009 | if ids.is_empty() { | |
| 1010 | return Ok(Vec::new()); | |
| 1011 | } | |
| 1012 | let marks = vec!["?"; ids.len()].join(", "); | |
| 1013 | let binds: Vec<JsValue> = ids.iter().map(|id| JsValue::from(id.as_str())).collect(); | |
| 1014 | Ok(self | |
| 1015 | .db | |
| 1016 | .prepare(format!("SELECT username FROM users WHERE id IN ({marks})")) | |
| 1017 | .bind(&binds)? | |
| 1018 | .all() | |
| 1019 | .await? | |
| 1020 | .results::<Row>()? | |
| 1021 | .into_iter() | |
| 1022 | .map(|row| row.username) | |
| 1023 | .collect()) | |
| 1024 | } | |
| 1025 | } | |
| 1026 | ||
| 1027 | /// `owner/name` for a repository asked for by name in `slug`. | |
| 1028 | fn qualified(slug: Option<&str>, name: &str) -> String { | |
| 1029 | let name = name.trim().trim_start_matches('/'); | |
| 1030 | match (name.contains('/'), slug) { | |
| 1031 | (false, Some(slug)) => format!("{slug}/{name}"), | |
| 1032 | _ => name.to_lowercase(), | |
| 1033 | } | |
| 1034 | } | |
| 1035 | ||
| 1036 | /// The policy in a sentence, for the audit log. | |
| 1037 | fn describe_policy(policy: &TokenPolicy) -> String { | |
| 1038 | let yes = |on: bool| if on { "allowed" } else { "not allowed" }; | |
| 1039 | format!( | |
| 1040 | "Classic tokens {}; fine-grained tokens {}{}; lifetime {}{}", | |
| 1041 | yes(policy.allow_classic), | |
| 1042 | yes(policy.allow_fine_grained), | |
| 1043 | if policy.require_approval { ", with approval" } else { ", without approval" }, | |
| 1044 | policy.max_lifetime_days.map_or_else(|| "unlimited".to_owned(), |days| format!("at most {days} days")), | |
| 1045 | if policy.forbid_no_expiry { "; tokens must expire" } else { "" }, | |
| 1046 | ) | |
| 1047 | } | |
| 1048 | ||
| 1049 | #[cfg(test)] | |
| 1050 | mod tests { | |
| 1051 | use super::*; | |
| 1052 | use g1t_contracts::scopes::Scope; | |
| 1053 | ||
| 1054 | const DAY: u64 = 86_400_000; | |
| 1055 | ||
| 1056 | #[test] | |
| 1057 | fn classic_tokens_follow_the_workspace_rules() { | |
| 1058 | let open = TokenPolicy::default(); | |
| 1059 | assert_eq!(blocked_by(&open, false, TokenStatus::Active, false, 0, None), None); | |
| 1060 | let closed = TokenPolicy { allow_classic: false, ..TokenPolicy::default() }; | |
| 1061 | assert_eq!(blocked_by(&closed, false, TokenStatus::Active, false, 0, Some(DAY)), Some("classic tokens not allowed")); | |
| 1062 | let capped = TokenPolicy { max_lifetime_days: Some(30), ..TokenPolicy::default() }; | |
| 1063 | assert_eq!(blocked_by(&capped, false, TokenStatus::Active, false, 0, Some(90 * DAY)), Some("lasts too long")); | |
| 1064 | assert_eq!(blocked_by(&capped, false, TokenStatus::Active, false, 0, None), Some("never expires")); | |
| 1065 | assert_eq!(blocked_by(&capped, false, TokenStatus::Active, false, 0, Some(7 * DAY)), None); | |
| 1066 | assert_eq!(blocked_by(&open, false, TokenStatus::Active, true, 0, None), Some("revoked")); | |
| 1067 | } | |
| 1068 | ||
| 1069 | #[test] | |
| 1070 | fn fine_grained_tokens_reach_once_active_and_allowed() { | |
| 1071 | let open = TokenPolicy::default(); | |
| 1072 | assert_eq!(blocked_by(&open, true, TokenStatus::Pending, false, 0, Some(DAY)), Some("pending approval")); | |
| 1073 | assert_eq!(blocked_by(&open, true, TokenStatus::Denied, false, 0, Some(DAY)), Some("denied")); | |
| 1074 | assert_eq!(blocked_by(&open, true, TokenStatus::Revoked, false, 0, Some(DAY)), Some("revoked")); | |
| 1075 | assert_eq!(blocked_by(&open, true, TokenStatus::Active, false, 0, Some(DAY)), None); | |
| 1076 | let closed = TokenPolicy { allow_fine_grained: false, ..TokenPolicy::default() }; | |
| 1077 | assert_eq!(blocked_by(&closed, true, TokenStatus::Active, false, 0, Some(DAY)), Some("fine-grained tokens not allowed")); | |
| 1078 | // Classic tokens being off does not touch fine-grained ones. | |
| 1079 | let no_classic = TokenPolicy { allow_classic: false, ..TokenPolicy::default() }; | |
| 1080 | assert_eq!(blocked_by(&no_classic, true, TokenStatus::Active, false, 0, Some(DAY)), None); | |
| 1081 | } | |
| 1082 | ||
| 1083 | #[test] | |
| 1084 | fn rules_rows_read_with_defaults() { | |
| 1085 | let row = RuleRow { id: "wsp_1".into(), slug: "acme".into(), ..RuleRow::default() }; | |
| 1086 | assert_eq!(row.policy(), TokenPolicy::default()); | |
| 1087 | let set = RuleRow { allow_classic: Some(0.0), require_approval: Some(0.0), max_lifetime_days: Some(90.0), forbid_no_expiry: Some(1.0), ..row }; | |
| 1088 | let policy = set.policy(); | |
| 1089 | assert!(!policy.allow_classic && policy.allow_fine_grained && !policy.require_approval && policy.forbid_no_expiry); | |
| 1090 | assert_eq!(policy.max_lifetime_days, Some(90)); | |
| 1091 | } | |
| 1092 | ||
| 1093 | #[test] | |
| 1094 | fn a_listed_row_describes_a_fine_grained_token() { | |
| 1095 | let more = TokenRowMore { | |
| 1096 | kind: Some(FINE_GRAINED.into()), | |
| 1097 | repository_selection: Some("selected".into()), | |
| 1098 | permissions: Some(r#"{"contents":"write","metadata":"read"}"#.into()), | |
| 1099 | status: Some("pending".into()), | |
| 1100 | owner_workspace: Some("acme".into()), | |
| 1101 | ..TokenRowMore::default() | |
| 1102 | }; | |
| 1103 | let mut info = AccessToken::default(); | |
| 1104 | more.describe(&mut info); | |
| 1105 | assert_eq!(info.kind, TokenKind::FineGrained); | |
| 1106 | let details = info.fine_grained.unwrap(); | |
| 1107 | assert_eq!(details.workspace.as_deref(), Some("acme")); | |
| 1108 | assert_eq!(details.repository_selection, RepositorySelection::Selected); | |
| 1109 | assert_eq!(details.status, TokenStatus::Pending); | |
| 1110 | assert_eq!(details.permissions.get("contents"), Some(&Access::Write)); | |
| 1111 | let mut workspace = AccessToken::default(); | |
| 1112 | TokenRowMore { workspace_id: Some("wsp_1".into()), admin: Some(1.0), ..TokenRowMore::default() }.describe(&mut workspace); | |
| 1113 | assert_eq!(workspace.kind, TokenKind::Workspace); | |
| 1114 | assert!(workspace.admin && workspace.fine_grained.is_none()); | |
| 1115 | } | |
| 1116 | ||
| 1117 | #[test] | |
| 1118 | fn repositories_are_named_in_the_resource_owner() { | |
| 1119 | assert_eq!(qualified(Some("acme"), "web"), "acme/web"); | |
| 1120 | assert_eq!(qualified(Some("acme"), "Acme/Web"), "acme/web"); | |
| 1121 | assert!(describe_policy(&TokenPolicy::default()).contains("with approval")); | |
| 1122 | } | |
| 1123 | ||
| 1124 | #[test] | |
| 1125 | fn scopes_are_kept_for_every_check() { | |
| 1126 | let asked: BTreeMap<String, String> = [("contents".to_owned(), "read".to_owned())].into(); | |
| 1127 | let (_, scopes) = fine_grained::resolve(&asked, true).unwrap(); | |
| 1128 | assert_eq!(scopes_text(&scopes), "repo:read code:read"); | |
| 1129 | assert!(scopes.contains(&Scope::CodeRead)); | |
| 1130 | } | |
| 1131 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.