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

377 lines13,240 bytesCodeBlame

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