Skip to content

Commit

A person's access token can be let use the website as them: identity keeps the choice (migration 0043, off for every token until its owner turns it on), only on a person's own token, never a workspace's, a job's, an agent's or an application's, and says so on the token when it is used, while full access, presets and OAuth never include it; the person's name and avatar come with a token as with a session, and the audit log records which token a person used on any surface.

syntaqxcommitted Parent6c97c24Browse files
7 files+122−60/7 viewed
+25−1
122122 .and_then(|acting| acting.run())
123123 .map(|run| run.kind.as_str().to_owned())
124124 .or_else(|| job.map(|_| WORKFLOW_JOB.to_owned())),
125+ // The token used, whatever the surface: a person's or a
126+ // workspace's on the API, MCP or git, and a person's on the
127+ // website (apps/web, app/lib/website-token.ts).
125128 credential_id: acting
126129 .map(|acting| acting.credential_id.clone())
127− .or_else(|| job.map(|(token, _)| token.token_id.clone())),
130+ .or_else(|| job.map(|(token, _)| token.token_id.clone()))
131+ .or_else(|| user.token.as_deref().map(|token| token.token_id.clone()).filter(|id| !id.is_empty())),
128132 }
129133 }
130134
342346 });
343347 assert_eq!(person.actor_kind, Some(ActorKind::Person));
344348 assert!(!person.records_reads());
349+ assert_eq!(person.credential_id, None, "signed in: no token");
350+ }
351+
352+ #[test]
353+ fn a_person_using_a_token_is_recorded_with_it_on_any_surface() {
354+ let user = User {
355+ id: "usr_1".to_owned(),
356+ username: "syntaqx".to_owned(),
357+ token: Some(Box::new(crate::scopes::TokenAccess {
358+ token_id: "tok_web".to_owned(),
359+ website: true,
360+ ..crate::scopes::TokenAccess::default()
361+ })),
362+ ..User::default()
363+ };
364+ let actor = AuditActor::of(&user);
365+ assert_eq!(actor.actor_kind, Some(ActorKind::Person));
366+ assert_eq!(actor.actor, "syntaqx");
367+ assert_eq!(actor.credential_id.as_deref(), Some("tok_web"));
368+ assert!(!actor.records_reads());
345369 }
346370
347371 #[test]
+4−0
7878 /// admin of the workspace's repositories rather than with Write.
7979 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8080 pub admin: bool,
81+ /// A person's token its owner let use the website (g1t.sh) as them,
82+ /// with `Authorization: Bearer`. See [`crate::scopes::TokenAccess::website`].
83+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
84+ pub website: bool,
8185 }
8286
8387 /// `sign_in`: verifies a username, or any confirmed email address of the
+17−0
681681 /// `repo` is the one repository it reaches.
682682 #[serde(default, skip_serializing_if = "Option::is_none")]
683683 pub deploy_key: Option<String>,
684+ /// Set on a person's token whose owner let it use the website (g1t.sh)
685+ /// as them, sent as `Authorization: Bearer`. Not a scope: no preset,
686+ /// full access or OAuth grant includes it, and git, the API and MCP
687+ /// ignore it.
688+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
689+ pub website: bool,
684690 }
685691
686692 /// Which repositories a token reaches in the workspace it is made for.
17501756 }))
17511757 .unwrap();
17521758 assert_eq!(older, access);
1759+ // Using the website is off unless set, and said only when on.
1760+ assert!(!access.website);
1761+ assert!(wire_of(&access).get("website").is_none());
1762+ let website = TokenAccess { website: true, ..access };
1763+ assert_eq!(wire_of(&website)["website"], json!(true));
1764+ // Never part of full access.
1765+ assert!(!TokenAccess::full().website);
1766+ }
1767+
1768+ fn wire_of(access: &TokenAccess) -> serde_json::Value {
1769+ serde_json::to_value(access).unwrap()
17531770 }
17541771
17551772 /// The site's copy of the table, `packages/contracts/src/scopes.ts`,
+7−0
111111 /// out or `none` is no access. See [`crate::scopes::resolve_permissions`].
112112 #[serde(default)]
113113 pub permissions: BTreeMap<String, String>,
114+ /// Whether it may be used on the website as its owner: a person's token
115+ /// only. Never part of its permissions, so full access does not include it.
116+ #[serde(default)]
117+ pub website: bool,
114118 }
115119
116120 /// `update_token`: a person changes a token of theirs, or, as an owner,
137141 pub repositories: Option<Vec<String>>,
138142 #[serde(default)]
139143 pub permissions: Option<BTreeMap<String, String>>,
144+ /// Whether it may be used on the website; a person's token only.
145+ #[serde(default)]
146+ pub website: Option<bool>,
140147 }
141148
142149 /// A workspace's rules for personal access tokens.
+7−0
1+-- A person's access token may be let use the website (g1t.sh) as them,
2+-- sent as `Authorization: Bearer`, so automation driving a browser can
3+-- work there without signing in. Off unless its owner turns it on when
4+-- making or changing the token. It is not a scope: full access and every
5+-- existing token stay off. See src/tokens.rs and apps/web's
6+-- app/lib/website-token.ts.
7+ALTER TABLE access_tokens ADD COLUMN website INTEGER NOT NULL DEFAULT 0;
+26−2
5151
5252 const DAY_SECONDS: u64 = 86_400;
5353
54+/// Why a workspace's token cannot use the website: it acts as no person.
55+const WORKSPACE_TOKEN_NO_WEBSITE: &str = "Only a person's token can use the website: a workspace's token acts as no one who can sign in.";
56+
5457 /// What a token row says about its reach, read with it when it is used.
5558 /// Numbers arrive from D1 as floats.
5659 #[derive(Clone, Debug, Default, Deserialize)]
107110 review_reason: Option<String>,
108111 #[serde(default)]
109112 owner_workspace: Option<String>,
113+ /// 1 when its owner let it use the website (migration 0043).
114+ #[serde(default)]
115+ website: Option<f64>,
110116 }
111117
112118 impl TokenRowMore {
120126 info.repository_selection = self.repository_selection.as_deref().and_then(RepositorySelection::parse).unwrap_or_default();
121127 info.status = TokenStatus::parse(self.status.as_deref().unwrap_or("active"));
122128 info.review_reason = self.review_reason.clone();
129+ info.website = self.website.is_some_and(|on| on >= 1.0) && self.workspace_id.is_none();
123130 }
124131 }
125132
431438 Outcome::Ok(id) => id,
432439 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
433440 };
441+ if a.website {
442+ return Ok(Outcome::fail(FailureCode::Invalid, WORKSPACE_TOKEN_NO_WEBSITE));
443+ }
434444 let scopes = match resolve_permissions(&a.permissions, false) {
435445 Ok(scopes) => scopes,
436446 Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)),
532542 let description = tidy(a.description.as_deref());
533543 let mut statements = vec![self
534544 .db
535− .prepare("UPDATE access_tokens SET owner_workspace_id = ?, repository_selection = ?, description = ?, status = ? WHERE id = ?")
545+ .prepare("UPDATE access_tokens SET owner_workspace_id = ?, repository_selection = ?, description = ?, status = ?, website = ? WHERE id = ?")
536546 .bind(&[
537547 text(workspace_id.as_deref()),
538548 selection.as_str().into(),
539549 text(description.as_deref()),
540550 status.as_str().into(),
551+ JsValue::from(u8::from(a.website)),
541552 created.info.id.as_str().into(),
542553 ])?];
543554 statements.extend(self.repository_rows(&created.info.id, &repo_ids)?);
547558 created.info.repository_selection = selection;
548559 created.info.repositories = qualified_all(slug.as_deref(), &repo_ids, &a.repositories);
549560 created.info.status = status;
561+ created.info.website = a.website;
550562 // In the person's security log and their workspaces' audit logs.
551563 self.log_security(&a.actor.id, "token_created", Some(&created.info.name), None).await;
552− self.audit_account(&a.actor, "token.created", &format!("Created access token {}", created.info.name)).await;
564+ let website = if a.website { " that can use the website" } else { "" };
565+ self.audit_account(&a.actor, "token.created", &format!("Created access token {}{website}", created.info.name)).await;
553566 if let (Some(slug), TokenStatus::Pending) = (&slug, status) {
554567 self.ask_owners(&a.actor, slug, &created.info).await?;
555568 }
618631 sets.push(("scopes", scopes_text(&scopes).into()));
619632 widened = true;
620633 }
634+ // Using the website: a person's token only. Turning it on is
635+ // asking for more; turning it off is not.
636+ if let Some(website) = a.website {
637+ if website && !personal {
638+ return Ok(Outcome::fail(FailureCode::Invalid, WORKSPACE_TOKEN_NO_WEBSITE));
639+ }
640+ if personal {
641+ sets.push(("website", JsValue::from(u8::from(website))));
642+ widened |= website;
643+ }
644+ }
621645 if let Some(selection) = a.repository_selection {
622646 if selection == RepositorySelection::Selected && repo_workspace.is_none() {
623647 return Ok(Outcome::fail(FailureCode::Invalid, "This token is not made for one workspace, so it cannot select repositories."));
+36−3
2929 access_tokens.last_used_at, users.username AS created_by, access_tokens.scopes,
3030 access_tokens.expires_at, access_tokens.description, access_tokens.admin,
3131 access_tokens.workspace_id, access_tokens.repository_selection,
32− access_tokens.status, access_tokens.review_reason,
32+ access_tokens.status, access_tokens.review_reason, access_tokens.website,
3333 (SELECT slug FROM workspaces WHERE workspaces.id = access_tokens.owner_workspace_id) AS owner_workspace";
3434
3535 /// Who a new token belongs to.
121121 job_run_id: Option<String>,
122122 #[serde(default)]
123123 job_pulls: Option<u32>,
124+ /// 1 when its owner let it use the website (migration 0043).
125+ #[serde(default)]
126+ website: Option<f64>,
124127 /// The workspace it is made for, its repositories and status, a
125128 /// workspace token's Admin, and when it was made and expires, for the
126129 /// rules of the workspaces it reaches (token_reach.rs).
138141 value.map_or(JsValue::NULL, JsValue::from)
139142 }
140143
144+/// Whether a token being used may be used on the website as its owner: one
145+/// a person made and turned that on for, never a workspace's, a job's or an
146+/// agent's (apps/web, app/lib/website-token.ts).
147+fn website_allowed(presented: &Presented) -> bool {
148+ presented.website.is_some_and(|on| on >= 1.0)
149+ && presented.user_id.is_some()
150+ && presented.workspace_id.is_none()
151+ && presented.job_id.is_none()
152+ && presented.agent_scope.is_none()
153+}
154+
141155 impl Identity {
142156 pub async fn user_for_access_token(&self, token: &str) -> Result<Viewer> {
143157 if !token.starts_with(TOKEN_PREFIX) {
148162 .prepare(format!(
149163 "SELECT id, user_id, workspace_id, last_used_at, agent_scope, scopes, name,
150164 repo, job_id, job_run_id, job_pulls, created_at, expires_at,
151− owner_workspace_id, repository_selection, status, admin
165+ owner_workspace_id, repository_selection, status, admin, website
152166 FROM access_tokens
153167 WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > {SQL_NOW})"
154168 ))
178192 let mut viewer = match (&presented.user_id, &presented.workspace_id) {
179193 (Some(user_id), _) => {
180194 self.find_user(
181− "SELECT id, username, email_verified_at IS NOT NULL AS verified
195+ "SELECT id, username, display_username, email_verified_at IS NOT NULL AS verified, avatar
182196 FROM users WHERE id = ? AND deleted_at IS NULL",
183197 user_id,
184198 )
204218 }),
205219 _ => None,
206220 },
221+ website: website_allowed(&presented),
207222 ..TokenAccess::default()
208223 }));
209224 // What it reaches: the workspace it is made for and its
542557 assert_eq!(Grant::asked(&None).scopes_column(), "*");
543558 assert_eq!(Grant::asked(&Some(vec![])).scopes_column(), "");
544559 }
560+
561+ #[test]
562+ fn only_a_persons_own_token_with_it_turned_on_uses_the_website() {
563+ let row = |extra: serde_json::Value| {
564+ let mut value = serde_json::json!({ "id": "tok_1", "user_id": "usr_1", "workspace_id": null, "last_used_at": null, "agent_scope": null, "scopes": "*", "website": 1.0 });
565+ for (key, field) in extra.as_object().unwrap() {
566+ value[key] = field.clone();
567+ }
568+ serde_json::from_value::<Presented>(value).unwrap()
569+ };
570+ assert!(website_allowed(&row(serde_json::json!({}))));
571+ assert!(!website_allowed(&row(serde_json::json!({ "website": 0.0 }))));
572+ assert!(!website_allowed(&row(serde_json::json!({ "website": null }))));
573+ // A workspace's token, a job's token and an agent's never do.
574+ assert!(!website_allowed(&row(serde_json::json!({ "user_id": null, "workspace_id": "wsp_1" }))));
575+ assert!(!website_allowed(&row(serde_json::json!({ "job_id": "job_1" }))));
576+ assert!(!website_allowed(&row(serde_json::json!({ "agent_scope": "{}" }))));
577+ }
545578 }