g1t/services/identity/src/tokens.rs

515 lines18,437 bytesCodeBlame

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 shell1//! 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
9use g1t_contracts::identity::*;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step10use g1t_contracts::scopes::{FULL_ACCESS, Scope, TokenAccess, parse_scopes, scopes_text};
Agents as a team: lifecycle, merge queue, billing and a new shell11use g1t_contracts::time::{SQL_NOW, rfc3339};
12use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, Role, User, Viewer, new_id};
13use g1t_kit::now_ms;
14use serde::Deserialize;
15use worker::Result;
16use worker::wasm_bindgen::JsValue;
17
18use crate::{Identity, crypto};
19
20pub const TOKEN_PREFIX: &str = "g1t_";
21/// How stale a token's last-used time may get before it is written again.
22const LAST_USED_RESOLUTION_MS: u64 = 5 * 60 * 1000;
23const MAX_TOKENS_PER_WORKSPACE: usize = 50;
24const WORKSPACE_ID_PREFIX: &str = "wsp_";
25
26const 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 step27 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 shell29
30/// Who a new token belongs to.
31enum Owner<'a> {
32 User(&'a str),
33 Workspace {
34 id: &'a str,
35 created_by: Option<&'a str>,
36 },
37}
38
39#[derive(Deserialize)]
40struct 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 step46 scopes: Option<String>,
47 expires_at: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell48}
49
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step50/// 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)]
58pub(crate) struct Grant {
59 /// Null: full access.
60 pub scopes: Option<Vec<Scope>>,
61}
62
63impl 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 shell76 }
77 }
78}
79
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step80/// A `scopes` column read back: the scopes (null for full access), and
81/// whether it is a legacy row, made before scopes.
82pub(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 shell93/// The owner of a token being used.
94#[derive(Deserialize)]
95struct 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 step102 scopes: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell103}
104
105#[derive(Deserialize)]
106struct WorkspaceRef {
107 id: String,
108 slug: String,
109}
110
111fn text(value: Option<&str>) -> JsValue {
112 value.map_or(JsValue::NULL, JsValue::from)
113}
114
115impl Identity {
116 pub async fn user_for_access_token(&self, token: &str) -> Result<Viewer> {
117 if !token.starts_with(TOKEN_PREFIX) {
118 return Ok(None);
119 }
120 let Some(presented) = self
121 .db
122 .prepare(format!(
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step123 "SELECT id, user_id, workspace_id, last_used_at, agent_scope, scopes
124 FROM access_tokens
Agents as a team: lifecycle, merge queue, billing and a new shell125 WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})"
126 ))
127 .bind(&[crypto::sha256_hex(token).into()])?
128 .first::<Presented>(None)
129 .await?
130 else {
131 return Ok(None);
132 };
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent133 // 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 API134 // for, in its repository's workspace while they belong to it, and
135 // only for what its scope lists. See run_credentials.rs.
Agents as a team: lifecycle, merge queue, billing and a new shell136 if let Some(scope) = presented
137 .agent_scope
138 .as_deref()
139 .and_then(|scope| serde_json::from_str::<AgentScope>(scope).ok())
140 {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API141 return self
142 .agent_principal(
143 &presented.id,
144 presented.user_id.as_deref(),
145 presented.workspace_id.as_deref(),
146 scope,
147 )
148 .await;
Agents as a team: lifecycle, merge queue, billing and a new shell149 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step150 let mut viewer = match (&presented.user_id, &presented.workspace_id) {
Agents as a team: lifecycle, merge queue, billing and a new shell151 (Some(user_id), _) => {
152 self.find_user(
153 "SELECT id, username, email_verified_at IS NOT NULL AS verified
154 FROM users WHERE id = ?",
155 user_id,
156 )
157 .await?
158 }
159 (None, Some(workspace_id)) => self.workspace_principal(workspace_id).await?,
160 (None, None) => None,
161 };
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step162 if let Some(user) = viewer.as_mut() {
Agents as a team: lifecycle, merge queue, billing and a new shell163 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 step164 let (scopes, legacy) = stored_scopes(presented.scopes.as_deref());
165 user.token = Some(Box::new(TokenAccess {
166 token_id: presented.id.clone(),
167 scopes,
168 legacy,
169 }));
Agents as a team: lifecycle, merge queue, billing and a new shell170 }
171 Ok(viewer)
172 }
173
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step174 fn info(row: TokenRow) -> AccessToken {
175 let (scopes, legacy) = stored_scopes(row.scopes.as_deref());
176 AccessToken {
177 id: row.id,
178 name: row.name,
179 created_at: row.created_at,
180 last_used_at: row.last_used_at,
181 created_by: row.created_by,
182 scopes,
183 legacy,
184 expires_at: row.expires_at,
185 }
186 }
187
Agents as a team: lifecycle, merge queue, billing and a new shell188 /// A workspace as the actor behind one of its own tokens. It can do
189 /// 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 API190 pub(crate) async fn workspace_principal(&self, workspace_id: &str) -> Result<Viewer> {
Agents as a team: lifecycle, merge queue, billing and a new shell191 let workspace = self
192 .db
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member193 // A deleted workspace's tokens are refused until it is restored.
194 .prepare("SELECT id, slug FROM workspaces WHERE id = ? AND deleted_at IS NULL")
Agents as a team: lifecycle, merge queue, billing and a new shell195 .bind(&[workspace_id.into()])?
196 .first::<WorkspaceRef>(None)
197 .await?;
198 Ok(workspace.map(|workspace| User {
199 id: workspace.id,
200 username: workspace.slug.clone(),
201 kind: PrincipalKind::Workspace,
202 verified: true,
Workspace names and icons, and a component kit for every control203 workspaces: vec![Membership::member(workspace.slug)],
204 ..User::default()
Agents as a team: lifecycle, merge queue, billing and a new shell205 }))
206 }
207
208 async fn note_use(&self, presented: &Presented) -> Result<()> {
209 let now = now_ms();
210 let stale = rfc3339(now.saturating_sub(LAST_USED_RESOLUTION_MS));
211 if presented
212 .last_used_at
213 .as_deref()
214 .is_some_and(|at| at >= stale.as_str())
215 {
216 return Ok(());
217 }
218 self.db
219 .prepare("UPDATE access_tokens SET last_used_at = ? WHERE id = ?")
220 .bind(&[rfc3339(now).into(), presented.id.as_str().into()])?
221 .run()
222 .await?;
223 Ok(())
224 }
225
226 async fn mint(
227 &self,
228 owner: Owner<'_>,
229 name: &str,
230 ttl_seconds: Option<u64>,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step231 grant: &Grant,
232 listed: bool,
Agents as a team: lifecycle, merge queue, billing and a new shell233 ) -> Result<CreatedAccessToken> {
234 let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20));
235 let now = now_ms();
236 let name: String = match name.trim() {
237 "" => "Access token".to_owned(),
238 name => name.chars().take(100).collect(),
239 };
240 let (user_id, workspace_id, created_by) = match owner {
241 Owner::User(id) => (Some(id), None, Some(id)),
242 Owner::Workspace { id, created_by } => (None, Some(id), created_by),
243 };
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step244 let expires_at = ttl_seconds.map(|ttl| rfc3339(now + ttl * 1000));
Agents as a team: lifecycle, merge queue, billing and a new shell245 let info = AccessToken {
246 id: new_id("tok", now),
247 name,
248 created_at: rfc3339(now),
249 last_used_at: None,
250 created_by: None,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step251 scopes: grant
252 .scopes
253 .as_ref()
254 .map(|scopes| scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
255 legacy: false,
256 expires_at: expires_at.clone(),
Agents as a team: lifecycle, merge queue, billing and a new shell257 };
258 self.db
259 .prepare(
260 "INSERT INTO access_tokens
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step261 (id, user_id, workspace_id, created_by, name, token_hash, created_at, expires_at,
262 scopes, listed)
263 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell264 )
265 .bind(&[
266 info.id.as_str().into(),
267 text(user_id),
268 text(workspace_id),
269 text(created_by),
270 info.name.as_str().into(),
271 crypto::sha256_hex(&token).into(),
272 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 step273 text(expires_at.as_deref()),
274 grant.scopes_column().into(),
275 JsValue::from(u8::from(listed)),
Agents as a team: lifecycle, merge queue, billing and a new shell276 ])?
277 .run()
278 .await?;
279 Ok(CreatedAccessToken { token, info })
280 }
281
282 pub async fn create_access_token(
283 &self,
284 a: CreateAccessTokenArgs,
285 ) -> Result<CreatedAccessToken> {
286 // Told apart by the id, which says what it names, since callers pass
287 // on actors that other services stored as an id and a name.
288 let owner = if a.user.id.starts_with(WORKSPACE_ID_PREFIX) {
289 Owner::Workspace {
290 id: &a.user.id,
291 created_by: None,
292 }
293 } else {
294 Owner::User(&a.user.id)
295 };
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step296 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 shell297 }
298
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step299 /// Changes what one of a person's own tokens may do.
300 pub async fn update_access_token(&self, a: UpdateAccessTokenArgs) -> Result<Outcome<AccessToken>> {
301 let grant = Grant::asked(&a.scopes);
302 let found: Option<String> = self
303 .db
304 .prepare(
305 "UPDATE access_tokens SET scopes = ?
306 WHERE id = ? AND user_id = ? AND agent_scope IS NULL
307 RETURNING id",
308 )
309 .bind(&[
310 grant.scopes_column().into(),
311 a.id.as_str().into(),
312 a.user.id.as_str().into(),
313 ])?
314 .first(Some("id"))
315 .await?;
316 if found.is_none() {
317 return Ok(Outcome::fail(FailureCode::NotFound, "No such token."));
318 }
319 let row = self
320 .db
321 .prepare(format!(
322 "SELECT {TOKEN_COLUMNS} FROM access_tokens
323 LEFT JOIN users ON users.id = access_tokens.created_by
324 WHERE access_tokens.id = ?"
325 ))
326 .bind(&[a.id.into()])?
327 .first::<TokenRow>(None)
328 .await?;
329 match row {
330 Some(row) => Ok(Outcome::Ok(Self::info(row))),
331 None => Ok(Outcome::fail(FailureCode::NotFound, "No such token.")),
332 }
333 }
334
Agents as a team: lifecycle, merge queue, billing and a new shell335 /// A token for a g1t agent working for `on_behalf_of`, which can do
336 /// only what `scope` lists. It is recorded as theirs, so it is listed and
337 /// can be deleted with their other tokens.
338 pub async fn create_agent_token(&self, a: CreateAgentTokenArgs) -> Result<CreatedAccessToken> {
339 let created = self
340 .mint(
341 Owner::User(&a.on_behalf_of.id),
342 &format!("g1t agent in {}/{}", a.scope.repo.namespace, a.scope.repo.name),
343 Some(a.ttl_seconds),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step344 &Grant::default(),
345 false,
Agents as a team: lifecycle, merge queue, billing and a new shell346 )
347 .await?;
348 self.db
349 .prepare("UPDATE access_tokens SET agent_scope = ? WHERE id = ?")
350 .bind(&[
351 serde_json::to_string(&a.scope)?.into(),
352 created.info.id.as_str().into(),
353 ])?
354 .run()
355 .await?;
356 Ok(created)
357 }
358
359 /// What an agent's token may do, or `None` for any other token.
360 pub async fn agent_scope(&self, a: TokenArgs) -> Result<Option<AgentScope>> {
361 let scope: Option<Option<String>> = self
362 .db
363 .prepare(format!(
364 "SELECT agent_scope FROM access_tokens
365 WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})"
366 ))
367 .bind(&[crypto::sha256_hex(&a.token).into()])?
368 .first::<Option<String>>(Some("agent_scope"))
369 .await?;
370 Ok(scope
371 .flatten()
372 .and_then(|scope| serde_json::from_str(&scope).ok()))
373 }
374
375 pub async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> {
376 self.tokens_where("access_tokens.user_id = ?", &a.user.id)
377 .await
378 }
379
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step380 /// The tokens a person or workspace made on purpose: those that do not
381 /// expire, and those made with an expiry from settings, rather than
382 /// those issued to an application or a hosted agent.
Agents as a team: lifecycle, merge queue, billing and a new shell383 async fn tokens_where(&self, owner: &str, id: &str) -> Result<Vec<AccessToken>> {
384 let rows = self
385 .db
386 .prepare(format!(
387 "SELECT {TOKEN_COLUMNS} FROM access_tokens
388 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 step389 WHERE {owner} AND (access_tokens.expires_at IS NULL OR access_tokens.listed = 1)
390 AND access_tokens.agent_scope IS NULL
Agents as a team: lifecycle, merge queue, billing and a new shell391 ORDER BY access_tokens.id"
392 ))
393 .bind(&[id.into()])?
394 .all()
395 .await?
396 .results::<TokenRow>()?;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step397 Ok(rows.into_iter().map(Self::info).collect())
Agents as a team: lifecycle, merge queue, billing and a new shell398 }
399
400 pub async fn list_workspace_tokens(
401 &self,
402 a: WorkspaceTokensArgs,
403 ) -> Result<Outcome<Vec<AccessToken>>> {
404 let slug = a.slug.to_lowercase();
405 if !a.viewer.is_some_and(|viewer| viewer.is_member(&slug)) {
406 return Ok(Outcome::fail(
407 FailureCode::Forbidden,
408 "Only members can see a workspace's access tokens.",
409 ));
410 }
411 let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else {
412 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
413 };
414 Ok(Outcome::Ok(
415 self.tokens_where("access_tokens.workspace_id = ?", &workspace.id)
416 .await?,
417 ))
418 }
419
420 /// The workspace's id, if `actor` is a person who owns it.
421 async fn owned_workspace(&self, actor: &User, slug: &str) -> Result<Outcome<String>> {
422 let slug = slug.to_lowercase();
423 if actor.kind != PrincipalKind::User || actor.role_in(&slug) != Some(Role::Owner) {
424 return Ok(Outcome::fail(
425 FailureCode::Forbidden,
426 "Only an owner can manage a workspace's access tokens.",
427 ));
428 }
429 Ok(match self.get_workspace(SlugArgs { slug }).await? {
430 Some(workspace) => Outcome::Ok(workspace.id),
431 None => Outcome::fail(FailureCode::NotFound, "Workspace not found."),
432 })
433 }
434
435 pub async fn create_workspace_token(
436 &self,
437 a: CreateWorkspaceTokenArgs,
438 ) -> Result<Outcome<CreatedAccessToken>> {
439 let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? {
440 Outcome::Ok(id) => id,
441 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
442 };
443 if a.name.trim().is_empty() {
444 return Ok(Outcome::fail(
445 FailureCode::Invalid,
446 "Name the token after what will use it.",
447 ));
448 }
449 let existing = self
450 .tokens_where("access_tokens.workspace_id = ?", &workspace_id)
451 .await?;
452 if existing.len() >= MAX_TOKENS_PER_WORKSPACE {
453 return Ok(Outcome::fail(
454 FailureCode::Conflict,
455 "This workspace has the maximum number of access tokens. Delete one first.",
456 ));
457 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step458 // A workspace's token reaches that workspace only: it acts as the
459 // workspace (see `workspace_principal`), narrowed by its scopes.
460 let grant = Grant::asked(&a.scopes);
Agents as a team: lifecycle, merge queue, billing and a new shell461 let mut created = self
462 .mint(
463 Owner::Workspace {
464 id: &workspace_id,
465 created_by: Some(&a.actor.id),
466 },
467 &a.name,
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step468 a.ttl_seconds,
469 &grant,
470 true,
Agents as a team: lifecycle, merge queue, billing and a new shell471 )
472 .await?;
473 created.info.created_by = Some(a.actor.username);
474 Ok(Outcome::Ok(created))
475 }
476
477 pub async fn remove_workspace_token(
478 &self,
479 a: RemoveWorkspaceTokenArgs,
480 ) -> Result<Outcome<bool>> {
481 let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? {
482 Outcome::Ok(id) => id,
483 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
484 };
485 self.db
486 .prepare("DELETE FROM access_tokens WHERE id = ? AND workspace_id = ?")
487 .bind(&[a.id.into(), workspace_id.into()])?
488 .run()
489 .await?;
490 Ok(Outcome::Ok(true))
491 }
492}
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step493
494#[cfg(test)]
495mod tests {
496 use super::*;
497
498 #[test]
499 fn a_row_without_scopes_is_legacy_full_access() {
500 assert_eq!(stored_scopes(None), (None, true));
501 assert_eq!(stored_scopes(Some("*")), (None, false));
502 assert_eq!(
503 stored_scopes(Some("issues:write repo:read nonsense")),
504 (Some(vec!["repo:read".to_owned(), "issues:write".to_owned()]), false)
505 );
506 }
507
508 #[test]
509 fn scopes_are_stored_as_text() {
510 let grant = Grant::asked(&Some(vec!["issues:read".to_owned(), "bogus".to_owned()]));
511 assert_eq!(grant.scopes_column(), "issues:read");
512 assert_eq!(Grant::asked(&None).scopes_column(), "*");
513 assert_eq!(Grant::asked(&Some(vec![])).scopes_column(), "");
514 }
515}