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.
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1 | //! Access tokens: the `g1t_…` secrets used by git, the API and the MCP |
| 2 | //! server. | |
| 3 | //! | |
| 4 | //! There is one implementation and two kinds of owner. A personal token | |
| 5 | //! acts as the person who made it. A workspace's token belongs to the | |
| 6 | //! workspace and acts as it, so automation needs no account of its own and | |
| 7 | //! keeps working when the member who set it up leaves. | |
| 8 | ||
| 9 | use g1t_contracts::identity::*; | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 10 | use g1t_contracts::scopes::{FULL_ACCESS, JobToken, Scope, TokenAccess, parse_scopes, scopes_text}; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 11 | use g1t_contracts::time::{SQL_NOW, rfc3339}; |
| 12 | use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, Role, User, Viewer, new_id}; | |
| 13 | use g1t_kit::now_ms; | |
| 14 | use serde::Deserialize; | |
| 15 | use worker::Result; | |
| 16 | use worker::wasm_bindgen::JsValue; | |
| 17 | ||
| 18 | use crate::{Identity, crypto}; | |
| 19 | ||
| 20 | pub const TOKEN_PREFIX: &str = "g1t_"; | |
| 21 | /// How stale a token's last-used time may get before it is written again. | |
| 22 | const LAST_USED_RESOLUTION_MS: u64 = 5 * 60 * 1000; | |
| 23 | const MAX_TOKENS_PER_WORKSPACE: usize = 50; | |
| 24 | const WORKSPACE_ID_PREFIX: &str = "wsp_"; | |
| 25 | ||
| 26 | const TOKEN_COLUMNS: &str = "access_tokens.id, access_tokens.name, access_tokens.created_at, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 27 | access_tokens.last_used_at, users.username AS created_by, access_tokens.scopes, |
| 28 | access_tokens.expires_at"; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 29 | |
| 30 | /// Who a new token belongs to. | |
| 31 | enum Owner<'a> { | |
| 32 | User(&'a str), | |
| 33 | Workspace { | |
| 34 | id: &'a str, | |
| 35 | created_by: Option<&'a str>, | |
| 36 | }, | |
| 37 | } | |
| 38 | ||
| 39 | #[derive(Deserialize)] | |
| 40 | struct TokenRow { | |
| 41 | id: String, | |
| 42 | name: String, | |
| 43 | created_at: String, | |
| 44 | last_used_at: Option<String>, | |
| 45 | created_by: Option<String>, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 46 | scopes: Option<String>, |
| 47 | expires_at: Option<String>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 48 | } |
| 49 | ||
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 50 | /// What a token or grant may do, as it is to be stored. A token reaches |
| 51 | /// whatever its owner can; only its scopes narrow that. | |
| 52 | /// | |
| 53 | /// The `resources` columns (migration 0022) held a limit to some | |
| 54 | /// workspaces or repositories. That limit was retired (migration 0023); | |
| 55 | /// the columns stay, since D1 cannot drop them in place, and nothing | |
| 56 | /// reads or writes them. | |
| 57 | #[derive(Clone, Debug, Default)] | |
| 58 | pub(crate) struct Grant { | |
| 59 | /// Null: full access. | |
| 60 | pub scopes: Option<Vec<Scope>>, | |
| 61 | } | |
| 62 | ||
| 63 | impl Grant { | |
| 64 | /// From what a caller asked for: unknown scopes are left out. | |
| 65 | pub(crate) fn asked(scopes: &Option<Vec<String>>) -> Self { | |
| 66 | Grant { | |
| 67 | scopes: scopes.as_ref().map(|scopes| parse_scopes(&scopes.join(" "))), | |
| 68 | } | |
| 69 | } | |
| 70 | ||
| 71 | /// The `scopes` column: `*` for full access. | |
| 72 | pub(crate) fn scopes_column(&self) -> String { | |
| 73 | match &self.scopes { | |
| 74 | None => FULL_ACCESS.to_owned(), | |
| 75 | Some(scopes) => scopes_text(scopes), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 76 | } |
| 77 | } | |
| 78 | } | |
| 79 | ||
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 80 | /// A `scopes` column read back: the scopes (null for full access), and |
| 81 | /// whether it is a legacy row, made before scopes. | |
| 82 | pub(crate) fn stored_scopes(column: Option<&str>) -> (Option<Vec<String>>, bool) { | |
| 83 | match column { | |
| 84 | None => (None, true), | |
| 85 | Some(FULL_ACCESS) => (None, false), | |
| 86 | Some(text) => ( | |
| 87 | Some(parse_scopes(text).iter().map(|scope| scope.as_str().to_owned()).collect()), | |
| 88 | false, | |
| 89 | ), | |
| 90 | } | |
| 91 | } | |
| 92 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 93 | /// The owner of a token being used. |
| 94 | #[derive(Deserialize)] | |
| 95 | struct Presented { | |
| 96 | id: String, | |
| 97 | user_id: Option<String>, | |
| 98 | workspace_id: Option<String>, | |
| 99 | last_used_at: Option<String>, | |
| 100 | /// Set on an agent's token: what it may do, as JSON `AgentScope`. | |
| 101 | agent_scope: Option<String>, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 102 | scopes: Option<String>, |
| Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens | 103 | #[serde(default)] |
| 104 | name: Option<String>, | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 105 | /// Set on a workflow job's token (job_tokens.rs): its repository, job |
| 106 | /// and run. | |
| 107 | #[serde(default)] | |
| 108 | repo: Option<String>, | |
| 109 | #[serde(default)] | |
| 110 | job_id: Option<String>, | |
| 111 | #[serde(default)] | |
| 112 | job_run_id: Option<String>, | |
| 113 | #[serde(default)] | |
| 114 | job_pulls: Option<u32>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 115 | } |
| 116 | ||
| 117 | #[derive(Deserialize)] | |
| 118 | struct WorkspaceRef { | |
| 119 | id: String, | |
| 120 | slug: String, | |
| 121 | } | |
| 122 | ||
| 123 | fn text(value: Option<&str>) -> JsValue { | |
| 124 | value.map_or(JsValue::NULL, JsValue::from) | |
| 125 | } | |
| 126 | ||
| 127 | impl Identity { | |
| 128 | pub async fn user_for_access_token(&self, token: &str) -> Result<Viewer> { | |
| 129 | if !token.starts_with(TOKEN_PREFIX) { | |
| 130 | return Ok(None); | |
| 131 | } | |
| 132 | let Some(presented) = self | |
| 133 | .db | |
| 134 | .prepare(format!( | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 135 | "SELECT id, user_id, workspace_id, last_used_at, agent_scope, scopes, name, |
| 136 | repo, job_id, job_run_id, job_pulls | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 137 | FROM access_tokens |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 138 | WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})" |
| 139 | )) | |
| 140 | .bind(&[crypto::sha256_hex(token).into()])? | |
| 141 | .first::<Presented>(None) | |
| 142 | .await? | |
| 143 | else { | |
| 144 | return Ok(None); | |
| 145 | }; | |
| g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent | 146 | // An agent's token: g1t on behalf of the person it was made |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 147 | // for, in its repository's workspace while they belong to it, and |
| 148 | // only for what its scope lists. See run_credentials.rs. | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 149 | if let Some(scope) = presented |
| 150 | .agent_scope | |
| 151 | .as_deref() | |
| 152 | .and_then(|scope| serde_json::from_str::<AgentScope>(scope).ok()) | |
| 153 | { | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 154 | return self |
| 155 | .agent_principal( | |
| 156 | &presented.id, | |
| 157 | presented.user_id.as_deref(), | |
| 158 | presented.workspace_id.as_deref(), | |
| 159 | scope, | |
| 160 | ) | |
| 161 | .await; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 162 | } |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 163 | let mut viewer = match (&presented.user_id, &presented.workspace_id) { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 164 | (Some(user_id), _) => { |
| 165 | self.find_user( | |
| 166 | "SELECT id, username, email_verified_at IS NOT NULL AS verified | |
| 167 | FROM users WHERE id = ?", | |
| 168 | user_id, | |
| 169 | ) | |
| 170 | .await? | |
| 171 | } | |
| 172 | (None, Some(workspace_id)) => self.workspace_principal(workspace_id).await?, | |
| 173 | (None, None) => None, | |
| 174 | }; | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 175 | if let Some(user) = viewer.as_mut() { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 176 | self.note_use(&presented).await?; |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 177 | let (scopes, legacy) = stored_scopes(presented.scopes.as_deref()); |
| 178 | user.token = Some(Box::new(TokenAccess { | |
| 179 | token_id: presented.id.clone(), | |
| 180 | scopes, | |
| 181 | legacy, | |
| Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens | 182 | name: presented.name.clone(), |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 183 | repo: presented.repo.clone(), |
| 184 | job: match (&presented.job_id, &presented.job_run_id) { | |
| 185 | (Some(job_id), Some(run_id)) => Some(JobToken { | |
| 186 | run_id: run_id.clone(), | |
| 187 | job_id: job_id.clone(), | |
| 188 | pull_requests: presented.job_pulls == Some(1), | |
| 189 | }), | |
| 190 | _ => None, | |
| 191 | }, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 192 | })); |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 193 | } |
| 194 | Ok(viewer) | |
| 195 | } | |
| 196 | ||
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 197 | fn info(row: TokenRow) -> AccessToken { |
| 198 | let (scopes, legacy) = stored_scopes(row.scopes.as_deref()); | |
| 199 | AccessToken { | |
| 200 | id: row.id, | |
| 201 | name: row.name, | |
| 202 | created_at: row.created_at, | |
| 203 | last_used_at: row.last_used_at, | |
| 204 | created_by: row.created_by, | |
| 205 | scopes, | |
| 206 | legacy, | |
| 207 | expires_at: row.expires_at, | |
| 208 | } | |
| 209 | } | |
| 210 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 211 | /// A workspace as the actor behind one of its own tokens. It can do |
| 212 | /// what a member can, in that workspace only. | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 213 | pub(crate) async fn workspace_principal(&self, workspace_id: &str) -> Result<Viewer> { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 214 | let workspace = self |
| 215 | .db | |
| Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member | 216 | // A deleted workspace's tokens are refused until it is restored. |
| 217 | .prepare("SELECT id, slug FROM workspaces WHERE id = ? AND deleted_at IS NULL") | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 218 | .bind(&[workspace_id.into()])? |
| 219 | .first::<WorkspaceRef>(None) | |
| 220 | .await?; | |
| 221 | Ok(workspace.map(|workspace| User { | |
| 222 | id: workspace.id, | |
| 223 | username: workspace.slug.clone(), | |
| 224 | kind: PrincipalKind::Workspace, | |
| 225 | verified: true, | |
| Workspace names and icons, and a component kit for every control | 226 | workspaces: vec![Membership::member(workspace.slug)], |
| 227 | ..User::default() | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 228 | })) |
| 229 | } | |
| 230 | ||
| 231 | async fn note_use(&self, presented: &Presented) -> Result<()> { | |
| 232 | let now = now_ms(); | |
| 233 | let stale = rfc3339(now.saturating_sub(LAST_USED_RESOLUTION_MS)); | |
| 234 | if presented | |
| 235 | .last_used_at | |
| 236 | .as_deref() | |
| 237 | .is_some_and(|at| at >= stale.as_str()) | |
| 238 | { | |
| 239 | return Ok(()); | |
| 240 | } | |
| 241 | self.db | |
| 242 | .prepare("UPDATE access_tokens SET last_used_at = ? WHERE id = ?") | |
| 243 | .bind(&[rfc3339(now).into(), presented.id.as_str().into()])? | |
| 244 | .run() | |
| 245 | .await?; | |
| 246 | Ok(()) | |
| 247 | } | |
| 248 | ||
| 249 | async fn mint( | |
| 250 | &self, | |
| 251 | owner: Owner<'_>, | |
| 252 | name: &str, | |
| 253 | ttl_seconds: Option<u64>, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 254 | grant: &Grant, |
| 255 | listed: bool, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 256 | ) -> Result<CreatedAccessToken> { |
| 257 | let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20)); | |
| 258 | let now = now_ms(); | |
| 259 | let name: String = match name.trim() { | |
| 260 | "" => "Access token".to_owned(), | |
| 261 | name => name.chars().take(100).collect(), | |
| 262 | }; | |
| 263 | let (user_id, workspace_id, created_by) = match owner { | |
| 264 | Owner::User(id) => (Some(id), None, Some(id)), | |
| 265 | Owner::Workspace { id, created_by } => (None, Some(id), created_by), | |
| 266 | }; | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 267 | let expires_at = ttl_seconds.map(|ttl| rfc3339(now + ttl * 1000)); |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 268 | let info = AccessToken { |
| 269 | id: new_id("tok", now), | |
| 270 | name, | |
| 271 | created_at: rfc3339(now), | |
| 272 | last_used_at: None, | |
| 273 | created_by: None, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 274 | scopes: grant |
| 275 | .scopes | |
| 276 | .as_ref() | |
| 277 | .map(|scopes| scopes.iter().map(|scope| scope.as_str().to_owned()).collect()), | |
| 278 | legacy: false, | |
| 279 | expires_at: expires_at.clone(), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 280 | }; |
| 281 | self.db | |
| 282 | .prepare( | |
| 283 | "INSERT INTO access_tokens | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 284 | (id, user_id, workspace_id, created_by, name, token_hash, created_at, expires_at, |
| 285 | scopes, listed) | |
| 286 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 287 | ) |
| 288 | .bind(&[ | |
| 289 | info.id.as_str().into(), | |
| 290 | text(user_id), | |
| 291 | text(workspace_id), | |
| 292 | text(created_by), | |
| 293 | info.name.as_str().into(), | |
| 294 | crypto::sha256_hex(&token).into(), | |
| 295 | info.created_at.as_str().into(), | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 296 | text(expires_at.as_deref()), |
| 297 | grant.scopes_column().into(), | |
| 298 | JsValue::from(u8::from(listed)), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 299 | ])? |
| 300 | .run() | |
| 301 | .await?; | |
| 302 | Ok(CreatedAccessToken { token, info }) | |
| 303 | } | |
| 304 | ||
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 305 | /// A workspace's own token that expires and is never listed: what a |
| 306 | /// workflow job's token is minted as (job_tokens.rs). | |
| 307 | pub(crate) async fn mint_for_workspace( | |
| 308 | &self, | |
| 309 | workspace_id: &str, | |
| 310 | name: &str, | |
| 311 | ttl_seconds: u64, | |
| 312 | grant: &Grant, | |
| 313 | ) -> Result<CreatedAccessToken> { | |
| 314 | self.mint( | |
| 315 | Owner::Workspace { | |
| 316 | id: workspace_id, | |
| 317 | created_by: None, | |
| 318 | }, | |
| 319 | name, | |
| 320 | Some(ttl_seconds), | |
| 321 | grant, | |
| 322 | false, | |
| 323 | ) | |
| 324 | .await | |
| 325 | } | |
| 326 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 327 | pub async fn create_access_token( |
| 328 | &self, | |
| 329 | a: CreateAccessTokenArgs, | |
| 330 | ) -> Result<CreatedAccessToken> { | |
| 331 | // Told apart by the id, which says what it names, since callers pass | |
| 332 | // on actors that other services stored as an id and a name. | |
| 333 | let owner = if a.user.id.starts_with(WORKSPACE_ID_PREFIX) { | |
| 334 | Owner::Workspace { | |
| 335 | id: &a.user.id, | |
| 336 | created_by: None, | |
| 337 | } | |
| 338 | } else { | |
| 339 | Owner::User(&a.user.id) | |
| 340 | }; | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 341 | self.mint(owner, &a.name, a.ttl_seconds, &Grant::asked(&a.scopes), a.listed).await |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 342 | } |
| 343 | ||
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 344 | /// Changes what one of a person's own tokens may do. |
| 345 | pub async fn update_access_token(&self, a: UpdateAccessTokenArgs) -> Result<Outcome<AccessToken>> { | |
| 346 | let grant = Grant::asked(&a.scopes); | |
| 347 | let found: Option<String> = self | |
| 348 | .db | |
| 349 | .prepare( | |
| 350 | "UPDATE access_tokens SET scopes = ? | |
| 351 | WHERE id = ? AND user_id = ? AND agent_scope IS NULL | |
| 352 | RETURNING id", | |
| 353 | ) | |
| 354 | .bind(&[ | |
| 355 | grant.scopes_column().into(), | |
| 356 | a.id.as_str().into(), | |
| 357 | a.user.id.as_str().into(), | |
| 358 | ])? | |
| 359 | .first(Some("id")) | |
| 360 | .await?; | |
| 361 | if found.is_none() { | |
| 362 | return Ok(Outcome::fail(FailureCode::NotFound, "No such token.")); | |
| 363 | } | |
| 364 | let row = self | |
| 365 | .db | |
| 366 | .prepare(format!( | |
| 367 | "SELECT {TOKEN_COLUMNS} FROM access_tokens | |
| 368 | LEFT JOIN users ON users.id = access_tokens.created_by | |
| 369 | WHERE access_tokens.id = ?" | |
| 370 | )) | |
| 371 | .bind(&[a.id.into()])? | |
| 372 | .first::<TokenRow>(None) | |
| 373 | .await?; | |
| 374 | match row { | |
| 375 | Some(row) => Ok(Outcome::Ok(Self::info(row))), | |
| 376 | None => Ok(Outcome::fail(FailureCode::NotFound, "No such token.")), | |
| 377 | } | |
| 378 | } | |
| 379 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 380 | /// A token for a g1t agent working for `on_behalf_of`, which can do |
| 381 | /// only what `scope` lists. It is recorded as theirs, so it is listed and | |
| 382 | /// can be deleted with their other tokens. | |
| 383 | pub async fn create_agent_token(&self, a: CreateAgentTokenArgs) -> Result<CreatedAccessToken> { | |
| 384 | let created = self | |
| 385 | .mint( | |
| 386 | Owner::User(&a.on_behalf_of.id), | |
| 387 | &format!("g1t agent in {}/{}", a.scope.repo.namespace, a.scope.repo.name), | |
| 388 | Some(a.ttl_seconds), | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 389 | &Grant::default(), |
| 390 | false, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 391 | ) |
| 392 | .await?; | |
| 393 | self.db | |
| 394 | .prepare("UPDATE access_tokens SET agent_scope = ? WHERE id = ?") | |
| 395 | .bind(&[ | |
| 396 | serde_json::to_string(&a.scope)?.into(), | |
| 397 | created.info.id.as_str().into(), | |
| 398 | ])? | |
| 399 | .run() | |
| 400 | .await?; | |
| 401 | Ok(created) | |
| 402 | } | |
| 403 | ||
| 404 | /// What an agent's token may do, or `None` for any other token. | |
| 405 | pub async fn agent_scope(&self, a: TokenArgs) -> Result<Option<AgentScope>> { | |
| 406 | let scope: Option<Option<String>> = self | |
| 407 | .db | |
| 408 | .prepare(format!( | |
| 409 | "SELECT agent_scope FROM access_tokens | |
| 410 | WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})" | |
| 411 | )) | |
| 412 | .bind(&[crypto::sha256_hex(&a.token).into()])? | |
| 413 | .first::<Option<String>>(Some("agent_scope")) | |
| 414 | .await?; | |
| 415 | Ok(scope | |
| 416 | .flatten() | |
| 417 | .and_then(|scope| serde_json::from_str(&scope).ok())) | |
| 418 | } | |
| 419 | ||
| 420 | pub async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> { | |
| 421 | self.tokens_where("access_tokens.user_id = ?", &a.user.id) | |
| 422 | .await | |
| 423 | } | |
| 424 | ||
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 425 | /// The tokens a person or workspace made on purpose: those that do not |
| 426 | /// expire, and those made with an expiry from settings, rather than | |
| 427 | /// those issued to an application or a hosted agent. | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 428 | async fn tokens_where(&self, owner: &str, id: &str) -> Result<Vec<AccessToken>> { |
| 429 | let rows = self | |
| 430 | .db | |
| 431 | .prepare(format!( | |
| 432 | "SELECT {TOKEN_COLUMNS} FROM access_tokens | |
| 433 | LEFT JOIN users ON users.id = access_tokens.created_by | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 434 | WHERE {owner} AND (access_tokens.expires_at IS NULL OR access_tokens.listed = 1) |
| 435 | AND access_tokens.agent_scope IS NULL | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 436 | ORDER BY access_tokens.id" |
| 437 | )) | |
| 438 | .bind(&[id.into()])? | |
| 439 | .all() | |
| 440 | .await? | |
| 441 | .results::<TokenRow>()?; | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 442 | Ok(rows.into_iter().map(Self::info).collect()) |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 443 | } |
| 444 | ||
| 445 | pub async fn list_workspace_tokens( | |
| 446 | &self, | |
| 447 | a: WorkspaceTokensArgs, | |
| 448 | ) -> Result<Outcome<Vec<AccessToken>>> { | |
| 449 | let slug = a.slug.to_lowercase(); | |
| 450 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&slug)) { | |
| 451 | return Ok(Outcome::fail( | |
| 452 | FailureCode::Forbidden, | |
| 453 | "Only members can see a workspace's access tokens.", | |
| 454 | )); | |
| 455 | } | |
| 456 | let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else { | |
| 457 | return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found.")); | |
| 458 | }; | |
| 459 | Ok(Outcome::Ok( | |
| 460 | self.tokens_where("access_tokens.workspace_id = ?", &workspace.id) | |
| 461 | .await?, | |
| 462 | )) | |
| 463 | } | |
| 464 | ||
| 465 | /// The workspace's id, if `actor` is a person who owns it. | |
| 466 | async fn owned_workspace(&self, actor: &User, slug: &str) -> Result<Outcome<String>> { | |
| 467 | let slug = slug.to_lowercase(); | |
| 468 | if actor.kind != PrincipalKind::User || actor.role_in(&slug) != Some(Role::Owner) { | |
| 469 | return Ok(Outcome::fail( | |
| 470 | FailureCode::Forbidden, | |
| 471 | "Only an owner can manage a workspace's access tokens.", | |
| 472 | )); | |
| 473 | } | |
| 474 | Ok(match self.get_workspace(SlugArgs { slug }).await? { | |
| 475 | Some(workspace) => Outcome::Ok(workspace.id), | |
| 476 | None => Outcome::fail(FailureCode::NotFound, "Workspace not found."), | |
| 477 | }) | |
| 478 | } | |
| 479 | ||
| 480 | pub async fn create_workspace_token( | |
| 481 | &self, | |
| 482 | a: CreateWorkspaceTokenArgs, | |
| 483 | ) -> Result<Outcome<CreatedAccessToken>> { | |
| 484 | let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? { | |
| 485 | Outcome::Ok(id) => id, | |
| 486 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 487 | }; | |
| 488 | if a.name.trim().is_empty() { | |
| 489 | return Ok(Outcome::fail( | |
| 490 | FailureCode::Invalid, | |
| 491 | "Name the token after what will use it.", | |
| 492 | )); | |
| 493 | } | |
| 494 | let existing = self | |
| 495 | .tokens_where("access_tokens.workspace_id = ?", &workspace_id) | |
| 496 | .await?; | |
| 497 | if existing.len() >= MAX_TOKENS_PER_WORKSPACE { | |
| 498 | return Ok(Outcome::fail( | |
| 499 | FailureCode::Conflict, | |
| 500 | "This workspace has the maximum number of access tokens. Delete one first.", | |
| 501 | )); | |
| 502 | } | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 503 | // A workspace's token reaches that workspace only: it acts as the |
| 504 | // workspace (see `workspace_principal`), narrowed by its scopes. | |
| 505 | let grant = Grant::asked(&a.scopes); | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 506 | let mut created = self |
| 507 | .mint( | |
| 508 | Owner::Workspace { | |
| 509 | id: &workspace_id, | |
| 510 | created_by: Some(&a.actor.id), | |
| 511 | }, | |
| 512 | &a.name, | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 513 | a.ttl_seconds, |
| 514 | &grant, | |
| 515 | true, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 516 | ) |
| 517 | .await?; | |
| 518 | created.info.created_by = Some(a.actor.username); | |
| 519 | Ok(Outcome::Ok(created)) | |
| 520 | } | |
| 521 | ||
| 522 | pub async fn remove_workspace_token( | |
| 523 | &self, | |
| 524 | a: RemoveWorkspaceTokenArgs, | |
| 525 | ) -> Result<Outcome<bool>> { | |
| 526 | let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? { | |
| 527 | Outcome::Ok(id) => id, | |
| 528 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 529 | }; | |
| 530 | self.db | |
| 531 | .prepare("DELETE FROM access_tokens WHERE id = ? AND workspace_id = ?") | |
| 532 | .bind(&[a.id.into(), workspace_id.into()])? | |
| 533 | .run() | |
| 534 | .await?; | |
| 535 | Ok(Outcome::Ok(true)) | |
| 536 | } | |
| 537 | } | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 538 | |
| 539 | #[cfg(test)] | |
| 540 | mod tests { | |
| 541 | use super::*; | |
| 542 | ||
| 543 | #[test] | |
| 544 | fn a_row_without_scopes_is_legacy_full_access() { | |
| 545 | assert_eq!(stored_scopes(None), (None, true)); | |
| 546 | assert_eq!(stored_scopes(Some("*")), (None, false)); | |
| 547 | assert_eq!( | |
| 548 | stored_scopes(Some("issues:write repo:read nonsense")), | |
| 549 | (Some(vec!["repo:read".to_owned(), "issues:write".to_owned()]), false) | |
| 550 | ); | |
| 551 | } | |
| 552 | ||
| 553 | #[test] | |
| 554 | fn scopes_are_stored_as_text() { | |
| 555 | let grant = Grant::asked(&Some(vec!["issues:read".to_owned(), "bogus".to_owned()])); | |
| 556 | assert_eq!(grant.scopes_column(), "issues:read"); | |
| 557 | assert_eq!(Grant::asked(&None).scopes_column(), "*"); | |
| 558 | assert_eq!(Grant::asked(&Some(vec![])).scopes_column(), ""); | |
| 559 | } | |
| 560 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.