Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
549 linesCodeBlameRaw
1//! Access tokens: the `g1t_…` secrets used by git, the API and the MCP
2//! server.
3//!
4//! There is one kind of token 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. Either is made and
8//! changed with permissions and a reach (token_reach.rs); this file mints,
9//! resolves, lists and deletes them.
10
11use g1t_contracts::identity::*;
12use g1t_contracts::scopes::{FULL_ACCESS, JobToken, Scope, TokenAccess, everything, parse_scopes, permissions_of, scopes_text};
13use 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;
25pub(crate) const MAX_TOKENS_PER_WORKSPACE: usize = 50;
26const WORKSPACE_ID_PREFIX: &str = "wsp_";
27
28pub(crate) const TOKEN_COLUMNS: &str = "access_tokens.id, access_tokens.name, access_tokens.created_at,
29 access_tokens.last_used_at, users.username AS created_by, access_tokens.scopes,
30 access_tokens.expires_at, access_tokens.description, access_tokens.admin,
31 access_tokens.workspace_id, access_tokens.repository_selection,
32 access_tokens.status, access_tokens.review_reason, access_tokens.website,
33 (SELECT slug FROM workspaces WHERE workspaces.id = access_tokens.owner_workspace_id) AS owner_workspace";
34
35/// Who a new token belongs to.
36pub(crate) enum Owner<'a> {
37 User(&'a str),
38 Workspace {
39 id: &'a str,
40 created_by: Option<&'a str>,
41 },
42}
43
44#[derive(Deserialize)]
45pub(crate) struct TokenRow {
46 id: String,
47 name: String,
48 created_at: String,
49 last_used_at: Option<String>,
50 created_by: Option<String>,
51 scopes: Option<String>,
52 expires_at: Option<String>,
53 /// Its reach, status, description and a workspace token's Admin
54 /// (migration 0034; see token_reach.rs).
55 #[serde(flatten)]
56 pub(crate) more: crate::token_reach::TokenRowMore,
57}
58
59/// 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),
85 }
86 }
87}
88
89/// 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
102/// 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 a sandbox run's credential: what it may do, as JSON `AgentScope`.
110 agent_scope: Option<String>,
111 scopes: Option<String>,
112 #[serde(default)]
113 name: Option<String>,
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>,
124 /// 1 when its owner let it use the website (migration 0043).
125 #[serde(default)]
126 website: Option<f64>,
127 /// 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).
130 #[serde(flatten)]
131 facts: crate::token_reach::Facts,
132}
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
144/// 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
155impl 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!(
163 "SELECT id, user_id, workspace_id, last_used_at, agent_scope, scopes, name,
164 repo, job_id, job_run_id, job_pulls, created_at, expires_at,
165 owner_workspace_id, repository_selection, status, admin, website, purpose
166 FROM access_tokens
167 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 };
175 // A sandbox run's credential (or an older agent token): g1t on
176 // behalf of the person it was made for, in its repository's
177 // workspace while they belong to it, and only for what its scope
178 // lists. See run_credentials.rs.
179 if let Some(scope) = presented
180 .agent_scope
181 .as_deref()
182 .and_then(|scope| serde_json::from_str::<AgentScope>(scope).ok())
183 {
184 return self
185 .agent_principal(
186 &presented.id,
187 presented.user_id.as_deref(),
188 presented.workspace_id.as_deref(),
189 scope,
190 )
191 .await;
192 }
193 let mut viewer = match (&presented.user_id, &presented.workspace_id) {
194 (Some(user_id), _) => {
195 self.find_user(
196 "SELECT id, username, display_username, email_verified_at IS NOT NULL AS verified, avatar
197 FROM users WHERE id = ? AND deleted_at IS NULL",
198 user_id,
199 )
200 .await?
201 }
202 (None, Some(workspace_id)) => self.workspace_principal(workspace_id).await?,
203 (None, None) => None,
204 };
205 if let Some(user) = viewer.as_mut() {
206 self.note_use(&presented).await?;
207 let (scopes, legacy) = stored_scopes(presented.scopes.as_deref());
208 user.token = Some(Box::new(TokenAccess {
209 token_id: presented.id.clone(),
210 scopes,
211 legacy,
212 name: presented.name.clone(),
213 repo: presented.repo.clone(),
214 job: match (&presented.job_id, &presented.job_run_id) {
215 (Some(job_id), Some(run_id)) => Some(JobToken {
216 run_id: run_id.clone(),
217 job_id: job_id.clone(),
218 pull_requests: presented.job_pulls == Some(1),
219 }),
220 _ => None,
221 },
222 website: website_allowed(&presented),
223 ..TokenAccess::default()
224 }));
225 // What it reaches: the workspace it is made for and its
226 // repositories, the workspaces whose rules let it in, a
227 // workspace token's role.
228 self.apply_reach(user, &presented.id, presented.user_id.is_some(), &presented.facts).await?;
229 }
230 Ok(viewer)
231 }
232
233 pub(crate) fn info(row: TokenRow) -> AccessToken {
234 let (scopes, legacy) = stored_scopes(row.scopes.as_deref());
235 let held: Vec<Scope> = scopes.as_ref().map_or_else(everything, |scopes| scopes.iter().filter_map(|scope| Scope::parse(scope)).collect());
236 let mut info = AccessToken {
237 id: row.id,
238 name: row.name,
239 created_at: row.created_at,
240 last_used_at: row.last_used_at,
241 created_by: row.created_by,
242 scopes,
243 legacy,
244 expires_at: row.expires_at,
245 permissions: permissions_of(&held),
246 ..AccessToken::default()
247 };
248 row.more.describe(&mut info);
249 info
250 }
251
252 /// A workspace as the actor behind one of its own tokens. It can do
253 /// what a member can, in that workspace only.
254 pub(crate) async fn workspace_principal(&self, workspace_id: &str) -> Result<Viewer> {
255 let workspace = self
256 .db
257 // A deleted workspace's tokens are refused until it is restored,
258 // and a suspended one's until staff lift it (suspension.rs).
259 .prepare("SELECT id, slug FROM workspaces WHERE id = ? AND deleted_at IS NULL AND suspended_at IS NULL")
260 .bind(&[workspace_id.into()])?
261 .first::<WorkspaceRef>(None)
262 .await?;
263 Ok(workspace.map(|workspace| User {
264 id: workspace.id,
265 username: workspace.slug.clone(),
266 kind: PrincipalKind::Workspace,
267 verified: true,
268 workspaces: vec![Membership::member(workspace.slug)],
269 ..User::default()
270 }))
271 }
272
273 async fn note_use(&self, presented: &Presented) -> Result<()> {
274 let now = now_ms();
275 let stale = rfc3339(now.saturating_sub(LAST_USED_RESOLUTION_MS));
276 if presented
277 .last_used_at
278 .as_deref()
279 .is_some_and(|at| at >= stale.as_str())
280 {
281 return Ok(());
282 }
283 self.db
284 .prepare("UPDATE access_tokens SET last_used_at = ? WHERE id = ?")
285 .bind(&[rfc3339(now).into(), presented.id.as_str().into()])?
286 .run()
287 .await?;
288 Ok(())
289 }
290
291 pub(crate) async fn mint(
292 &self,
293 owner: Owner<'_>,
294 name: &str,
295 ttl_seconds: Option<u64>,
296 grant: &Grant,
297 listed: bool,
298 ) -> Result<CreatedAccessToken> {
299 let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20));
300 let now = now_ms();
301 let name: String = match name.trim() {
302 "" => "Access token".to_owned(),
303 name => name.chars().take(100).collect(),
304 };
305 let (user_id, workspace_id, created_by) = match owner {
306 Owner::User(id) => (Some(id), None, Some(id)),
307 Owner::Workspace { id, created_by } => (None, Some(id), created_by),
308 };
309 let expires_at = ttl_seconds.map(|ttl| rfc3339(now + ttl * 1000));
310 let info = AccessToken {
311 id: new_id("tok", now),
312 name,
313 created_at: rfc3339(now),
314 last_used_at: None,
315 created_by: None,
316 scopes: grant
317 .scopes
318 .as_ref()
319 .map(|scopes| scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
320 legacy: false,
321 expires_at: expires_at.clone(),
322 permissions: permissions_of(&grant.scopes.clone().unwrap_or_else(everything)),
323 workspace_owned: workspace_id.is_some(),
324 ..AccessToken::default()
325 };
326 self.db
327 .prepare(
328 "INSERT INTO access_tokens
329 (id, user_id, workspace_id, created_by, name, token_hash, created_at, expires_at,
330 scopes, listed)
331 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
332 )
333 .bind(&[
334 info.id.as_str().into(),
335 text(user_id),
336 text(workspace_id),
337 text(created_by),
338 info.name.as_str().into(),
339 crypto::sha256_hex(&token).into(),
340 info.created_at.as_str().into(),
341 text(expires_at.as_deref()),
342 grant.scopes_column().into(),
343 JsValue::from(u8::from(listed)),
344 ])?
345 .run()
346 .await?;
347 Ok(CreatedAccessToken { token, info })
348 }
349
350 /// A workspace's own token that expires and is never listed: what a
351 /// workflow job's token is minted as (job_tokens.rs).
352 pub(crate) async fn mint_for_workspace(
353 &self,
354 workspace_id: &str,
355 name: &str,
356 ttl_seconds: u64,
357 grant: &Grant,
358 ) -> Result<CreatedAccessToken> {
359 self.mint(
360 Owner::Workspace {
361 id: workspace_id,
362 created_by: None,
363 },
364 name,
365 Some(ttl_seconds),
366 grant,
367 false,
368 )
369 .await
370 }
371
372 pub async fn create_access_token(
373 &self,
374 a: CreateAccessTokenArgs,
375 ) -> Result<CreatedAccessToken> {
376 // Told apart by the id, which says what it names, since callers pass
377 // on actors that other services stored as an id and a name.
378 let owner = if a.user.id.starts_with(WORKSPACE_ID_PREFIX) {
379 Owner::Workspace {
380 id: &a.user.id,
381 created_by: None,
382 }
383 } else {
384 Owner::User(&a.user.id)
385 };
386 let created = self.mint(owner, &a.name, a.ttl_seconds, &Grant::asked(&a.scopes), a.listed).await?;
387 // One repository only, as a workflow job's token is held to its
388 // own: a session g1t starts on someone's Anthropic account.
389 if let Some(repo) = a.repo.as_deref().map(str::trim).filter(|repo| repo.contains('/')) {
390 self.db
391 .prepare("UPDATE access_tokens SET repo = ? WHERE id = ?")
392 .bind(&[repo.to_lowercase().into(), created.info.id.as_str().into()])?
393 .run()
394 .await?;
395 }
396 // A person's lasting token: in their security log and their
397 // workspaces' audit logs. Short-lived ones (agents' runs, OAuth
398 // access tokens) are recorded where they are made.
399 if a.ttl_seconds.is_none() && !a.user.id.starts_with(WORKSPACE_ID_PREFIX) && !a.user.username.is_empty() {
400 self.log_security(&a.user.id, "token_created", Some(&created.info.name), None).await;
401 self.audit_account(&a.user, "token.created", &format!("Created access token {}", created.info.name)).await;
402 }
403 Ok(created)
404 }
405
406 /// `remove_access_token`: deletes one of a person's own tokens.
407 pub async fn remove_access_token(&self, a: RemoveArgs) -> Result<()> {
408 let name: Option<String> = self
409 .db
410 .prepare("DELETE FROM access_tokens WHERE id = ? AND user_id = ? RETURNING name")
411 .bind(&[a.id.as_str().into(), a.user.id.as_str().into()])?
412 .first(Some("name"))
413 .await?;
414 if let Some(name) = name {
415 self.log_security(&a.user.id, "token_deleted", Some(&name), None).await;
416 self.audit_account(&a.user, "token.deleted", &format!("Deleted access token {name}")).await;
417 }
418 Ok(())
419 }
420
421 pub async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> {
422 let mut tokens = self.tokens_where("access_tokens.user_id = ?", &a.user.id).await?;
423 // Its selected repositories, by name.
424 self.name_repositories(&mut tokens, &Some(a.user)).await?;
425 Ok(tokens)
426 }
427
428 /// The tokens a person or workspace made on purpose: those that do not
429 /// expire, and those made with an expiry from settings, rather than
430 /// those issued to an application or a hosted agent.
431 pub(crate) async fn tokens_where(&self, owner: &str, id: &str) -> Result<Vec<AccessToken>> {
432 let rows = self
433 .db
434 .prepare(format!(
435 "SELECT {TOKEN_COLUMNS} FROM access_tokens
436 LEFT JOIN users ON users.id = access_tokens.created_by
437 WHERE {owner} AND (access_tokens.expires_at IS NULL OR access_tokens.listed = 1)
438 AND access_tokens.agent_scope IS NULL
439 ORDER BY access_tokens.id"
440 ))
441 .bind(&[id.into()])?
442 .all()
443 .await?
444 .results::<TokenRow>()?;
445 Ok(rows.into_iter().map(Self::info).collect())
446 }
447
448 pub async fn list_workspace_tokens(
449 &self,
450 a: WorkspaceTokensArgs,
451 ) -> Result<Outcome<Vec<AccessToken>>> {
452 let slug = a.slug.to_lowercase();
453 if !a.viewer.as_ref().is_some_and(|viewer| viewer.is_member(&slug)) {
454 return Ok(Outcome::fail(
455 FailureCode::Forbidden,
456 "Only members can see a workspace's access tokens.",
457 ));
458 }
459 let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else {
460 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
461 };
462 let mut tokens = self.tokens_where("access_tokens.workspace_id = ?", &workspace.id).await?;
463 self.name_repositories(&mut tokens, &a.viewer).await?;
464 Ok(Outcome::Ok(tokens))
465 }
466
467 /// The workspace's id, if `actor` is a person who owns it.
468 pub(crate) async fn owned_workspace(&self, actor: &User, slug: &str) -> Result<Outcome<String>> {
469 let slug = slug.to_lowercase();
470 if actor.kind != PrincipalKind::User || actor.role_in(&slug) != Some(Role::Owner) {
471 return Ok(Outcome::fail(
472 FailureCode::Forbidden,
473 "Only an owner can manage a workspace's access tokens.",
474 ));
475 }
476 Ok(match self.get_workspace(SlugArgs { slug }).await? {
477 Some(workspace) => Outcome::Ok(workspace.id),
478 None => Outcome::fail(FailureCode::NotFound, "Workspace not found."),
479 })
480 }
481
482 pub async fn remove_workspace_token(
483 &self,
484 a: RemoveWorkspaceTokenArgs,
485 ) -> Result<Outcome<bool>> {
486 let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? {
487 Outcome::Ok(id) => id,
488 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
489 };
490 let name: Option<String> = self
491 .db
492 .prepare("DELETE FROM access_tokens WHERE id = ? AND workspace_id = ? RETURNING name")
493 .bind(&[a.id.into(), workspace_id.into()])?
494 .first(Some("name"))
495 .await?;
496 if let Some(name) = name {
497 self.audit_workspace(
498 &a.actor,
499 "workspace_token.deleted",
500 &a.slug.to_lowercase(),
501 g1t_contracts::audit::Surface::Web,
502 format!("Deleted workspace access token {name}"),
503 )
504 .await;
505 }
506 Ok(Outcome::Ok(true))
507 }
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513
514 #[test]
515 fn a_row_without_scopes_is_legacy_full_access() {
516 assert_eq!(stored_scopes(None), (None, true));
517 assert_eq!(stored_scopes(Some("*")), (None, false));
518 assert_eq!(
519 stored_scopes(Some("issues:write repo:read nonsense")),
520 (Some(vec!["repo:read".to_owned(), "issues:write".to_owned()]), false)
521 );
522 }
523
524 #[test]
525 fn scopes_are_stored_as_text() {
526 let grant = Grant::asked(&Some(vec!["issues:read".to_owned(), "bogus".to_owned()]));
527 assert_eq!(grant.scopes_column(), "issues:read");
528 assert_eq!(Grant::asked(&None).scopes_column(), "*");
529 assert_eq!(Grant::asked(&Some(vec![])).scopes_column(), "");
530 }
531
532 #[test]
533 fn only_a_persons_own_token_with_it_turned_on_uses_the_website() {
534 let row = |extra: serde_json::Value| {
535 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 });
536 for (key, field) in extra.as_object().unwrap() {
537 value[key] = field.clone();
538 }
539 serde_json::from_value::<Presented>(value).unwrap()
540 };
541 assert!(website_allowed(&row(serde_json::json!({}))));
542 assert!(!website_allowed(&row(serde_json::json!({ "website": 0.0 }))));
543 assert!(!website_allowed(&row(serde_json::json!({ "website": null }))));
544 // A workspace's token, a job's token and an agent's never do.
545 assert!(!website_allowed(&row(serde_json::json!({ "user_id": null, "workspace_id": "wsp_1" }))));
546 assert!(!website_allowed(&row(serde_json::json!({ "job_id": "job_1" }))));
547 assert!(!website_allowed(&row(serde_json::json!({ "agent_scope": "{}" }))));
548 }
549}