pr_01m47d15m3e54sn21z27rpy5n9/services/identity/src/tokens.rs
| 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, |
| 108 | workspaces: vec![Membership { |
| 109 | slug: scope.repo.namespace, |
| 110 | role: Role::Member, |
| 111 | }], |
| 112 | })); |
| 113 | } |
| 114 | let viewer = match (&presented.user_id, &presented.workspace_id) { |
| 115 | (Some(user_id), _) => { |
| 116 | self.find_user( |
| 117 | "SELECT id, username, email_verified_at IS NOT NULL AS verified |
| 118 | FROM users WHERE id = ?", |
| 119 | user_id, |
| 120 | ) |
| 121 | .await? |
| 122 | } |
| 123 | (None, Some(workspace_id)) => self.workspace_principal(workspace_id).await?, |
| 124 | (None, None) => None, |
| 125 | }; |
| 126 | if viewer.is_some() { |
| 127 | self.note_use(&presented).await?; |
| 128 | } |
| 129 | Ok(viewer) |
| 130 | } |
| 131 | |
| 132 | /// A workspace as the actor behind one of its own tokens. It can do |
| 133 | /// what a member can, in that workspace only. |
| 134 | async fn workspace_principal(&self, workspace_id: &str) -> Result<Viewer> { |
| 135 | let workspace = self |
| 136 | .db |
| 137 | .prepare("SELECT id, slug FROM workspaces WHERE id = ?") |
| 138 | .bind(&[workspace_id.into()])? |
| 139 | .first::<WorkspaceRef>(None) |
| 140 | .await?; |
| 141 | Ok(workspace.map(|workspace| User { |
| 142 | id: workspace.id, |
| 143 | username: workspace.slug.clone(), |
| 144 | kind: PrincipalKind::Workspace, |
| 145 | verified: true, |
| 146 | workspaces: vec![Membership { |
| 147 | slug: workspace.slug, |
| 148 | role: Role::Member, |
| 149 | }], |
| 150 | })) |
| 151 | } |
| 152 | |
| 153 | async fn note_use(&self, presented: &Presented) -> Result<()> { |
| 154 | let now = now_ms(); |
| 155 | let stale = rfc3339(now.saturating_sub(LAST_USED_RESOLUTION_MS)); |
| 156 | if presented |
| 157 | .last_used_at |
| 158 | .as_deref() |
| 159 | .is_some_and(|at| at >= stale.as_str()) |
| 160 | { |
| 161 | return Ok(()); |
| 162 | } |
| 163 | self.db |
| 164 | .prepare("UPDATE access_tokens SET last_used_at = ? WHERE id = ?") |
| 165 | .bind(&[rfc3339(now).into(), presented.id.as_str().into()])? |
| 166 | .run() |
| 167 | .await?; |
| 168 | Ok(()) |
| 169 | } |
| 170 | |
| 171 | async fn mint( |
| 172 | &self, |
| 173 | owner: Owner<'_>, |
| 174 | name: &str, |
| 175 | ttl_seconds: Option<u64>, |
| 176 | ) -> Result<CreatedAccessToken> { |
| 177 | let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20)); |
| 178 | let now = now_ms(); |
| 179 | let name: String = match name.trim() { |
| 180 | "" => "Access token".to_owned(), |
| 181 | name => name.chars().take(100).collect(), |
| 182 | }; |
| 183 | let (user_id, workspace_id, created_by) = match owner { |
| 184 | Owner::User(id) => (Some(id), None, Some(id)), |
| 185 | Owner::Workspace { id, created_by } => (None, Some(id), created_by), |
| 186 | }; |
| 187 | let info = AccessToken { |
| 188 | id: new_id("tok", now), |
| 189 | name, |
| 190 | created_at: rfc3339(now), |
| 191 | last_used_at: None, |
| 192 | created_by: None, |
| 193 | }; |
| 194 | self.db |
| 195 | .prepare( |
| 196 | "INSERT INTO access_tokens |
| 197 | (id, user_id, workspace_id, created_by, name, token_hash, created_at, expires_at) |
| 198 | VALUES (?, ?, ?, ?, ?, ?, ?, ?)", |
| 199 | ) |
| 200 | .bind(&[ |
| 201 | info.id.as_str().into(), |
| 202 | text(user_id), |
| 203 | text(workspace_id), |
| 204 | text(created_by), |
| 205 | info.name.as_str().into(), |
| 206 | crypto::sha256_hex(&token).into(), |
| 207 | info.created_at.as_str().into(), |
| 208 | ttl_seconds.map_or(JsValue::NULL, |ttl| rfc3339(now + ttl * 1000).into()), |
| 209 | ])? |
| 210 | .run() |
| 211 | .await?; |
| 212 | Ok(CreatedAccessToken { token, info }) |
| 213 | } |
| 214 | |
| 215 | pub async fn create_access_token( |
| 216 | &self, |
| 217 | a: CreateAccessTokenArgs, |
| 218 | ) -> Result<CreatedAccessToken> { |
| 219 | // Told apart by the id, which says what it names, since callers pass |
| 220 | // on actors that other services stored as an id and a name. |
| 221 | let owner = if a.user.id.starts_with(WORKSPACE_ID_PREFIX) { |
| 222 | Owner::Workspace { |
| 223 | id: &a.user.id, |
| 224 | created_by: None, |
| 225 | } |
| 226 | } else { |
| 227 | Owner::User(&a.user.id) |
| 228 | }; |
| 229 | self.mint(owner, &a.name, a.ttl_seconds).await |
| 230 | } |
| 231 | |
| 232 | /// A token for a g1t agent working for `on_behalf_of`, which can do |
| 233 | /// only what `scope` lists. It is recorded as theirs, so it is listed and |
| 234 | /// can be deleted with their other tokens. |
| 235 | pub async fn create_agent_token(&self, a: CreateAgentTokenArgs) -> Result<CreatedAccessToken> { |
| 236 | let created = self |
| 237 | .mint( |
| 238 | Owner::User(&a.on_behalf_of.id), |
| 239 | &format!("g1t agent in {}/{}", a.scope.repo.namespace, a.scope.repo.name), |
| 240 | Some(a.ttl_seconds), |
| 241 | ) |
| 242 | .await?; |
| 243 | self.db |
| 244 | .prepare("UPDATE access_tokens SET agent_scope = ? WHERE id = ?") |
| 245 | .bind(&[ |
| 246 | serde_json::to_string(&a.scope)?.into(), |
| 247 | created.info.id.as_str().into(), |
| 248 | ])? |
| 249 | .run() |
| 250 | .await?; |
| 251 | Ok(created) |
| 252 | } |
| 253 | |
| 254 | /// What an agent's token may do, or `None` for any other token. |
| 255 | pub async fn agent_scope(&self, a: TokenArgs) -> Result<Option<AgentScope>> { |
| 256 | let scope: Option<Option<String>> = self |
| 257 | .db |
| 258 | .prepare(format!( |
| 259 | "SELECT agent_scope FROM access_tokens |
| 260 | WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})" |
| 261 | )) |
| 262 | .bind(&[crypto::sha256_hex(&a.token).into()])? |
| 263 | .first::<Option<String>>(Some("agent_scope")) |
| 264 | .await?; |
| 265 | Ok(scope |
| 266 | .flatten() |
| 267 | .and_then(|scope| serde_json::from_str(&scope).ok())) |
| 268 | } |
| 269 | |
| 270 | pub async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> { |
| 271 | self.tokens_where("access_tokens.user_id = ?", &a.user.id) |
| 272 | .await |
| 273 | } |
| 274 | |
| 275 | /// Tokens that do not expire: the ones a person made on purpose, rather |
| 276 | /// than those issued to an application or a hosted agent. |
| 277 | async fn tokens_where(&self, owner: &str, id: &str) -> Result<Vec<AccessToken>> { |
| 278 | let rows = self |
| 279 | .db |
| 280 | .prepare(format!( |
| 281 | "SELECT {TOKEN_COLUMNS} FROM access_tokens |
| 282 | LEFT JOIN users ON users.id = access_tokens.created_by |
| 283 | WHERE {owner} AND access_tokens.expires_at IS NULL |
| 284 | ORDER BY access_tokens.id" |
| 285 | )) |
| 286 | .bind(&[id.into()])? |
| 287 | .all() |
| 288 | .await? |
| 289 | .results::<TokenRow>()?; |
| 290 | Ok(rows.into_iter().map(AccessToken::from).collect()) |
| 291 | } |
| 292 | |
| 293 | pub async fn list_workspace_tokens( |
| 294 | &self, |
| 295 | a: WorkspaceTokensArgs, |
| 296 | ) -> Result<Outcome<Vec<AccessToken>>> { |
| 297 | let slug = a.slug.to_lowercase(); |
| 298 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&slug)) { |
| 299 | return Ok(Outcome::fail( |
| 300 | FailureCode::Forbidden, |
| 301 | "Only members can see a workspace's access tokens.", |
| 302 | )); |
| 303 | } |
| 304 | let Some(workspace) = self.get_workspace(SlugArgs { slug }).await? else { |
| 305 | return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found.")); |
| 306 | }; |
| 307 | Ok(Outcome::Ok( |
| 308 | self.tokens_where("access_tokens.workspace_id = ?", &workspace.id) |
| 309 | .await?, |
| 310 | )) |
| 311 | } |
| 312 | |
| 313 | /// The workspace's id, if `actor` is a person who owns it. |
| 314 | async fn owned_workspace(&self, actor: &User, slug: &str) -> Result<Outcome<String>> { |
| 315 | let slug = slug.to_lowercase(); |
| 316 | if actor.kind != PrincipalKind::User || actor.role_in(&slug) != Some(Role::Owner) { |
| 317 | return Ok(Outcome::fail( |
| 318 | FailureCode::Forbidden, |
| 319 | "Only an owner can manage a workspace's access tokens.", |
| 320 | )); |
| 321 | } |
| 322 | Ok(match self.get_workspace(SlugArgs { slug }).await? { |
| 323 | Some(workspace) => Outcome::Ok(workspace.id), |
| 324 | None => Outcome::fail(FailureCode::NotFound, "Workspace not found."), |
| 325 | }) |
| 326 | } |
| 327 | |
| 328 | pub async fn create_workspace_token( |
| 329 | &self, |
| 330 | a: CreateWorkspaceTokenArgs, |
| 331 | ) -> Result<Outcome<CreatedAccessToken>> { |
| 332 | let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? { |
| 333 | Outcome::Ok(id) => id, |
| 334 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 335 | }; |
| 336 | if a.name.trim().is_empty() { |
| 337 | return Ok(Outcome::fail( |
| 338 | FailureCode::Invalid, |
| 339 | "Name the token after what will use it.", |
| 340 | )); |
| 341 | } |
| 342 | let existing = self |
| 343 | .tokens_where("access_tokens.workspace_id = ?", &workspace_id) |
| 344 | .await?; |
| 345 | if existing.len() >= MAX_TOKENS_PER_WORKSPACE { |
| 346 | return Ok(Outcome::fail( |
| 347 | FailureCode::Conflict, |
| 348 | "This workspace has the maximum number of access tokens. Delete one first.", |
| 349 | )); |
| 350 | } |
| 351 | let mut created = self |
| 352 | .mint( |
| 353 | Owner::Workspace { |
| 354 | id: &workspace_id, |
| 355 | created_by: Some(&a.actor.id), |
| 356 | }, |
| 357 | &a.name, |
| 358 | None, |
| 359 | ) |
| 360 | .await?; |
| 361 | created.info.created_by = Some(a.actor.username); |
| 362 | Ok(Outcome::Ok(created)) |
| 363 | } |
| 364 | |
| 365 | pub async fn remove_workspace_token( |
| 366 | &self, |
| 367 | a: RemoveWorkspaceTokenArgs, |
| 368 | ) -> Result<Outcome<bool>> { |
| 369 | let workspace_id = match self.owned_workspace(&a.actor, &a.slug).await? { |
| 370 | Outcome::Ok(id) => id, |
| 371 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 372 | }; |
| 373 | self.db |
| 374 | .prepare("DELETE FROM access_tokens WHERE id = ? AND workspace_id = ?") |
| 375 | .bind(&[a.id.into(), workspace_id.into()])? |
| 376 | .run() |
| 377 | .await?; |
| 378 | Ok(Outcome::Ok(true)) |
| 379 | } |
| 380 | } |