Skip to content
578 linesCodeBlameRaw

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.

Plan: integrations are in1//! Access tokens: the `g1t_…` secrets used by git, the API and the MCP
2//! server.
3//!
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers4//! There is one kind of token and two kinds of owner. A personal token
Plan: integrations are in5//! 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
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers7//! keeps working when the member who set it up leaves. Either is made and
8//! changed with permissions and a reach (token_reach.rs); this file mints,
9//! resolves, lists and deletes them.
Plan: integrations are in10
11use g1t_contracts::identity::*;
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers12use g1t_contracts::scopes::{FULL_ACCESS, JobToken, Scope, TokenAccess, everything, parse_scopes, permissions_of, scopes_text};
Plan: integrations are in13use g1t_contracts::time::{SQL_NOW, rfc3339};
14use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, Role, User, Viewer, new_id};
15use g1t_kit::now_ms;
16use serde::Deserialize;
17use worker::Result;
18use worker::wasm_bindgen::JsValue;
19
20use crate::{Identity, crypto};
21
22pub const TOKEN_PREFIX: &str = "g1t_";
23/// How stale a token's last-used time may get before it is written again.
24const LAST_USED_RESOLUTION_MS: u64 = 5 * 60 * 1000;
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers25pub(crate) const MAX_TOKENS_PER_WORKSPACE: usize = 50;
Plan: integrations are in26const WORKSPACE_ID_PREFIX: &str = "wsp_";
27
Fine-grained personal tokens, workspace token rules and approvals in identity28pub(crate) 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 step29 access_tokens.last_used_at, users.username AS created_by, access_tokens.scopes,
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers30 access_tokens.expires_at, access_tokens.description, access_tokens.admin,
31 access_tokens.workspace_id, access_tokens.repository_selection,
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate32 access_tokens.status, access_tokens.review_reason, access_tokens.website,
Fine-grained personal tokens, workspace token rules and approvals in identity33 (SELECT slug FROM workspaces WHERE workspaces.id = access_tokens.owner_workspace_id) AS owner_workspace";
Plan: integrations are in34
35/// Who a new token belongs to.
Fine-grained personal tokens, workspace token rules and approvals in identity36pub(crate) enum Owner<'a> {
Plan: integrations are in37 User(&'a str),
38 Workspace {
39 id: &'a str,
40 created_by: Option<&'a str>,
41 },
42}
43
44#[derive(Deserialize)]
Fine-grained personal tokens, workspace token rules and approvals in identity45pub(crate) struct TokenRow {
Plan: integrations are in46 id: String,
47 name: String,
48 created_at: String,
49 last_used_at: Option<String>,
50 created_by: Option<String>,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step51 scopes: Option<String>,
52 expires_at: Option<String>,
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers53 /// Its reach, status, description and a workspace token's Admin
54 /// (migration 0034; see token_reach.rs).
Fine-grained personal tokens, workspace token rules and approvals in identity55 #[serde(flatten)]
56 pub(crate) more: crate::token_reach::TokenRowMore,
Plan: integrations are in57}
58
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step59/// What a token or grant may do, as it is to be stored. A token reaches
60/// whatever its owner can; only its scopes narrow that.
61///
62/// The `resources` columns (migration 0022) held a limit to some
63/// workspaces or repositories. That limit was retired (migration 0023);
64/// the columns stay, since D1 cannot drop them in place, and nothing
65/// reads or writes them.
66#[derive(Clone, Debug, Default)]
67pub(crate) struct Grant {
68 /// Null: full access.
69 pub scopes: Option<Vec<Scope>>,
70}
71
72impl Grant {
73 /// From what a caller asked for: unknown scopes are left out.
74 pub(crate) fn asked(scopes: &Option<Vec<String>>) -> Self {
75 Grant {
76 scopes: scopes.as_ref().map(|scopes| parse_scopes(&scopes.join(" "))),
77 }
78 }
79
80 /// The `scopes` column: `*` for full access.
81 pub(crate) fn scopes_column(&self) -> String {
82 match &self.scopes {
83 None => FULL_ACCESS.to_owned(),
84 Some(scopes) => scopes_text(scopes),
Plan: integrations are in85 }
86 }
87}
88
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step89/// A `scopes` column read back: the scopes (null for full access), and
90/// whether it is a legacy row, made before scopes.
91pub(crate) fn stored_scopes(column: Option<&str>) -> (Option<Vec<String>>, bool) {
92 match column {
93 None => (None, true),
94 Some(FULL_ACCESS) => (None, false),
95 Some(text) => (
96 Some(parse_scopes(text).iter().map(|scope| scope.as_str().to_owned()).collect()),
97 false,
98 ),
99 }
100}
101
Plan: integrations are in102/// The owner of a token being used.
103#[derive(Deserialize)]
104struct Presented {
105 id: String,
106 user_id: Option<String>,
107 workspace_id: Option<String>,
108 last_used_at: Option<String>,
109 /// Set on an agent's token: what it may do, as JSON `AgentScope`.
110 agent_scope: Option<String>,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step111 scopes: Option<String>,
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens112 #[serde(default)]
113 name: Option<String>,
Merge branch 'worktree-agent-a3abfcce648e87dca'114 /// Set on a workflow job's token (job_tokens.rs): its repository, job
115 /// and run.
116 #[serde(default)]
117 repo: Option<String>,
118 #[serde(default)]
119 job_id: Option<String>,
120 #[serde(default)]
121 job_run_id: Option<String>,
122 #[serde(default)]
123 job_pulls: Option<u32>,
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate124 /// 1 when its owner let it use the website (migration 0043).
125 #[serde(default)]
126 website: Option<f64>,
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers127 /// The workspace it is made for, its repositories and status, a
128 /// workspace token's Admin, and when it was made and expires, for the
129 /// rules of the workspaces it reaches (token_reach.rs).
Fine-grained personal tokens, workspace token rules and approvals in identity130 #[serde(flatten)]
131 facts: crate::token_reach::Facts,
Plan: integrations are in132}
133
134#[derive(Deserialize)]
135struct WorkspaceRef {
136 id: String,
137 slug: String,
138}
139
140fn text(value: Option<&str>) -> JsValue {
141 value.map_or(JsValue::NULL, JsValue::from)
142}
143
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate144/// Whether a token being used may be used on the website as its owner: one
145/// a person made and turned that on for, never a workspace's, a job's or an
146/// agent's (apps/web, app/lib/website-token.ts).
147fn website_allowed(presented: &Presented) -> bool {
148 presented.website.is_some_and(|on| on >= 1.0)
149 && presented.user_id.is_some()
150 && presented.workspace_id.is_none()
151 && presented.job_id.is_none()
152 && presented.agent_scope.is_none()
153}
154
Plan: integrations are in155impl Identity {
156 pub async fn user_for_access_token(&self, token: &str) -> Result<Viewer> {
157 if !token.starts_with(TOKEN_PREFIX) {
158 return Ok(None);
159 }
160 let Some(presented) = self
161 .db
162 .prepare(format!(
Merge branch 'worktree-agent-a3abfcce648e87dca'163 "SELECT id, user_id, workspace_id, last_used_at, agent_scope, scopes, name,
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers164 repo, job_id, job_run_id, job_pulls, created_at, expires_at,
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate165 owner_workspace_id, repository_selection, status, admin, website
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step166 FROM access_tokens
Plan: integrations are in167 WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})"
168 ))
169 .bind(&[crypto::sha256_hex(token).into()])?
170 .first::<Presented>(None)
171 .await?
172 else {
173 return Ok(None);
174 };
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent175 // 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 API176 // for, in its repository's workspace while they belong to it, and
177 // only for what its scope lists. See run_credentials.rs.
Plan: integrations are in178 if let Some(scope) = presented
179 .agent_scope
180 .as_deref()
181 .and_then(|scope| serde_json::from_str::<AgentScope>(scope).ok())
182 {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API183 return self
184 .agent_principal(
185 &presented.id,
186 presented.user_id.as_deref(),
187 presented.workspace_id.as_deref(),
188 scope,
189 )
190 .await;
Plan: integrations are in191 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step192 let mut viewer = match (&presented.user_id, &presented.workspace_id) {
Plan: integrations are in193 (Some(user_id), _) => {
194 self.find_user(
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate195 "SELECT id, username, display_username, email_verified_at IS NOT NULL AS verified, avatar
Merge account deletion: soft delete for 30 days, staff restore and purge, ghost for what remains (identity 0037)196 FROM users WHERE id = ? AND deleted_at IS NULL",
Plan: integrations are in197 user_id,
198 )
199 .await?
200 }
201 (None, Some(workspace_id)) => self.workspace_principal(workspace_id).await?,
202 (None, None) => None,
203 };
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step204 if let Some(user) = viewer.as_mut() {
Plan: integrations are in205 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 step206 let (scopes, legacy) = stored_scopes(presented.scopes.as_deref());
207 user.token = Some(Box::new(TokenAccess {
208 token_id: presented.id.clone(),
209 scopes,
210 legacy,
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens211 name: presented.name.clone(),
Merge branch 'worktree-agent-a3abfcce648e87dca'212 repo: presented.repo.clone(),
213 job: match (&presented.job_id, &presented.job_run_id) {
214 (Some(job_id), Some(run_id)) => Some(JobToken {
215 run_id: run_id.clone(),
216 job_id: job_id.clone(),
217 pull_requests: presented.job_pulls == Some(1),
218 }),
219 _ => None,
220 },
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate221 website: website_allowed(&presented),
Fine-grained personal tokens, workspace token rules and approvals in identity222 ..TokenAccess::default()
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step223 }));
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers224 // What it reaches: the workspace it is made for and its
Fine-grained personal tokens, workspace token rules and approvals in identity225 // repositories, the workspaces whose rules let it in, a
226 // workspace token's role.
227 self.apply_reach(user, &presented.id, presented.user_id.is_some(), &presented.facts).await?;
Plan: integrations are in228 }
229 Ok(viewer)
230 }
231
Fine-grained personal tokens, workspace token rules and approvals in identity232 pub(crate) fn info(row: TokenRow) -> AccessToken {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step233 let (scopes, legacy) = stored_scopes(row.scopes.as_deref());
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers234 let held: Vec<Scope> = scopes.as_ref().map_or_else(everything, |scopes| scopes.iter().filter_map(|scope| Scope::parse(scope)).collect());
Fine-grained personal tokens, workspace token rules and approvals in identity235 let mut info = AccessToken {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step236 id: row.id,
237 name: row.name,
238 created_at: row.created_at,
239 last_used_at: row.last_used_at,
240 created_by: row.created_by,
241 scopes,
242 legacy,
243 expires_at: row.expires_at,
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers244 permissions: permissions_of(&held),
Fine-grained personal tokens, workspace token rules and approvals in identity245 ..AccessToken::default()
246 };
247 row.more.describe(&mut info);
248 info
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step249 }
250
Plan: integrations are in251 /// A workspace as the actor behind one of its own tokens. It can do
252 /// 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 API253 pub(crate) async fn workspace_principal(&self, workspace_id: &str) -> Result<Viewer> {
Plan: integrations are in254 let workspace = self
255 .db
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member256 // A deleted workspace's tokens are refused until it is restored.
257 .prepare("SELECT id, slug FROM workspaces WHERE id = ? AND deleted_at IS NULL")
Plan: integrations are in258 .bind(&[workspace_id.into()])?
259 .first::<WorkspaceRef>(None)
260 .await?;
261 Ok(workspace.map(|workspace| User {
262 id: workspace.id,
263 username: workspace.slug.clone(),
264 kind: PrincipalKind::Workspace,
265 verified: true,
Workspace names and icons, and a component kit for every control266 workspaces: vec![Membership::member(workspace.slug)],
267 ..User::default()
Plan: integrations are in268 }))
269 }
270
271 async fn note_use(&self, presented: &Presented) -> Result<()> {
272 let now = now_ms();
273 let stale = rfc3339(now.saturating_sub(LAST_USED_RESOLUTION_MS));
274 if presented
275 .last_used_at
276 .as_deref()
277 .is_some_and(|at| at >= stale.as_str())
278 {
279 return Ok(());
280 }
281 self.db
282 .prepare("UPDATE access_tokens SET last_used_at = ? WHERE id = ?")
283 .bind(&[rfc3339(now).into(), presented.id.as_str().into()])?
284 .run()
285 .await?;
286 Ok(())
287 }
288
Fine-grained personal tokens, workspace token rules and approvals in identity289 pub(crate) async fn mint(
Plan: integrations are in290 &self,
291 owner: Owner<'_>,
292 name: &str,
293 ttl_seconds: Option<u64>,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step294 grant: &Grant,
295 listed: bool,
Plan: integrations are in296 ) -> Result<CreatedAccessToken> {
297 let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20));
298 let now = now_ms();
299 let name: String = match name.trim() {
300 "" => "Access token".to_owned(),
301 name => name.chars().take(100).collect(),
302 };
303 let (user_id, workspace_id, created_by) = match owner {
304 Owner::User(id) => (Some(id), None, Some(id)),
305 Owner::Workspace { id, created_by } => (None, Some(id), created_by),
306 };
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step307 let expires_at = ttl_seconds.map(|ttl| rfc3339(now + ttl * 1000));
Plan: integrations are in308 let info = AccessToken {
309 id: new_id("tok", now),
310 name,
311 created_at: rfc3339(now),
312 last_used_at: None,
313 created_by: None,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step314 scopes: grant
315 .scopes
316 .as_ref()
317 .map(|scopes| scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
318 legacy: false,
319 expires_at: expires_at.clone(),
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers320 permissions: permissions_of(&grant.scopes.clone().unwrap_or_else(everything)),
321 workspace_owned: workspace_id.is_some(),
Fine-grained personal tokens, workspace token rules and approvals in identity322 ..AccessToken::default()
Plan: integrations are in323 };
324 self.db
325 .prepare(
326 "INSERT INTO access_tokens
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step327 (id, user_id, workspace_id, created_by, name, token_hash, created_at, expires_at,
328 scopes, listed)
329 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Plan: integrations are in330 )
331 .bind(&[
332 info.id.as_str().into(),
333 text(user_id),
334 text(workspace_id),
335 text(created_by),
336 info.name.as_str().into(),
337 crypto::sha256_hex(&token).into(),
338 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 step339 text(expires_at.as_deref()),
340 grant.scopes_column().into(),
341 JsValue::from(u8::from(listed)),
Plan: integrations are in342 ])?
343 .run()
344 .await?;
345 Ok(CreatedAccessToken { token, info })
346 }
347
Merge branch 'worktree-agent-a3abfcce648e87dca'348 /// A workspace's own token that expires and is never listed: what a
349 /// workflow job's token is minted as (job_tokens.rs).
350 pub(crate) async fn mint_for_workspace(
351 &self,
352 workspace_id: &str,
353 name: &str,
354 ttl_seconds: u64,
355 grant: &Grant,
356 ) -> Result<CreatedAccessToken> {
357 self.mint(
358 Owner::Workspace {
359 id: workspace_id,
360 created_by: None,
361 },
362 name,
363 Some(ttl_seconds),
364 grant,
365 false,
366 )
367 .await
368 }
369
Plan: integrations are in370 pub async fn create_access_token(
371 &self,
372 a: CreateAccessTokenArgs,
373 ) -> Result<CreatedAccessToken> {
374 // Told apart by the id, which says what it names, since callers pass
375 // on actors that other services stored as an id and a name.
376 let owner = if a.user.id.starts_with(WORKSPACE_ID_PREFIX) {
377 Owner::Workspace {
378 id: &a.user.id,
379 created_by: None,
380 }
381 } else {
382 Owner::User(&a.user.id)
383 };
Merge main (membership, two-factor, GitHub repo roles) into tokens384 let created = self.mint(owner, &a.name, a.ttl_seconds, &Grant::asked(&a.scopes), a.listed).await?;
385 // A person's lasting token: in their security log and their
386 // workspaces' audit logs. Short-lived ones (agents' runs, OAuth
387 // access tokens) are recorded where they are made.
388 if a.ttl_seconds.is_none() && !a.user.id.starts_with(WORKSPACE_ID_PREFIX) && !a.user.username.is_empty() {
389 self.log_security(&a.user.id, "token_created", Some(&created.info.name), None).await;
390 self.audit_account(&a.user, "token.created", &format!("Created access token {}", created.info.name)).await;
391 }
392 Ok(created)
393 }
394
395 /// `remove_access_token`: deletes one of a person's own tokens.
396 pub async fn remove_access_token(&self, a: RemoveArgs) -> Result<()> {
397 let name: Option<String> = self
398 .db
399 .prepare("DELETE FROM access_tokens WHERE id = ? AND user_id = ? RETURNING name")
400 .bind(&[a.id.as_str().into(), a.user.id.as_str().into()])?
401 .first(Some("name"))
402 .await?;
403 if let Some(name) = name {
404 self.log_security(&a.user.id, "token_deleted", Some(&name), None).await;
405 self.audit_account(&a.user, "token.deleted", &format!("Deleted access token {name}")).await;
406 }
407 Ok(())
Plan: integrations are in408 }
409
410 /// A token for a g1t agent working for `on_behalf_of`, which can do
411 /// only what `scope` lists. It is recorded as theirs, so it is listed and
412 /// can be deleted with their other tokens.
413 pub async fn create_agent_token(&self, a: CreateAgentTokenArgs) -> Result<CreatedAccessToken> {
414 let created = self
415 .mint(
416 Owner::User(&a.on_behalf_of.id),
417 &format!("g1t agent in {}/{}", a.scope.repo.namespace, a.scope.repo.name),
418 Some(a.ttl_seconds),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step419 &Grant::default(),
420 false,
Plan: integrations are in421 )
422 .await?;
423 self.db
424 .prepare("UPDATE access_tokens SET agent_scope = ? WHERE id = ?")
425 .bind(&[
426 serde_json::to_string(&a.scope)?.into(),
427 created.info.id.as_str().into(),
428 ])?
429 .run()
430 .await?;
431 Ok(created)
432 }
433
434 /// What an agent's token may do, or `None` for any other token.
435 pub async fn agent_scope(&self, a: TokenArgs) -> Result<Option<AgentScope>> {
436 let scope: Option<Option<String>> = self
437 .db
438 .prepare(format!(
439 "SELECT agent_scope FROM access_tokens
440 WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})"
441 ))
442 .bind(&[crypto::sha256_hex(&a.token).into()])?
443 .first::<Option<String>>(Some("agent_scope"))
444 .await?;
445 Ok(scope
446 .flatten()
447 .and_then(|scope| serde_json::from_str(&scope).ok()))
448 }
449
450 pub async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> {
Fine-grained personal tokens, workspace token rules and approvals in identity451 let mut tokens = self.tokens_where("access_tokens.user_id = ?", &a.user.id).await?;
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers452 // Its selected repositories, by name.
Fine-grained personal tokens, workspace token rules and approvals in identity453 self.name_repositories(&mut tokens, &Some(a.user)).await?;
454 Ok(tokens)
Plan: integrations are in455 }
456
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step457 /// The tokens a person or workspace made on purpose: those that do not
458 /// expire, and those made with an expiry from settings, rather than
459 /// those issued to an application or a hosted agent.
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers460 pub(crate) async fn tokens_where(&self, owner: &str, id: &str) -> Result<Vec<AccessToken>> {
Plan: integrations are in461 let rows = self
462 .db
463 .prepare(format!(
464 "SELECT {TOKEN_COLUMNS} FROM access_tokens
465 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 step466 WHERE {owner} AND (access_tokens.expires_at IS NULL OR access_tokens.listed = 1)
467 AND access_tokens.agent_scope IS NULL
Plan: integrations are in468 ORDER BY access_tokens.id"
469 ))
470 .bind(&[id.into()])?
471 .all()
472 .await?
473 .results::<TokenRow>()?;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step474 Ok(rows.into_iter().map(Self::info).collect())
Plan: integrations are in475 }
476
477 pub async fn list_workspace_tokens(
478 &self,
479 a: WorkspaceTokensArgs,
480 ) -> Result<Outcome<Vec<AccessToken>>> {
481 let slug = a.slug.to_lowercase();
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers482 if !a.viewer.as_ref().is_some_and(|viewer| viewer.is_member(&slug)) {
Plan: integrations are in483 return Ok(Outcome::fail(
484 FailureCode::Forbidden,
485 "Only members can see a workspace's access tokens.",
486 ));
487 }
488 let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else {
489 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
490 };
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers491 let mut tokens = self.tokens_where("access_tokens.workspace_id = ?", &workspace.id).await?;
492 self.name_repositories(&mut tokens, &a.viewer).await?;
493 Ok(Outcome::Ok(tokens))
Plan: integrations are in494 }
495
496 /// The workspace's id, if `actor` is a person who owns it.
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers497 pub(crate) async fn owned_workspace(&self, actor: &User, slug: &str) -> Result<Outcome<String>> {
Plan: integrations are in498 let slug = slug.to_lowercase();
499 if actor.kind != PrincipalKind::User || actor.role_in(&slug) != Some(Role::Owner) {
500 return Ok(Outcome::fail(
501 FailureCode::Forbidden,
502 "Only an owner can manage a workspace's access tokens.",
503 ));
504 }
505 Ok(match self.get_workspace(SlugArgs { slug }).await? {
506 Some(workspace) => Outcome::Ok(workspace.id),
507 None => Outcome::fail(FailureCode::NotFound, "Workspace not found."),
508 })
509 }
510
511 pub async fn remove_workspace_token(
512 &self,
513 a: RemoveWorkspaceTokenArgs,
514 ) -> Result<Outcome<bool>> {
515 let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? {
516 Outcome::Ok(id) => id,
517 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
518 };
Merge main (membership, two-factor, GitHub repo roles) into tokens519 let name: Option<String> = self
520 .db
521 .prepare("DELETE FROM access_tokens WHERE id = ? AND workspace_id = ? RETURNING name")
Plan: integrations are in522 .bind(&[a.id.into(), workspace_id.into()])?
Merge main (membership, two-factor, GitHub repo roles) into tokens523 .first(Some("name"))
Plan: integrations are in524 .await?;
Merge main (membership, two-factor, GitHub repo roles) into tokens525 if let Some(name) = name {
526 self.audit_workspace(
527 &a.actor,
528 "workspace_token.deleted",
529 &a.slug.to_lowercase(),
530 g1t_contracts::audit::Surface::Web,
531 format!("Deleted workspace access token {name}"),
532 )
533 .await;
534 }
Plan: integrations are in535 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 step538
539#[cfg(test)]
540mod 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 }
Merge branch 'worktree-agent-ad4439ce85a91ecb4' into integrate560
561 #[test]
562 fn only_a_persons_own_token_with_it_turned_on_uses_the_website() {
563 let row = |extra: serde_json::Value| {
564 let mut value = serde_json::json!({ "id": "tok_1", "user_id": "usr_1", "workspace_id": null, "last_used_at": null, "agent_scope": null, "scopes": "*", "website": 1.0 });
565 for (key, field) in extra.as_object().unwrap() {
566 value[key] = field.clone();
567 }
568 serde_json::from_value::<Presented>(value).unwrap()
569 };
570 assert!(website_allowed(&row(serde_json::json!({}))));
571 assert!(!website_allowed(&row(serde_json::json!({ "website": 0.0 }))));
572 assert!(!website_allowed(&row(serde_json::json!({ "website": null }))));
573 // A workspace's token, a job's token and an agent's never do.
574 assert!(!website_allowed(&row(serde_json::json!({ "user_id": null, "workspace_id": "wsp_1" }))));
575 assert!(!website_allowed(&row(serde_json::json!({ "job_id": "job_1" }))));
576 assert!(!website_allowed(&row(serde_json::json!({ "agent_scope": "{}" }))));
577 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step578}

This file's history is long; its oldest lines are credited to the oldest commit read.