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