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