g1t/services/identity/src/tokens.rs
Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Agents as a team: lifecycle, merge queue, billing and a new shell | 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 | ||
| 9 | use g1t_contracts::identity::*; | |
| 10 | use g1t_contracts::time::{SQL_NOW, rfc3339}; | |
| 11 | use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, Role, User, Viewer, new_id}; | |
| 12 | use g1t_kit::now_ms; | |
| 13 | use serde::Deserialize; | |
| 14 | use worker::Result; | |
| 15 | use worker::wasm_bindgen::JsValue; | |
| 16 | ||
| 17 | use crate::{Identity, crypto}; | |
| 18 | ||
| 19 | pub const TOKEN_PREFIX: &str = "g1t_"; | |
| 20 | /// How stale a token's last-used time may get before it is written again. | |
| 21 | const LAST_USED_RESOLUTION_MS: u64 = 5 * 60 * 1000; | |
| 22 | const MAX_TOKENS_PER_WORKSPACE: usize = 50; | |
| 23 | const WORKSPACE_ID_PREFIX: &str = "wsp_"; | |
| 24 | ||
| 25 | const TOKEN_COLUMNS: &str = "access_tokens.id, access_tokens.name, access_tokens.created_at, | |
| 26 | access_tokens.last_used_at, users.username AS created_by"; | |
| 27 | ||
| 28 | /// Who a new token belongs to. | |
| 29 | enum Owner<'a> { | |
| 30 | User(&'a str), | |
| 31 | Workspace { | |
| 32 | id: &'a str, | |
| 33 | created_by: Option<&'a str>, | |
| 34 | }, | |
| 35 | } | |
| 36 | ||
| 37 | #[derive(Deserialize)] | |
| 38 | struct TokenRow { | |
| 39 | id: String, | |
| 40 | name: String, | |
| 41 | created_at: String, | |
| 42 | last_used_at: Option<String>, | |
| 43 | created_by: Option<String>, | |
| 44 | } | |
| 45 | ||
| 46 | impl From<TokenRow> for AccessToken { | |
| 47 | fn from(row: TokenRow) -> Self { | |
| 48 | AccessToken { | |
| 49 | id: row.id, | |
| 50 | name: row.name, | |
| 51 | created_at: row.created_at, | |
| 52 | last_used_at: row.last_used_at, | |
| 53 | created_by: row.created_by, | |
| 54 | } | |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | /// The owner of a token being used. | |
| 59 | #[derive(Deserialize)] | |
| 60 | struct Presented { | |
| 61 | id: String, | |
| 62 | user_id: Option<String>, | |
| 63 | workspace_id: Option<String>, | |
| 64 | last_used_at: Option<String>, | |
| 65 | /// Set on an agent's token: what it may do, as JSON `AgentScope`. | |
| 66 | agent_scope: Option<String>, | |
| 67 | } | |
| 68 | ||
| 69 | #[derive(Deserialize)] | |
| 70 | struct WorkspaceRef { | |
| 71 | id: String, | |
| 72 | slug: String, | |
| 73 | } | |
| 74 | ||
| 75 | fn text(value: Option<&str>) -> JsValue { | |
| 76 | value.map_or(JsValue::NULL, JsValue::from) | |
| 77 | } | |
| 78 | ||
| 79 | impl Identity { | |
| 80 | pub async fn user_for_access_token(&self, token: &str) -> Result<Viewer> { | |
| 81 | if !token.starts_with(TOKEN_PREFIX) { | |
| 82 | return Ok(None); | |
| 83 | } | |
| 84 | let Some(presented) = self | |
| 85 | .db | |
| 86 | .prepare(format!( | |
| 87 | "SELECT id, user_id, workspace_id, last_used_at, agent_scope FROM access_tokens | |
| 88 | WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})" | |
| 89 | )) | |
| 90 | .bind(&[crypto::sha256_hex(token).into()])? | |
| 91 | .first::<Presented>(None) | |
| 92 | .await? | |
| 93 | else { | |
| 94 | return Ok(None); | |
| 95 | }; | |
| 96 | // An agent's token: g1t-agent, a member of its repository's | |
| 97 | // workspace, and only for what its scope lists. | |
| 98 | if let Some(scope) = presented | |
| 99 | .agent_scope | |
| 100 | .as_deref() | |
| 101 | .and_then(|scope| serde_json::from_str::<AgentScope>(scope).ok()) | |
| 102 | { | |
| 103 | return Ok(Some(User { | |
| 104 | id: AGENT_ID.to_owned(), | |
| 105 | username: AGENT_NAME.to_owned(), | |
| 106 | kind: PrincipalKind::Agent, | |
| 107 | verified: true, | |
| Workspace names and icons, and a component kit for every control | 108 | workspaces: vec![Membership::member(scope.repo.namespace)], |
| 109 | ..User::default() | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 110 | })); |
| 111 | } | |
| 112 | let viewer = match (&presented.user_id, &presented.workspace_id) { | |
| 113 | (Some(user_id), _) => { | |
| 114 | self.find_user( | |
| 115 | "SELECT id, username, email_verified_at IS NOT NULL AS verified | |
| 116 | FROM users WHERE id = ?", | |
| 117 | user_id, | |
| 118 | ) | |
| 119 | .await? | |
| 120 | } | |
| 121 | (None, Some(workspace_id)) => self.workspace_principal(workspace_id).await?, | |
| 122 | (None, None) => None, | |
| 123 | }; | |
| 124 | if viewer.is_some() { | |
| 125 | self.note_use(&presented).await?; | |
| 126 | } | |
| 127 | Ok(viewer) | |
| 128 | } | |
| 129 | ||
| 130 | /// A workspace as the actor behind one of its own tokens. It can do | |
| 131 | /// what a member can, in that workspace only. | |
| 132 | async fn workspace_principal(&self, workspace_id: &str) -> Result<Viewer> { | |
| 133 | let workspace = self | |
| 134 | .db | |
| 135 | .prepare("SELECT id, slug FROM workspaces WHERE id = ?") | |
| 136 | .bind(&[workspace_id.into()])? | |
| 137 | .first::<WorkspaceRef>(None) | |
| 138 | .await?; | |
| 139 | Ok(workspace.map(|workspace| User { | |
| 140 | id: workspace.id, | |
| 141 | username: workspace.slug.clone(), | |
| 142 | kind: PrincipalKind::Workspace, | |
| 143 | verified: true, | |
| Workspace names and icons, and a component kit for every control | 144 | workspaces: vec![Membership::member(workspace.slug)], |
| 145 | ..User::default() | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 146 | })) |
| 147 | } | |
| 148 | ||
| 149 | async fn note_use(&self, presented: &Presented) -> Result<()> { | |
| 150 | let now = now_ms(); | |
| 151 | let stale = rfc3339(now.saturating_sub(LAST_USED_RESOLUTION_MS)); | |
| 152 | if presented | |
| 153 | .last_used_at | |
| 154 | .as_deref() | |
| 155 | .is_some_and(|at| at >= stale.as_str()) | |
| 156 | { | |
| 157 | return Ok(()); | |
| 158 | } | |
| 159 | self.db | |
| 160 | .prepare("UPDATE access_tokens SET last_used_at = ? WHERE id = ?") | |
| 161 | .bind(&[rfc3339(now).into(), presented.id.as_str().into()])? | |
| 162 | .run() | |
| 163 | .await?; | |
| 164 | Ok(()) | |
| 165 | } | |
| 166 | ||
| 167 | async fn mint( | |
| 168 | &self, | |
| 169 | owner: Owner<'_>, | |
| 170 | name: &str, | |
| 171 | ttl_seconds: Option<u64>, | |
| 172 | ) -> Result<CreatedAccessToken> { | |
| 173 | let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20)); | |
| 174 | let now = now_ms(); | |
| 175 | let name: String = match name.trim() { | |
| 176 | "" => "Access token".to_owned(), | |
| 177 | name => name.chars().take(100).collect(), | |
| 178 | }; | |
| 179 | let (user_id, workspace_id, created_by) = match owner { | |
| 180 | Owner::User(id) => (Some(id), None, Some(id)), | |
| 181 | Owner::Workspace { id, created_by } => (None, Some(id), created_by), | |
| 182 | }; | |
| 183 | let info = AccessToken { | |
| 184 | id: new_id("tok", now), | |
| 185 | name, | |
| 186 | created_at: rfc3339(now), | |
| 187 | last_used_at: None, | |
| 188 | created_by: None, | |
| 189 | }; | |
| 190 | self.db | |
| 191 | .prepare( | |
| 192 | "INSERT INTO access_tokens | |
| 193 | (id, user_id, workspace_id, created_by, name, token_hash, created_at, expires_at) | |
| 194 | VALUES (?, ?, ?, ?, ?, ?, ?, ?)", | |
| 195 | ) | |
| 196 | .bind(&[ | |
| 197 | info.id.as_str().into(), | |
| 198 | text(user_id), | |
| 199 | text(workspace_id), | |
| 200 | text(created_by), | |
| 201 | info.name.as_str().into(), | |
| 202 | crypto::sha256_hex(&token).into(), | |
| 203 | info.created_at.as_str().into(), | |
| 204 | ttl_seconds.map_or(JsValue::NULL, |ttl| rfc3339(now + ttl * 1000).into()), | |
| 205 | ])? | |
| 206 | .run() | |
| 207 | .await?; | |
| 208 | Ok(CreatedAccessToken { token, info }) | |
| 209 | } | |
| 210 | ||
| 211 | pub async fn create_access_token( | |
| 212 | &self, | |
| 213 | a: CreateAccessTokenArgs, | |
| 214 | ) -> Result<CreatedAccessToken> { | |
| 215 | // Told apart by the id, which says what it names, since callers pass | |
| 216 | // on actors that other services stored as an id and a name. | |
| 217 | let owner = if a.user.id.starts_with(WORKSPACE_ID_PREFIX) { | |
| 218 | Owner::Workspace { | |
| 219 | id: &a.user.id, | |
| 220 | created_by: None, | |
| 221 | } | |
| 222 | } else { | |
| 223 | Owner::User(&a.user.id) | |
| 224 | }; | |
| 225 | self.mint(owner, &a.name, a.ttl_seconds).await | |
| 226 | } | |
| 227 | ||
| 228 | /// A token for a g1t agent working for `on_behalf_of`, which can do | |
| 229 | /// only what `scope` lists. It is recorded as theirs, so it is listed and | |
| 230 | /// can be deleted with their other tokens. | |
| 231 | pub async fn create_agent_token(&self, a: CreateAgentTokenArgs) -> Result<CreatedAccessToken> { | |
| 232 | let created = self | |
| 233 | .mint( | |
| 234 | Owner::User(&a.on_behalf_of.id), | |
| 235 | &format!("g1t agent in {}/{}", a.scope.repo.namespace, a.scope.repo.name), | |
| 236 | Some(a.ttl_seconds), | |
| 237 | ) | |
| 238 | .await?; | |
| 239 | self.db | |
| 240 | .prepare("UPDATE access_tokens SET agent_scope = ? WHERE id = ?") | |
| 241 | .bind(&[ | |
| 242 | serde_json::to_string(&a.scope)?.into(), | |
| 243 | created.info.id.as_str().into(), | |
| 244 | ])? | |
| 245 | .run() | |
| 246 | .await?; | |
| 247 | Ok(created) | |
| 248 | } | |
| 249 | ||
| 250 | /// What an agent's token may do, or `None` for any other token. | |
| 251 | pub async fn agent_scope(&self, a: TokenArgs) -> Result<Option<AgentScope>> { | |
| 252 | let scope: Option<Option<String>> = self | |
| 253 | .db | |
| 254 | .prepare(format!( | |
| 255 | "SELECT agent_scope FROM access_tokens | |
| 256 | WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})" | |
| 257 | )) | |
| 258 | .bind(&[crypto::sha256_hex(&a.token).into()])? | |
| 259 | .first::<Option<String>>(Some("agent_scope")) | |
| 260 | .await?; | |
| 261 | Ok(scope | |
| 262 | .flatten() | |
| 263 | .and_then(|scope| serde_json::from_str(&scope).ok())) | |
| 264 | } | |
| 265 | ||
| 266 | pub async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> { | |
| 267 | self.tokens_where("access_tokens.user_id = ?", &a.user.id) | |
| 268 | .await | |
| 269 | } | |
| 270 | ||
| 271 | /// Tokens that do not expire: the ones a person made on purpose, rather | |
| 272 | /// than those issued to an application or a hosted agent. | |
| 273 | async fn tokens_where(&self, owner: &str, id: &str) -> Result<Vec<AccessToken>> { | |
| 274 | let rows = self | |
| 275 | .db | |
| 276 | .prepare(format!( | |
| 277 | "SELECT {TOKEN_COLUMNS} FROM access_tokens | |
| 278 | LEFT JOIN users ON users.id = access_tokens.created_by | |
| 279 | WHERE {owner} AND access_tokens.expires_at IS NULL | |
| 280 | ORDER BY access_tokens.id" | |
| 281 | )) | |
| 282 | .bind(&[id.into()])? | |
| 283 | .all() | |
| 284 | .await? | |
| 285 | .results::<TokenRow>()?; | |
| 286 | Ok(rows.into_iter().map(AccessToken::from).collect()) | |
| 287 | } | |
| 288 | ||
| 289 | pub async fn list_workspace_tokens( | |
| 290 | &self, | |
| 291 | a: WorkspaceTokensArgs, | |
| 292 | ) -> Result<Outcome<Vec<AccessToken>>> { | |
| 293 | let slug = a.slug.to_lowercase(); | |
| 294 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&slug)) { | |
| 295 | return Ok(Outcome::fail( | |
| 296 | FailureCode::Forbidden, | |
| 297 | "Only members can see a workspace's access tokens.", | |
| 298 | )); | |
| 299 | } | |
| 300 | let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else { | |
| 301 | return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found.")); | |
| 302 | }; | |
| 303 | Ok(Outcome::Ok( | |
| 304 | self.tokens_where("access_tokens.workspace_id = ?", &workspace.id) | |
| 305 | .await?, | |
| 306 | )) | |
| 307 | } | |
| 308 | ||
| 309 | /// The workspace's id, if `actor` is a person who owns it. | |
| 310 | async fn owned_workspace(&self, actor: &User, slug: &str) -> Result<Outcome<String>> { | |
| 311 | let slug = slug.to_lowercase(); | |
| 312 | if actor.kind != PrincipalKind::User || actor.role_in(&slug) != Some(Role::Owner) { | |
| 313 | return Ok(Outcome::fail( | |
| 314 | FailureCode::Forbidden, | |
| 315 | "Only an owner can manage a workspace's access tokens.", | |
| 316 | )); | |
| 317 | } | |
| 318 | Ok(match self.get_workspace(SlugArgs { slug }).await? { | |
| 319 | Some(workspace) => Outcome::Ok(workspace.id), | |
| 320 | None => Outcome::fail(FailureCode::NotFound, "Workspace not found."), | |
| 321 | }) | |
| 322 | } | |
| 323 | ||
| 324 | pub async fn create_workspace_token( | |
| 325 | &self, | |
| 326 | a: CreateWorkspaceTokenArgs, | |
| 327 | ) -> Result<Outcome<CreatedAccessToken>> { | |
| 328 | let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? { | |
| 329 | Outcome::Ok(id) => id, | |
| 330 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 331 | }; | |
| 332 | if a.name.trim().is_empty() { | |
| 333 | return Ok(Outcome::fail( | |
| 334 | FailureCode::Invalid, | |
| 335 | "Name the token after what will use it.", | |
| 336 | )); | |
| 337 | } | |
| 338 | let existing = self | |
| 339 | .tokens_where("access_tokens.workspace_id = ?", &workspace_id) | |
| 340 | .await?; | |
| 341 | if existing.len() >= MAX_TOKENS_PER_WORKSPACE { | |
| 342 | return Ok(Outcome::fail( | |
| 343 | FailureCode::Conflict, | |
| 344 | "This workspace has the maximum number of access tokens. Delete one first.", | |
| 345 | )); | |
| 346 | } | |
| 347 | let mut created = self | |
| 348 | .mint( | |
| 349 | Owner::Workspace { | |
| 350 | id: &workspace_id, | |
| 351 | created_by: Some(&a.actor.id), | |
| 352 | }, | |
| 353 | &a.name, | |
| 354 | None, | |
| 355 | ) | |
| 356 | .await?; | |
| 357 | created.info.created_by = Some(a.actor.username); | |
| 358 | Ok(Outcome::Ok(created)) | |
| 359 | } | |
| 360 | ||
| 361 | pub async fn remove_workspace_token( | |
| 362 | &self, | |
| 363 | a: RemoveWorkspaceTokenArgs, | |
| 364 | ) -> Result<Outcome<bool>> { | |
| 365 | let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? { | |
| 366 | Outcome::Ok(id) => id, | |
| 367 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 368 | }; | |
| 369 | self.db | |
| 370 | .prepare("DELETE FROM access_tokens WHERE id = ? AND workspace_id = ?") | |
| 371 | .bind(&[a.id.into(), workspace_id.into()])? | |
| 372 | .run() | |
| 373 | .await?; | |
| 374 | Ok(Outcome::Ok(true)) | |
| 375 | } | |
| 376 | } |