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