flagon-io/g1t

public

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/services/identity/src/tokens.rs

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