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