Skip to content
1,840 linesCodeBlameRaw
1//! The identity service: accounts, credentials and sessions.
2//!
3//! Each `*Args` struct is the argument of the method of the same name,
4//! served at `POST /rpc/<method>`.
5
6use serde::{Deserialize, Serialize};
7
8use crate::User;
9
10#[derive(Clone, Debug, Serialize, Deserialize)]
11#[serde(rename_all = "camelCase")]
12pub struct SshKey {
13 pub id: String,
14 pub title: String,
15 pub fingerprint: String,
16 /// RFC 3339.
17 pub created_at: String,
18 /// When it was last used to sign in over SSH, RFC 3339, to within 5
19 /// minutes; null when it never was.
20 #[serde(default)]
21 pub last_used_at: Option<String>,
22}
23
24#[derive(Clone, Debug, Default, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct AccessToken {
27 pub id: String,
28 pub name: String,
29 /// RFC 3339.
30 pub created_at: String,
31 /// RFC 3339, to within a few minutes. Null until it is first used.
32 pub last_used_at: Option<String>,
33 /// For a workspace's token, the username of the member who made it.
34 /// Null once that account is gone, and on personal tokens.
35 pub created_by: Option<String>,
36 /// Its scopes, as `resource:level`, the highest of each resource.
37 /// Null: full access (an application's or an agent's credential).
38 #[serde(default)]
39 pub scopes: Option<Vec<String>>,
40 /// Made before tokens had scopes: full access until someone narrows it.
41 #[serde(default)]
42 pub legacy: bool,
43 /// RFC 3339. Null: it does not expire.
44 #[serde(default)]
45 pub expires_at: Option<String>,
46 /// Its scopes as permissions: each resource it may use, by name, at
47 /// the highest level, such as `{"issues": "write"}`. Every resource at
48 /// its highest when `scopes` is null.
49 #[serde(default)]
50 pub permissions: std::collections::BTreeMap<String, String>,
51 /// What it is for, as its owner wrote it.
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub description: Option<String>,
54 /// A personal token's reach: the workspace it is made for, by slug;
55 /// null for every workspace its owner belongs to (or, with
56 /// `repository_selection` public, none). Null on a workspace's own
57 /// token, which reaches its workspace.
58 #[serde(default)]
59 pub workspace: Option<String>,
60 /// Which repositories of that workspace it reaches.
61 #[serde(default)]
62 pub repository_selection: crate::scopes::RepositorySelection,
63 /// With `selected`: the repositories, as `owner/name`, that the viewer
64 /// can see.
65 #[serde(default)]
66 pub repositories: Vec<String>,
67 /// Whether a token made for a workspace that approves tokens may be
68 /// used there yet.
69 #[serde(default)]
70 pub status: crate::tokens::TokenStatus,
71 /// Why an owner denied or revoked it.
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub review_reason: Option<String>,
74 /// Whether it is a workspace's own token, acting as the workspace.
75 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
76 pub workspace_owned: bool,
77 /// A workspace's own token with Repositories: admin, which acts as an
78 /// admin of the workspace's repositories rather than with Write.
79 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
80 pub admin: bool,
81}
82
83/// `sign_in`: verifies a username, or any confirmed email address of the
84/// account, and its password, for website sign-in. Wrong passwords are
85/// counted against the account and `client`, and past a limit nothing is
86/// checked for a while (see identity's `throttle.rs`).
87/// Returns `Outcome<SignedIn>`.
88#[derive(Debug, Serialize, Deserialize)]
89pub struct SignInArgs {
90 pub username: String,
91 pub password: String,
92 /// Who is asking, such as the visitor's IP address, for rate limits.
93 #[serde(default)]
94 pub client: Option<String>,
95}
96
97#[derive(Debug, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub struct SignedIn {
100 pub user: User,
101 /// Empty while `two_factor_challenge` is set: no session is made until
102 /// the code is given.
103 pub session_token: String,
104 /// Set when the account has two-factor authentication on: the token to
105 /// pass to `two_factor_sign_in` with a code. Valid for
106 /// `accounts::TWO_FACTOR_CHALLENGE_SECONDS`.
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub two_factor_challenge: Option<String>,
109}
110
111/// `sign_out` and `user_for_session`.
112#[derive(Debug, Serialize, Deserialize)]
113#[serde(rename_all = "camelCase")]
114pub struct SessionArgs {
115 pub session_token: String,
116}
117
118/// `user_for_git_credentials`: the account password or an access token.
119#[derive(Debug, Serialize, Deserialize)]
120pub struct GitCredentialsArgs {
121 pub username: String,
122 pub secret: String,
123}
124
125/// `user_for_access_token`.
126#[derive(Debug, Serialize, Deserialize)]
127pub struct TokenArgs {
128 pub token: String,
129}
130
131/// `user_for_ssh_key`, and `principal_for_ssh_key` (see [`crate::deploy_keys`]).
132#[derive(Debug, Serialize, Deserialize)]
133pub struct FingerprintArgs {
134 pub fingerprint: String,
135}
136
137/// `user_by_username`.
138#[derive(Debug, Serialize, Deserialize)]
139pub struct UsernameArgs {
140 pub username: String,
141}
142
143/// `usernames`: the names behind account and workspace ids, as events and
144/// other records store them. Returns a map from id to name; ids it does
145/// not know are left out. Also `accounts`: the accounts behind user ids,
146/// each with its username and avatar (`HashMap<String, accounts::EmailOwner>`).
147#[derive(Debug, Serialize, Deserialize)]
148pub struct UsernamesArgs {
149 pub ids: Vec<String>,
150}
151
152/// `display_usernames`: how each of these people (by lowercased username,
153/// at most 200) wrote their username, for showing it beside the key.
154/// Returns a map from the lowercased username to its chosen case; people
155/// who chose none, and names nobody has, are left out.
156#[derive(Debug, Default, Serialize, Deserialize)]
157pub struct DisplayUsernamesArgs {
158 pub usernames: Vec<String>,
159}
160
161/// `list_ssh_keys` and `list_access_tokens`.
162#[derive(Debug, Serialize, Deserialize)]
163pub struct UserArgs {
164 pub user: User,
165}
166
167/// `ssh_key_owners`: services only. The account (user id) that registered
168/// each key, by fingerprint (`SHA256:…`, as `ssh-keygen -lf` prints it),
169/// for verifying commits signed with SSH keys. Returns a map of the
170/// fingerprints found to user ids.
171#[derive(Debug, Serialize, Deserialize)]
172pub struct SshKeyOwnersArgs {
173 pub fingerprints: Vec<String>,
174}
175
176/// `add_ssh_key`: `public_key` is one line in OpenSSH format.
177/// Returns `Outcome<SshKey>`.
178#[derive(Debug, Serialize, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub struct AddSshKeyArgs {
181 pub user: User,
182 pub title: String,
183 pub public_key: String,
184}
185
186/// `remove_ssh_key` and `remove_access_token`.
187#[derive(Debug, Serialize, Deserialize)]
188pub struct RemoveArgs {
189 pub user: User,
190 pub id: String,
191}
192
193/// `create_access_token`: a token that acts as `user`. For a workspace
194/// acting through a token of its own, the new token belongs to that
195/// workspace too.
196#[derive(Debug, Serialize, Deserialize)]
197#[serde(rename_all = "camelCase")]
198pub struct CreateAccessTokenArgs {
199 pub user: User,
200 pub name: String,
201 /// When set, the token stops working after this many seconds and is
202 /// left out of the user's token list, unless `listed`. Used for hosted
203 /// attempts.
204 #[serde(default)]
205 pub ttl_seconds: Option<u64>,
206 /// Its scopes, as `resource:level`; unknown names are left out. Null:
207 /// full access.
208 #[serde(default)]
209 pub scopes: Option<Vec<String>>,
210 /// Listed with the person's tokens although it expires: one they made
211 /// themselves, with an expiry.
212 #[serde(default)]
213 pub listed: bool,
214}
215
216/// `create_job_token`: a workflow job's `G1T_TOKEN`. It acts as the
217/// repository's workspace, reaches that repository only, holds `scopes`
218/// (from the job's `permissions`), and is never listed. The actions service
219/// revokes it when the job ends (`revoke_job_tokens`); `ttl_seconds` is a
220/// backstop. Returns `CreatedAccessToken`.
221#[derive(Debug, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct CreateJobTokenArgs {
224 /// The workspace the repository belongs to, as its own principal.
225 pub workspace: User,
226 pub repo: crate::repos::RepoPath,
227 pub run_id: String,
228 pub job_id: String,
229 /// What the token is listed as in logs: `G1T_TOKEN for acme/web run 4`.
230 pub name: String,
231 pub ttl_seconds: u64,
232 /// As `resource:level`; unknown names are left out.
233 pub scopes: Vec<String>,
234 /// Whether it may open and approve pull requests (`JobToken::pull_requests`).
235 #[serde(default)]
236 pub pull_requests: bool,
237}
238
239/// `revoke_job_tokens`: ends a workflow job's tokens at once, when the job
240/// finishes or is cancelled. Only job tokens are touched. Returns `bool`.
241#[derive(Debug, Default, Serialize, Deserialize)]
242#[serde(rename_all = "camelCase")]
243pub struct RevokeJobTokensArgs {
244 pub job_id: String,
245}
246
247/// The plaintext token is returned once and never stored.
248#[derive(Debug, Serialize, Deserialize)]
249pub struct CreatedAccessToken {
250 pub token: String,
251 pub info: AccessToken,
252}
253
254/// `register`: creates an account and signs it in.
255/// Returns `Outcome<SignedIn>`.
256///
257/// While registration is invite-only (`REGISTRATION_MODE=invite`), every
258/// new account needs `invite_code`: an unused, unexpired invite, and, when
259/// the invite names an email, that address. See [`CreateInviteArgs`].
260#[derive(Debug, Serialize, Deserialize)]
261pub struct RegisterArgs {
262 pub username: String,
263 pub email: String,
264 pub password: String,
265 /// An invite code such as `g1t-k7m2-q9xd-4hpw-…`. Ignored while
266 /// registration is open.
267 #[serde(default)]
268 pub invite_code: Option<String>,
269 /// The `proof` from the invite email's link. When it is the invite's
270 /// own and `email` is the address the invite was sent to, the account
271 /// starts with that address confirmed; otherwise it is ignored.
272 #[serde(default)]
273 pub email_proof: Option<String>,
274 /// Who is asking, such as the visitor's IP address, for rate limits.
275 #[serde(default)]
276 pub client: Option<String>,
277}
278
279/// `verify_email`: the token from the emailed link. Returns `Outcome<User>`.
280#[derive(Debug, Serialize, Deserialize)]
281pub struct EmailTokenArgs {
282 pub token: String,
283}
284
285/// `request_password_reset`. Always succeeds, so it cannot be used to find
286/// out which addresses have accounts. Any confirmed address of an account
287/// works: the link goes to the address given, and the primary (and the
288/// backup) are told a reset was asked for. A few requests an hour per
289/// address and per `client`; past that, nothing is sent.
290#[derive(Debug, Serialize, Deserialize)]
291pub struct EmailArgs {
292 pub email: String,
293 /// Who is asking, such as the visitor's IP address, for rate limits.
294 #[serde(default)]
295 pub client: Option<String>,
296}
297
298/// `reset_password`: sets a new password and ends every session.
299/// Returns `Outcome<User>`.
300#[derive(Debug, Serialize, Deserialize)]
301pub struct ResetPasswordArgs {
302 pub token: String,
303 pub password: String,
304}
305
306/// `device_start`: begins a device sign-in. Returns `DeviceStart`.
307#[derive(Debug, Serialize, Deserialize)]
308#[serde(rename_all = "camelCase")]
309pub struct DeviceStartArgs {
310 /// What is asking, shown to the person approving, e.g. "Claude Code".
311 pub client_name: String,
312}
313
314#[derive(Debug, Serialize, Deserialize)]
315#[serde(rename_all = "camelCase")]
316pub struct DeviceStart {
317 /// Secret held by the tool and exchanged for a token once approved.
318 pub device_code: String,
319 /// Short code shown to the person, e.g. `WDJB-MJHT`.
320 pub user_code: String,
321 /// Seconds until both codes stop working.
322 pub expires_in: u32,
323 /// Seconds the tool should wait between polls.
324 pub interval: u32,
325}
326
327/// `device_lookup`: what a user code is asking for, or null if it is not
328/// valid. Returns `Option<DeviceRequest>`.
329#[derive(Debug, Serialize, Deserialize)]
330#[serde(rename_all = "camelCase")]
331pub struct DeviceLookupArgs {
332 pub user_code: String,
333}
334
335#[derive(Debug, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct DeviceRequest {
338 pub user_code: String,
339 pub client_name: String,
340}
341
342/// `device_resolve`: the signed-in person approves or denies a request.
343/// Returns `Outcome<bool>`.
344#[derive(Debug, Serialize, Deserialize)]
345#[serde(rename_all = "camelCase")]
346pub struct DeviceResolveArgs {
347 pub user_code: String,
348 pub user: User,
349 pub approve: bool,
350}
351
352/// `device_claim`: the tool asks whether its request was approved.
353#[derive(Debug, Serialize, Deserialize)]
354#[serde(rename_all = "camelCase")]
355pub struct DeviceClaimArgs {
356 pub device_code: String,
357}
358
359/// The answer to a `device_claim`.
360#[derive(Debug, Serialize, Deserialize)]
361#[serde(tag = "status", rename_all = "snake_case")]
362pub enum DeviceClaim {
363 /// Nobody has approved or denied it yet; ask again after the interval.
364 Pending,
365 Denied,
366 /// The code was never issued, has expired, or was already used.
367 Expired,
368 /// The access token, returned once.
369 Approved {
370 token: String,
371 user: User,
372 },
373}
374
375/// A workspace: the owner of repositories, and the first segment of their
376/// URLs. A person's own space and a team's are the same thing.
377#[derive(Clone, Debug, Serialize, Deserialize)]
378#[serde(rename_all = "camelCase")]
379pub struct Workspace {
380 pub id: String,
381 pub slug: String,
382 pub name: String,
383 /// One line saying what the workspace is for.
384 pub description: Option<String>,
385 /// RFC 3339.
386 pub created_at: String,
387 pub member_count: u32,
388 /// The workspace's uploaded icon: the SHA-256 of its bytes, served at
389 /// `/avatars/<avatar>`. Null means the generated letter avatar.
390 #[serde(default)]
391 pub avatar: Option<String>,
392 /// What every member gets on each of its repositories; owners have
393 /// Admin. See [`crate::access`].
394 #[serde(default)]
395 pub base_permission: crate::access::BasePermission,
396 /// Who may create its teams. See [`crate::teams::TeamCreation`].
397 #[serde(default)]
398 pub team_creation: crate::teams::TeamCreation,
399 /// What members may do, by GitHub's names for each
400 /// (`members_can_create_public_repositories`...), at the top level as
401 /// GitHub's organization has them. See [`crate::MemberPrivileges`].
402 #[serde(flatten)]
403 pub privileges: crate::MemberPrivileges,
404 /// Whether members and outside collaborators need two-factor
405 /// authentication to use it.
406 #[serde(default)]
407 pub two_factor_requirement_enabled: bool,
408}
409
410#[derive(Clone, Debug, Serialize, Deserialize)]
411pub struct Member {
412 pub username: String,
413 /// The username as its owner wrote it (`Ana`), when that differs from
414 /// `username`: what pages show.
415 #[serde(default, skip_serializing_if = "Option::is_none")]
416 pub display_username: Option<String>,
417 pub role: crate::Role,
418 /// The roles they hold besides `role`.
419 #[serde(default)]
420 pub org_roles: Vec<crate::OrgRole>,
421 /// Whether they have two-factor authentication on. Shown to owners
422 /// only; null for anyone else.
423 #[serde(default)]
424 pub two_factor: Option<bool>,
425 /// Their display name, when they set one.
426 #[serde(default)]
427 pub name: Option<String>,
428 /// Their uploaded avatar: the SHA-256 of its bytes, served at
429 /// `/avatars/<avatar>`. None means the generated letter avatar.
430 #[serde(default)]
431 pub avatar: Option<String>,
432}
433
434/// Where a workspace keeps its repositories' git data: anywhere g1t
435/// stores it (the default), or in the EU only. It applies to repositories
436/// made after it is set; the repos service reads it when it places a new
437/// one (`storage_options` says whether the EU can be chosen).
438#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(rename_all = "lowercase")]
440pub enum DataResidency {
441 #[default]
442 Anywhere,
443 Eu,
444}
445
446impl DataResidency {
447 pub fn as_str(self) -> &'static str {
448 match self {
449 DataResidency::Anywhere => "anywhere",
450 DataResidency::Eu => "eu",
451 }
452 }
453
454 pub fn parse(text: &str) -> Option<Self> {
455 match text.trim().to_ascii_lowercase().as_str() {
456 "anywhere" => Some(DataResidency::Anywhere),
457 "eu" => Some(DataResidency::Eu),
458 _ => None,
459 }
460 }
461}
462
463/// `workspace_residency` takes [`SlugArgs`] and returns
464/// `Option<DataResidency>` (null when there is no such workspace).
465/// `set_workspace_residency`: owners only. Returns `Outcome<DataResidency>`.
466#[derive(Debug, Serialize, Deserialize)]
467pub struct SetResidencyArgs {
468 pub actor: User,
469 pub slug: String,
470 pub residency: DataResidency,
471}
472
473/// `create_workspace`. Returns `Outcome<Workspace>`.
474#[derive(Debug, Serialize, Deserialize)]
475pub struct CreateWorkspaceArgs {
476 pub user: User,
477 pub slug: String,
478 #[serde(default)]
479 pub name: String,
480}
481
482/// `get_workspace`: public details, or null. Returns `Option<Workspace>`.
483#[derive(Debug, Serialize, Deserialize)]
484pub struct SlugArgs {
485 pub slug: String,
486}
487
488/// `list_members`: members only. Owners also see each member's
489/// `two_factor`. Returns `Outcome<Vec<Member>>`.
490#[derive(Debug, Serialize, Deserialize)]
491pub struct ListMembersArgs {
492 pub slug: String,
493 pub viewer: crate::Viewer,
494}
495
496/// `add_member` and `remove_member`: owners only. `add_member` never adds a
497/// person at once: it sends them a workspace invitation to accept or
498/// decline, as `invite_member` with a username does. Only g1t's own agent
499/// is added at once. Removing yourself is
500/// leaving (`members::LeaveWorkspaceArgs`); removing an owner is refused
501/// when they are the last. Each returns `Outcome<bool>`.
502#[derive(Debug, Serialize, Deserialize)]
503pub struct MemberArgs {
504 pub actor: User,
505 pub slug: String,
506 pub username: String,
507 #[serde(default)]
508 pub surface: Option<crate::audit::Surface>,
509}
510
511/// `update_workspace`: owners only. An empty name falls back to the slug;
512/// an empty description clears it. Returns `Outcome<Workspace>`.
513#[derive(Debug, Serialize, Deserialize)]
514pub struct UpdateWorkspaceArgs {
515 pub actor: User,
516 pub slug: String,
517 pub name: String,
518 pub description: String,
519}
520
521/// `rename_workspace`: owners only. Changes the workspace's slug, the first
522/// segment of its URLs, to `new_slug`; the display name is untouched. The
523/// old slug redirects to the new one, and is held for this workspace, for
524/// [`SLUG_HOLD_DAYS`]. Publishes `workspace.renamed`. Returns
525/// `Outcome<Workspace>`.
526///
527/// `check_workspace_rename` takes the same arguments and answers whether
528/// the rename would be allowed, changing nothing. Returns `Outcome<bool>`.
529#[derive(Debug, Serialize, Deserialize)]
530#[serde(rename_all = "camelCase")]
531pub struct RenameWorkspaceArgs {
532 pub actor: User,
533 pub slug: String,
534 pub new_slug: String,
535}
536
537/// `delete_workspace`: owners only, and only a person. `confirm` must be
538/// the workspace's slug, typed out. Refused for a protected workspace
539/// ([`protected_names`]), whoever asks, and while billing cannot settle it
540/// (`close_workspace`). Everything in it goes with it at once: nobody can
541/// reach it, its tokens stop working, its pages are not found, and its
542/// repositories, projects and apps are deleted with it. It is kept for
543/// [`WORKSPACE_RESTORE_DAYS`] so g1t's staff can restore it, then purged:
544/// its memberships, access tokens and old-slug redirects go, and billing's
545/// ledger and the audit log keep its history. The slug is never given to
546/// another workspace; the person whose username it is may make a workspace
547/// of that name again once it is purged. Publishes `workspace.deleting`,
548/// and `workspace.deleted` at the purge. Returns `Outcome<bool>`.
549///
550/// `check_workspace_deletion` takes the same arguments (with `confirm`
551/// ignored) and says what would go and whether anything stands in the way,
552/// changing nothing. Returns `Outcome<WorkspaceDeletion>`.
553#[derive(Debug, Serialize, Deserialize)]
554pub struct DeleteWorkspaceArgs {
555 pub actor: User,
556 pub slug: String,
557 #[serde(default)]
558 pub confirm: String,
559 /// Where the request came in, for the audit log; g1t.sh when absent.
560 #[serde(default)]
561 pub surface: Option<crate::audit::Surface>,
562}
563
564/// What deleting a workspace takes with it, and what stands in the way.
565/// Nothing does when `billing` is null and it is not `protected`.
566#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
567pub struct WorkspaceDeletion {
568 /// Its live repositories, which are deleted with it.
569 pub repositories: u32,
570 /// Its projects, hidden with it.
571 pub projects: u32,
572 #[serde(default)]
573 pub members: u32,
574 /// Why billing cannot close the workspace yet, in words for its owner.
575 pub billing: Option<String>,
576 /// It can never be deleted, by anyone ([`protected_names`]).
577 #[serde(default)]
578 pub protected: bool,
579}
580
581impl WorkspaceDeletion {
582 pub fn blocked(&self) -> bool {
583 self.protected || self.billing.is_some()
584 }
585
586 /// Why the workspace cannot be deleted, as one sentence, or `None`.
587 pub fn reason(&self, slug: &str) -> Option<String> {
588 if self.protected {
589 return Some(protected_refusal(slug));
590 }
591 self.billing.clone()
592 }
593}
594
595/// How long a deleted workspace is kept, for staff to restore, before it is
596/// purged.
597pub const WORKSPACE_RESTORE_DAYS: u64 = 30;
598
599/// Workspaces nobody can delete, whatever identity's `PROTECTED_WORKSPACES`
600/// says: Flagon's, which runs g1t.
601pub const ALWAYS_PROTECTED: &[&str] = &["flagon-io"];
602
603/// The protected workspaces: `configured` (comma-separated slugs or
604/// workspace ids, as identity's `PROTECTED_WORKSPACES` holds them), and
605/// [`ALWAYS_PROTECTED`] whatever it says, so an empty or missing variable
606/// still protects them. Lowercased, without duplicates.
607pub fn protected_names(configured: Option<&str>) -> Vec<String> {
608 let mut names: Vec<String> = Vec::new();
609 let given = configured.unwrap_or_default().split(',');
610 for name in ALWAYS_PROTECTED.iter().copied().chain(given) {
611 let name = name.trim().to_lowercase();
612 if !name.is_empty() && !names.contains(&name) {
613 names.push(name);
614 }
615 }
616 names
617}
618
619/// Why a protected workspace is not deleted, purged or acted on.
620pub fn protected_refusal(slug: &str) -> String {
621 format!("{slug} is protected and can never be deleted.")
622}
623
624/// `admin_deleted_workspaces` takes no arguments (`{}`) and returns
625/// `Vec<DeletedWorkspace>`, newest first. Staff only.
626///
627/// A workspace an owner deleted, kept until `purge_after` for staff to
628/// restore.
629#[derive(Clone, Debug, Serialize, Deserialize)]
630#[serde(rename_all = "camelCase")]
631pub struct DeletedWorkspace {
632 pub workspace_id: String,
633 pub slug: String,
634 pub name: String,
635 /// RFC 3339.
636 pub deleted_at: String,
637 /// The username of the owner who deleted it, or the staff member (by
638 /// email) who deleted it with the account that was its only owner.
639 pub deleted_by: String,
640 /// RFC 3339: when it is purged unless restored first.
641 pub purge_after: String,
642 /// What went with it, counted when it was deleted.
643 pub went: WorkspaceDeletion,
644 /// Whether staff can still restore it.
645 pub restorable: bool,
646}
647
648/// `admin_restore_workspace` and `admin_purge_workspace`: staff restore a
649/// deleted workspace within [`WORKSPACE_RESTORE_DAYS`], or purge it now.
650/// `staff` is who, for the audit logs. Purging needs `confirm`, the slug
651/// typed out, and is refused for a protected workspace. Restoring publishes
652/// `workspace.restored`; purging, `workspace.deleted`. Both return
653/// `Outcome<bool>`.
654#[derive(Debug, Serialize, Deserialize)]
655#[serde(rename_all = "camelCase")]
656pub struct AdminDeletedWorkspaceArgs {
657 pub workspace_id: String,
658 pub staff: String,
659 #[serde(default)]
660 pub confirm: String,
661}
662
663/// `transfer_repo_scopes`: a repository moved from `from` to `to`; the
664/// tokens of agents at work on it are kept pointing at it. For repos'
665/// `transfer`. Returns `bool`.
666#[derive(Debug, Serialize, Deserialize)]
667pub struct TransferRepoScopesArgs {
668 pub from: crate::repos::RepoPath,
669 pub to: crate::repos::RepoPath,
670}
671
672/// How long a workspace's old slug keeps redirecting to it, and stays
673/// reserved for it, after a rename.
674pub const SLUG_HOLD_DAYS: u64 = 90;
675
676/// How long a workspace must wait between renames.
677pub const RENAME_COOLDOWN_HOURS: u64 = 24;
678
679// `resolve_slug` takes `SlugArgs` and returns `Option<String>`: the
680// workspace's current slug when `slug` is one it was renamed from within
681// the last `SLUG_HOLD_DAYS`, and null otherwise (including for a slug that
682// is in use), or the workspace's slug when `slug` is one of its aliases.
683
684// `resolve_alias` takes `SlugArgs` and returns `Option<String>`: the slug
685// now of the workspace `slug` is an alias of, and null when it is none.
686// Aliases are set by g1t's staff only: `g1t` is Flagon, Inc.'s `flagon-io`.
687// An alias follows its workspace through renames.
688
689/// `admin_aliases` takes no arguments (`{}`) and returns
690/// `Vec<WorkspaceAlias>`, by alias. Staff only.
691///
692/// A name staff point at a workspace, so that its addresses (pages, git,
693/// the API, packages) lead to the workspace under its own name.
694#[derive(Clone, Debug, Serialize, Deserialize)]
695#[serde(rename_all = "camelCase")]
696pub struct WorkspaceAlias {
697 pub alias: String,
698 pub workspace_id: String,
699 /// The workspace's slug and name now.
700 pub workspace: String,
701 pub workspace_name: String,
702 /// Why it exists, as staff wrote it.
703 pub note: String,
704 /// The staff member who set it, or `migration`.
705 pub created_by: String,
706 /// RFC 3339.
707 pub created_at: String,
708}
709
710/// `admin_set_alias`: points `alias` at the workspace whose slug is
711/// `workspace`. The alias must have a namespace's shape, must not be one of
712/// the site's routes, and must not be anyone's username, a workspace's slug
713/// (deleted, or held after a rename) or another alias. `note` is required:
714/// it is the reason, kept with the alias and in sudo's audit log. Staff
715/// only. Returns `Outcome<WorkspaceAlias>`.
716#[derive(Debug, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718pub struct AdminSetAliasArgs {
719 pub alias: String,
720 pub workspace: String,
721 pub note: String,
722 pub staff: String,
723}
724
725/// `admin_remove_alias`: the alias stops leading anywhere, and the name is
726/// nobody's again unless it is reserved. `reason` goes in sudo's audit log.
727/// Staff only. Returns `Outcome<bool>`.
728#[derive(Debug, Serialize, Deserialize)]
729#[serde(rename_all = "camelCase")]
730pub struct AdminRemoveAliasArgs {
731 pub alias: String,
732 pub reason: String,
733 pub staff: String,
734}
735
736/// `set_workspace_avatar`: owners only. `image` is the file's bytes in
737/// base64: PNG, JPEG, WebP or GIF, at most `MAX_AVATAR_BYTES`. Null removes
738/// the icon. Returns `Outcome<Workspace>`.
739#[derive(Debug, Serialize, Deserialize)]
740pub struct SetWorkspaceAvatarArgs {
741 pub actor: User,
742 pub slug: String,
743 pub image: Option<String>,
744}
745
746/// `set_user_avatar`: a person's own avatar, as `SetWorkspaceAvatarArgs`.
747/// Returns `Outcome<Option<String>>`: the new avatar, or null once removed.
748#[derive(Debug, Serialize, Deserialize)]
749pub struct SetUserAvatarArgs {
750 pub user: User,
751 pub image: Option<String>,
752}
753
754/// The largest avatar that can be uploaded, in bytes.
755pub const MAX_AVATAR_BYTES: usize = 1024 * 1024;
756
757/// `list_workspace_tokens`: members only. Returns
758/// `Outcome<Vec<AccessToken>>`.
759#[derive(Debug, Serialize, Deserialize)]
760pub struct WorkspaceTokensArgs {
761 pub slug: String,
762 pub viewer: crate::Viewer,
763}
764
765/// `remove_workspace_token`: owners only. Returns `Outcome<bool>`.
766#[derive(Debug, Serialize, Deserialize)]
767pub struct RemoveWorkspaceTokenArgs {
768 pub actor: User,
769 pub slug: String,
770 pub id: String,
771}
772
773/// `oauth_authorize`: the signed-in person approved an application. The
774/// caller has checked the client and that it may be redirected to
775/// `redirect_uri`. Returns `OAuthCode`.
776#[derive(Debug, Serialize, Deserialize)]
777#[serde(rename_all = "camelCase")]
778pub struct OAuthAuthorizeArgs {
779 pub user: User,
780 pub client_id: String,
781 /// Shown wherever the application's access is listed.
782 pub client_name: String,
783 pub redirect_uri: String,
784 /// PKCE challenge, method S256.
785 pub code_challenge: String,
786 /// What the person granted, as `resource:level`. Null: full access.
787 #[serde(default)]
788 pub scopes: Option<Vec<String>>,
789}
790
791#[derive(Debug, Serialize, Deserialize)]
792pub struct OAuthCode {
793 pub code: String,
794}
795
796/// `oauth_exchange`: redeems an authorization code.
797/// Returns `Outcome<OAuthTokens>`.
798#[derive(Debug, Serialize, Deserialize)]
799#[serde(rename_all = "camelCase")]
800pub struct OAuthExchangeArgs {
801 pub code: String,
802 pub code_verifier: String,
803 pub client_id: String,
804 pub redirect_uri: String,
805}
806
807/// `oauth_refresh`: trades a refresh token for new tokens.
808/// Returns `Outcome<OAuthTokens>`.
809#[derive(Debug, Serialize, Deserialize)]
810#[serde(rename_all = "camelCase")]
811pub struct OAuthRefreshArgs {
812 pub refresh_token: String,
813 pub client_id: String,
814}
815
816#[derive(Debug, Serialize, Deserialize)]
817#[serde(rename_all = "camelCase")]
818pub struct OAuthTokens {
819 pub access_token: String,
820 /// Works once; using it returns the next one.
821 pub refresh_token: String,
822 /// Seconds until the access token stops working.
823 pub expires_in: u64,
824 /// The scopes granted, space-separated, or `*` for full access.
825 #[serde(default)]
826 pub scope: Option<String>,
827}
828
829/// An application a person has signed in to. Listed by `list_oauth_grants`
830/// and ended by `revoke_oauth_grant`.
831#[derive(Debug, Serialize, Deserialize)]
832#[serde(rename_all = "camelCase")]
833pub struct OAuthGrant {
834 pub id: String,
835 pub client_name: String,
836 /// RFC 3339.
837 pub created_at: String,
838 /// RFC 3339.
839 pub last_used_at: String,
840 /// What the person granted. Null: full access.
841 #[serde(default)]
842 pub scopes: Option<Vec<String>>,
843 /// Signed in before applications were given scopes: full access until
844 /// someone narrows it.
845 #[serde(default)]
846 pub legacy: bool,
847}
848
849/// `update_oauth_grant`: changes what an application the person signed in
850/// to may do, at once and when it refreshes. Returns `Outcome<OAuthGrant>`.
851#[derive(Debug, Serialize, Deserialize)]
852pub struct UpdateOAuthGrantArgs {
853 pub user: User,
854 pub id: String,
855 #[serde(default)]
856 pub scopes: Option<Vec<String>>,
857}
858
859
860/// What an agent's token may do: these operations, in this repository.
861#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
862pub struct AgentScope {
863 pub repo: crate::repos::RepoPath,
864 /// API and MCP operation names, such as `create_issue`.
865 pub operations: Vec<String>,
866 /// Set on a run credential: the run it belongs to, and what it may do
867 /// with git. See [`crate::credentials`].
868 #[serde(default, skip_serializing_if = "Option::is_none")]
869 pub run: Option<crate::credentials::RunBinding>,
870}
871
872/// `create_agent_token`: a token for a g1t agent working on someone's
873/// behalf. It acts as `g1t`, a member of the repository's workspace,
874/// and only for the operations in `scope`. Returns `CreatedAccessToken`.
875#[derive(Debug, Serialize, Deserialize)]
876#[serde(rename_all = "camelCase")]
877pub struct CreateAgentTokenArgs {
878 /// The person the agent works for; the token is recorded as theirs.
879 pub on_behalf_of: User,
880 pub scope: AgentScope,
881 pub ttl_seconds: u64,
882}
883
884// `agent_scope` takes `TokenArgs` and returns `Option<AgentScope>`: what an
885// agent's token may do, or null for any other token.
886
887/// The id g1t's agent acts under. Only ever stored, never shown: it keeps
888/// the agent's work apart from g1t's own ([`crate::system::ID`]) where
889/// that matters, such as whether its approval counts.
890pub const AGENT_ID: &str = "usr_g1t_agent";
891/// The name g1t's agent is shown by: g1t's own, [`crate::system::USERNAME`].
892/// Everything it does, people see g1t do.
893pub const AGENT_NAME: &str = crate::system::USERNAME;
894
895// --- Staff ---------------------------------------------------------------
896//
897// Staff-only methods, for sudo.g1t.sh. They take no viewer and check no
898// membership: only sudo calls them, over its service binding, after it has
899// verified a Cloudflare Access sign-in and its staff list. Nothing a
900// customer can reach should ever forward to them.
901
902/// `notify_owners`: emails a short notice, with one link, to each owner of
903/// a workspace with a confirmed address. Called by other services (billing
904/// warns owners near their usage limit), never on a person's behalf.
905/// Returns how many were sent.
906#[derive(Clone, Debug, Serialize, Deserialize)]
907pub struct NotifyOwnersArgs {
908 pub workspace: String,
909 pub subject: String,
910 /// One or two sentences: what happened and what it means.
911 pub intro: String,
912 /// The button's words, such as `Open billing`.
913 pub action: String,
914 /// Where the button goes; must be on g1t.sh.
915 pub link: String,
916 /// Small print: why they got it.
917 pub footer: String,
918}
919
920/// `admin_workspaces`: every workspace, newest first, at most
921/// [`ADMIN_WORKSPACES_LIMIT`], optionally only those whose slug, name or
922/// an owner's username or email contains `query`. Returns
923/// `Vec<AdminWorkspace>`. Staff only.
924#[derive(Debug, Default, Serialize, Deserialize)]
925pub struct AdminWorkspacesArgs {
926 #[serde(default)]
927 pub query: Option<String>,
928}
929
930/// The most workspaces one `admin_workspaces` call returns.
931pub const ADMIN_WORKSPACES_LIMIT: usize = 500;
932
933/// An owner of a workspace, as staff see them.
934#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
935pub struct AdminOwner {
936 pub username: String,
937 pub email: Option<String>,
938}
939
940/// A workspace as staff see it: who owns it and how many belong to it.
941#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
942#[serde(rename_all = "camelCase")]
943pub struct AdminWorkspace {
944 pub slug: String,
945 pub name: String,
946 /// RFC 3339.
947 pub created_at: String,
948 pub owners: Vec<AdminOwner>,
949 pub member_count: u32,
950}
951
952/// `admin_workspace`: one workspace with every member, or null. Takes
953/// `SlugArgs`; returns `Option<AdminWorkspaceDetail>`. Staff only.
954#[derive(Clone, Debug, Serialize, Deserialize)]
955#[serde(rename_all = "camelCase")]
956pub struct AdminWorkspaceDetail {
957 pub slug: String,
958 pub name: String,
959 pub description: Option<String>,
960 /// RFC 3339.
961 pub created_at: String,
962 /// Owners first, then by username.
963 pub members: Vec<AdminMember>,
964 /// It can never be deleted ([`protected_names`]).
965 #[serde(default)]
966 pub protected: bool,
967}
968
969/// A member of a workspace, as staff see them.
970#[derive(Clone, Debug, Serialize, Deserialize)]
971pub struct AdminMember {
972 pub username: String,
973 pub email: Option<String>,
974 pub role: crate::Role,
975 /// When they joined the workspace. RFC 3339.
976 pub joined: String,
977}
978
979// --- Profiles ------------------------------------------------------------
980//
981// A person's public page at `g1t.sh/u/<username>`. Everything in a
982// `Profile` is shown to anyone, signed in or not; an email address never is.
983
984/// The most characters each profile field takes.
985pub const MAX_PROFILE_NAME: usize = 80;
986pub const MAX_PROFILE_BIO: usize = 160;
987pub const MAX_PROFILE_LOCATION: usize = 80;
988pub const MAX_PROFILE_WEBSITE: usize = 200;
989pub const MAX_PROFILE_PRONOUNS: usize = 40;
990pub const MAX_PROFILE_TIMEZONE: usize = 64;
991
992/// What anyone may see about a person.
993#[derive(Clone, Debug, Default, Serialize, Deserialize)]
994#[serde(rename_all = "camelCase")]
995pub struct Profile {
996 /// Lowercased: what the profile is found and linked by.
997 pub username: String,
998 /// The username as its owner wrote it, when that differs: what the page shows.
999 #[serde(default, skip_serializing_if = "Option::is_none")]
1000 pub display_username: Option<String>,
1001 /// The name they go by, if they gave one.
1002 pub name: Option<String>,
1003 /// One or two lines about them, at most [`MAX_PROFILE_BIO`] characters.
1004 pub bio: Option<String>,
1005 pub location: Option<String>,
1006 /// An `https://` address.
1007 pub website: Option<String>,
1008 pub pronouns: Option<String>,
1009 /// The time zone they are in, an IANA name such as `America/Denver`.
1010 #[serde(default)]
1011 pub timezone: Option<String>,
1012 /// The uploaded avatar's hash, served at `/avatars/<avatar>`.
1013 pub avatar: Option<String>,
1014 /// When the account was made. RFC 3339.
1015 pub created_at: String,
1016}
1017
1018// `profile` takes `UsernameArgs` and returns `Option<Profile>`: null for
1019// an account that does not exist.
1020
1021/// `update_profile`: a person changes their own profile. Every field is
1022/// replaced; an empty one is cleared. Returns `Outcome<Profile>`.
1023#[derive(Debug, Default, Serialize, Deserialize)]
1024#[serde(rename_all = "camelCase")]
1025pub struct UpdateProfileArgs {
1026 pub actor: User,
1027 #[serde(default)]
1028 pub name: String,
1029 #[serde(default)]
1030 pub bio: String,
1031 #[serde(default)]
1032 pub location: String,
1033 #[serde(default)]
1034 pub website: String,
1035 #[serde(default)]
1036 pub pronouns: String,
1037 /// An IANA time zone name, such as `America/Denver`.
1038 #[serde(default)]
1039 pub timezone: String,
1040}
1041
1042/// `profile_workspaces`: the workspaces shown on a person's profile, as
1043/// `viewer` may see them. A membership is shown only when it is no secret
1044/// from the viewer: a workspace the viewer belongs to as well, or one of
1045/// `public`, the workspaces the caller found the person has made a public
1046/// project in (whose page shows that already). Returns
1047/// `Vec<ProfileWorkspace>`; empty for an account that does not exist.
1048#[derive(Debug, Serialize, Deserialize)]
1049pub struct ProfileWorkspacesArgs {
1050 pub username: String,
1051 pub viewer: crate::Viewer,
1052 #[serde(default)]
1053 pub public: Vec<String>,
1054}
1055
1056/// A workspace on a person's profile.
1057#[derive(Clone, Debug, Serialize, Deserialize)]
1058pub struct ProfileWorkspace {
1059 pub slug: String,
1060 pub name: String,
1061 pub avatar: Option<String>,
1062}
1063
1064/// `directory`: every account or every workspace, as their public pages
1065/// show them, a page at a time in name order. For services that index
1066/// them, such as search; nothing private is in it. Returns
1067/// `DirectoryPage`.
1068#[derive(Debug, Default, Serialize, Deserialize)]
1069pub struct DirectoryArgs {
1070 /// `user` or `workspace`.
1071 pub kind: String,
1072 /// Names after this one.
1073 #[serde(default)]
1074 pub after: Option<String>,
1075 pub limit: u32,
1076}
1077
1078/// One account or workspace in the directory.
1079#[derive(Clone, Debug, Serialize, Deserialize)]
1080#[serde(rename_all = "camelCase")]
1081pub struct DirectoryEntry {
1082 /// The account's or workspace's id.
1083 pub id: String,
1084 /// A username or a workspace's slug.
1085 pub slug: String,
1086 /// A person's display name or a workspace's name.
1087 pub name: Option<String>,
1088 /// A person's bio or a workspace's description.
1089 pub bio: Option<String>,
1090 pub avatar: Option<String>,
1091 /// RFC 3339.
1092 pub created_at: String,
1093}
1094
1095#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1096pub struct DirectoryPage {
1097 pub entries: Vec<DirectoryEntry>,
1098 /// Where the next page starts; null on the last.
1099 pub next: Option<String>,
1100}
1101
1102// --- Invites ---------------------------------------------------------------
1103//
1104// While registration is invite-only, every new account (with a password or
1105// through GitHub) needs an invite code. Each person may have
1106// `INVITES_PER_USER` invites out at a time; staff grant more to a person or
1107// to a workspace, whose owners share them. Inviting an email with no
1108// account into a workspace makes an invite bound to that address, which
1109// registers and joins in one step. See services/identity/src/invites.rs.
1110
1111/// Whether anyone may make an account, or only someone with an invite. Set
1112/// by identity's `REGISTRATION_MODE` var; anything but `open`, including
1113/// leaving it unset, is `invite`, so a missing setting never opens sign-up.
1114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1115#[serde(rename_all = "snake_case")]
1116pub enum RegistrationMode {
1117 #[default]
1118 Invite,
1119 Open,
1120}
1121
1122impl RegistrationMode {
1123 pub fn parse(text: Option<&str>) -> RegistrationMode {
1124 match text.map(|text| text.trim().to_ascii_lowercase()).as_deref() {
1125 Some("open") => RegistrationMode::Open,
1126 _ => RegistrationMode::Invite,
1127 }
1128 }
1129}
1130
1131/// How many invites a person may have out at once, unless identity's
1132/// `INVITES_PER_USER` var says otherwise.
1133pub const INVITES_PER_USER: u32 = 5;
1134
1135/// How long an invite works, unless identity's `INVITE_TTL_DAYS` var says
1136/// otherwise.
1137pub const INVITE_TTL_DAYS: u64 = 30;
1138
1139/// Where an invite stands. Only a pending invite can be used. A pending
1140/// invite can be revoked, and so can one awaiting confirmation. An expired
1141/// or revoked invite that was never used gives its inviter the invite back.
1142#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1143#[serde(rename_all = "snake_case")]
1144pub enum InviteStatus {
1145 Pending,
1146 /// Used to make an account that has not confirmed its email address
1147 /// yet. The code is spent; the workspace (or repository) it gives is
1148 /// joined when the address is confirmed, unless it is revoked first.
1149 AwaitingConfirmation,
1150 /// Used to make an account that has confirmed its address, for a
1151 /// workspace it has not yet joined or declined: the workspace
1152 /// invitation waits for the person's answer (`accept_invitation`).
1153 AwaitingAnswer,
1154 Redeemed,
1155 /// Its person declined the workspace it invited them to.
1156 Declined,
1157 Expired,
1158 Revoked,
1159}
1160
1161/// What using an invite does.
1162#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1163#[serde(rename_all = "snake_case")]
1164pub enum InviteKind {
1165 /// Makes a new account, and joins `workspace` when one is set.
1166 Account,
1167 /// An existing account joins `workspace`. Never makes an account.
1168 Workspace,
1169}
1170
1171/// Whose allowance an invite uses.
1172#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1173#[serde(rename_all = "snake_case")]
1174pub enum InviteCharge {
1175 /// Its inviter's own.
1176 User,
1177 /// The workspace's, granted by staff and shared by its owners.
1178 Workspace,
1179 /// Nobody's: staff minted it, or it invites an existing account.
1180 None,
1181}
1182
1183/// One invite, as the person who made it sees it.
1184#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1185#[serde(rename_all = "camelCase")]
1186pub struct Invite {
1187 pub id: String,
1188 /// The code, such as `g1t-k7m2-q9xd-…`: returned once when the invite
1189 /// is made, and afterwards to whoever made it while it is pending.
1190 /// Null otherwise.
1191 pub code: Option<String>,
1192 /// The code's first group, such as `g1t-k7m2`, to recognise it by.
1193 pub hint: String,
1194 /// Only an account with this address can use it. Null: anyone with
1195 /// the code.
1196 pub email: Option<String>,
1197 pub kind: InviteKind,
1198 /// The workspace it joins, by slug.
1199 pub workspace: Option<String>,
1200 pub status: InviteStatus,
1201 pub charged_to: InviteCharge,
1202 /// Who made it, by username. Null when g1t staff did.
1203 pub invited_by: Option<String>,
1204 /// The account that used it, by username.
1205 pub redeemed_by: Option<String>,
1206 /// RFC 3339.
1207 pub created_at: String,
1208 /// RFC 3339.
1209 pub expires_at: String,
1210 /// RFC 3339.
1211 pub redeemed_at: Option<String>,
1212 /// RFC 3339.
1213 pub revoked_at: Option<String>,
1214 /// The account a workspace invitation is for, by username: someone
1215 /// invited by username, or the account the invite made.
1216 #[serde(default)]
1217 pub invitee: Option<String>,
1218 /// The role `workspace` is joined with. Null when it names none.
1219 #[serde(default)]
1220 pub role: Option<crate::Role>,
1221 /// The staff member who minted it. Only in staff views.
1222 #[serde(default, skip_serializing_if = "Option::is_none")]
1223 pub staff: Option<String>,
1224}
1225
1226/// How many invites someone may have out, and how many they have.
1227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1228pub struct Allowance {
1229 /// Null: no limit.
1230 pub limit: Option<u32>,
1231 /// Pending and used invites; revoked and expired ones are not counted.
1232 pub used: u32,
1233 /// Null: no limit.
1234 pub remaining: Option<u32>,
1235}
1236
1237impl Allowance {
1238 pub fn new(limit: Option<u32>, used: u32) -> Allowance {
1239 Allowance {
1240 limit,
1241 used,
1242 remaining: limit.map(|limit| limit.saturating_sub(used)),
1243 }
1244 }
1245
1246 pub fn exhausted(&self) -> bool {
1247 self.remaining == Some(0)
1248 }
1249}
1250
1251/// A workspace's shared invites, for one of its owners.
1252#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1253pub struct WorkspaceAllowance {
1254 pub slug: String,
1255 pub allowance: Allowance,
1256}
1257
1258/// `list_invites` (takes `UserArgs`): a person's invites, newest first,
1259/// and what they have left. Returns `InvitesOverview`.
1260#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1261pub struct InvitesOverview {
1262 pub mode: RegistrationMode,
1263 pub allowance: Allowance,
1264 /// Workspaces the person owns that staff granted invites to.
1265 pub workspaces: Vec<WorkspaceAllowance>,
1266 pub invites: Vec<Invite>,
1267}
1268
1269/// `create_invite`: a person makes an invite, optionally for one email
1270/// address. People only; never an agent or a workspace's token, and not
1271/// before their email is confirmed. Uses one of the person's invites, or,
1272/// with `workspace`, one of the invites staff granted that workspace (its
1273/// owners only). Emails the address when one is given. Returns
1274/// `Outcome<Invite>`, with the code.
1275///
1276/// `revoke_invite` (takes `RemoveArgs`): its maker revokes a pending
1277/// invite; a workspace's owners may revoke one made for the workspace.
1278/// The invite comes back to whoever it was charged to. Returns
1279/// `Outcome<Invite>`.
1280#[derive(Debug, Serialize, Deserialize)]
1281pub struct CreateInviteArgs {
1282 pub user: User,
1283 #[serde(default)]
1284 pub email: Option<String>,
1285 /// Use this workspace's granted invites, by slug.
1286 #[serde(default)]
1287 pub workspace: Option<String>,
1288 /// The workspace the new account is invited to, by slug: one the
1289 /// person owns that can add members (not on the free plan). Once the
1290 /// account is confirmed it gets a workspace invitation to accept, as a
1291 /// member, and no workspace of its own is made for it.
1292 #[serde(default)]
1293 pub join: Option<String>,
1294 /// The role `join` invites them with; member when absent. Ignored
1295 /// without `join`.
1296 #[serde(default)]
1297 pub join_role: Option<crate::Role>,
1298 /// Where the request came in, for the audit log; g1t.sh when absent.
1299 #[serde(default)]
1300 pub surface: Option<crate::audit::Surface>,
1301}
1302
1303/// `check_invite`: what an invite code is for, before using it. Returns
1304/// `Outcome<InvitePreview>`; a code that is unknown, used, revoked or
1305/// expired gets the same answer, so codes cannot be probed. With
1306/// `any_status`, a real code that can no longer be used is described
1307/// instead (its `status` says why), so the page can say whom to ask for a
1308/// new one; an unknown code still gets the one answer.
1309#[derive(Debug, Serialize, Deserialize)]
1310pub struct InviteCodeArgs {
1311 pub code: String,
1312 /// Who is asking, such as the visitor's IP address, for rate limits.
1313 #[serde(default)]
1314 pub client: Option<String>,
1315 /// Who is looking, if signed in: sets `InvitePreview::for_viewer`.
1316 #[serde(default)]
1317 pub viewer: Option<User>,
1318 #[serde(default)]
1319 pub any_status: bool,
1320 /// The `proof` from the invite email's link, if the page was opened
1321 /// from it: sets `InvitePreview::email_proven`.
1322 #[serde(default)]
1323 pub email_proof: Option<String>,
1324}
1325
1326/// Someone shown on an invite.
1327#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1328pub struct InviteFrom {
1329 pub username: String,
1330 pub name: Option<String>,
1331 pub avatar: Option<String>,
1332}
1333
1334/// A repository an invite code was sent with: using the code accepts the
1335/// invitation to collaborate on it.
1336#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1337pub struct InviteRepository {
1338 /// `workspace/repo`.
1339 pub name: String,
1340 /// The role it gives, such as `write`.
1341 pub role: String,
1342}
1343
1344/// What a valid invite code is for.
1345#[derive(Clone, Debug, Serialize, Deserialize)]
1346#[serde(rename_all = "camelCase")]
1347pub struct InvitePreview {
1348 pub kind: InviteKind,
1349 /// Pending, unless `any_status` asked about a code that is spent.
1350 pub status: InviteStatus,
1351 /// Null when g1t staff sent it.
1352 pub invited_by: Option<InviteFrom>,
1353 pub workspace: Option<ProfileWorkspace>,
1354 /// The repository it accepts an invitation to, if it was sent with one.
1355 pub repository: Option<InviteRepository>,
1356 /// The address it is for, partly hidden, such as `a•••@example.com`.
1357 pub email: Option<String>,
1358 /// The address in full, while it is pending: whoever holds the code
1359 /// was sent it there. Fills in and locks the sign-up form.
1360 pub address: Option<String>,
1361 /// Whether the address it is for has a g1t account already, so the
1362 /// page asks them to sign in rather than sign up.
1363 pub has_account: bool,
1364 /// With a viewer: whether the invite is theirs (it is for one of their
1365 /// confirmed addresses, or they used it). Null without a viewer or,
1366 /// for a pending invite, when it is for anyone with the code.
1367 pub for_viewer: Option<bool>,
1368 /// RFC 3339.
1369 pub expires_at: String,
1370 /// For a shared invite link ([`SharedInvite`]): the group it was made
1371 /// for, such as `Cloudflare judges`. Not secret; the sign-up page shows
1372 /// it. Null for a one-person invite.
1373 #[serde(default)]
1374 pub shared_label: Option<String>,
1375 /// For a shared invite link limited to some email domains: those
1376 /// domains, such as `["cloudflare.com"]`. Empty for any address.
1377 #[serde(default)]
1378 pub shared_domains: Vec<String>,
1379 /// Whether `email_proof` was this pending invite's own, from the email
1380 /// it was sent in: the account made with it starts with `address`
1381 /// confirmed. False without a proof, with a wrong one, and for an
1382 /// invite bound to no address.
1383 #[serde(default)]
1384 pub email_proven: bool,
1385}
1386
1387/// `accept_invite`: a signed-in person uses a workspace invite made for
1388/// their confirmed address, and joins the workspace, or an invite sent with
1389/// a repository invitation, and accepts it. Returns `Outcome<String>`: the
1390/// workspace's slug, or `workspace/repo`.
1391#[derive(Debug, Serialize, Deserialize)]
1392pub struct AcceptInviteArgs {
1393 pub user: User,
1394 pub code: String,
1395}
1396
1397/// `invite_member`: an owner invites an email address into a workspace.
1398/// It always makes an invite bound to that address and emails it, so the
1399/// answer never says whether the address has an account. Without one, the
1400/// invite registers and joins in one step, and uses one of the workspace's
1401/// granted invites or else one of the owner's own. With one, it costs
1402/// nothing. Returns `Outcome<Invite>`, with the code.
1403#[derive(Debug, Serialize, Deserialize)]
1404pub struct InviteMemberArgs {
1405 pub actor: User,
1406 pub slug: String,
1407 /// An email address. Give this or `username`.
1408 #[serde(default)]
1409 pub email: String,
1410 /// A g1t username: that account gets a workspace invitation to accept
1411 /// or decline, in its inbox and by email. Nobody joins without saying
1412 /// yes.
1413 #[serde(default)]
1414 pub username: Option<String>,
1415 /// The role they join with; member when absent.
1416 #[serde(default)]
1417 pub role: Option<crate::Role>,
1418 /// Where the request came in, for the audit log; g1t.sh when absent.
1419 #[serde(default)]
1420 pub surface: Option<crate::audit::Surface>,
1421}
1422
1423/// A workspace invitation waiting for its person's answer, as they see it.
1424/// `list_invitations` (takes `UserArgs`) returns `Vec<WorkspaceInvitation>`,
1425/// newest first: pending ones only, never expired, revoked or answered.
1426#[derive(Clone, Debug, Serialize, Deserialize)]
1427#[serde(rename_all = "camelCase")]
1428pub struct WorkspaceInvitation {
1429 pub id: String,
1430 pub workspace: ProfileWorkspace,
1431 /// The role accepting joins with.
1432 pub role: crate::Role,
1433 /// Null when g1t staff sent it.
1434 pub invited_by: Option<InviteFrom>,
1435 /// RFC 3339.
1436 pub created_at: String,
1437 /// RFC 3339.
1438 pub expires_at: String,
1439}
1440
1441/// `accept_invitation`: the person it is for joins the workspace with the
1442/// role it names. Returns `Outcome<String>`, the workspace's slug.
1443///
1444/// `decline_invitation`: they say no; whoever sent it is told in their
1445/// inbox. Returns `Outcome<bool>`.
1446#[derive(Debug, Serialize, Deserialize)]
1447pub struct InvitationArgs {
1448 pub user: User,
1449 pub id: String,
1450 /// Where the request came in, for the audit log; g1t.sh when absent.
1451 #[serde(default)]
1452 pub surface: Option<crate::audit::Surface>,
1453}
1454
1455/// `find_people`: accounts whose username starts with `query`, or whose
1456/// name contains it, for picking someone to invite. Only what a profile
1457/// shows: a username, a name and an avatar, never an email address.
1458/// Returns `Vec<InviteFrom>`, at most `limit` (10 at most, 8 when absent).
1459#[derive(Debug, Serialize, Deserialize)]
1460pub struct FindPeopleArgs {
1461 pub query: String,
1462 #[serde(default)]
1463 pub limit: Option<u32>,
1464}
1465
1466/// `workspace_invites` (takes `ListMembersArgs`): a workspace's invites,
1467/// newest first. Owners only. Returns `Outcome<Vec<Invite>>`.
1468///
1469/// `revoke_workspace_invite`: owners only. Returns `Outcome<Invite>`.
1470#[derive(Debug, Serialize, Deserialize)]
1471pub struct WorkspaceInviteArgs {
1472 pub actor: User,
1473 pub slug: String,
1474 pub id: String,
1475}
1476
1477/// `request_access`: someone without an invite asks for one. Kept on the
1478/// waitlist, one entry per address. Answers the same way whether or not
1479/// the address is already on it. Returns `Outcome<bool>`.
1480#[derive(Debug, Default, Serialize, Deserialize)]
1481pub struct RequestAccessArgs {
1482 pub email: String,
1483 /// What they will build, if they said.
1484 #[serde(default)]
1485 pub about: String,
1486 /// Who is asking, such as the visitor's IP address, for rate limits.
1487 #[serde(default)]
1488 pub client: Option<String>,
1489}
1490
1491/// The most characters `RequestAccessArgs::about` keeps.
1492pub const MAX_WAITLIST_ABOUT: usize = 1000;
1493
1494// `registration` takes `{}` and returns `RegistrationMode`.
1495
1496// --- Invites, staff only ---
1497
1498#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1499#[serde(rename_all = "snake_case")]
1500pub enum WaitlistStatus {
1501 Waiting,
1502 Invited,
1503 Dismissed,
1504}
1505
1506impl WaitlistStatus {
1507 pub fn as_str(self) -> &'static str {
1508 match self {
1509 WaitlistStatus::Waiting => "waiting",
1510 WaitlistStatus::Invited => "invited",
1511 WaitlistStatus::Dismissed => "dismissed",
1512 }
1513 }
1514}
1515
1516/// Someone who asked for access.
1517#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1518#[serde(rename_all = "camelCase")]
1519pub struct WaitlistEntry {
1520 pub id: String,
1521 pub email: String,
1522 pub about: Option<String>,
1523 pub status: WaitlistStatus,
1524 pub invite_id: Option<String>,
1525 pub decided_by: Option<String>,
1526 /// RFC 3339.
1527 pub decided_at: Option<String>,
1528 /// What staff wrote when approving; it went in the invite email.
1529 #[serde(default)]
1530 pub note: Option<String>,
1531 /// The account made with the invite, once it was used.
1532 #[serde(default)]
1533 pub joined_as: Option<String>,
1534 /// When they first asked. RFC 3339.
1535 pub created_at: String,
1536 /// When they last asked. RFC 3339.
1537 pub updated_at: String,
1538}
1539
1540/// `admin_waitlist`: the waitlist, newest first, at most
1541/// [`ADMIN_INVITES_LIMIT`]. Returns `Vec<WaitlistEntry>`.
1542///
1543/// `admin_waitlist_pending` takes `{}` and returns the number of requests
1544/// still waiting, for sudo's navigation.
1545#[derive(Debug, Default, Serialize, Deserialize)]
1546pub struct AdminWaitlistArgs {
1547 /// Part of an email address or of what they said.
1548 #[serde(default)]
1549 pub query: Option<String>,
1550 /// Null: every status.
1551 #[serde(default)]
1552 pub status: Option<WaitlistStatus>,
1553}
1554
1555/// The most rows one staff listing of invites or the waitlist returns.
1556pub const ADMIN_INVITES_LIMIT: usize = 500;
1557
1558/// `admin_decide_waitlist`: approving mints an invite bound to the
1559/// address, charged to nobody, and emails it, with `note` if given;
1560/// dismissing only marks the entry. Returns `Outcome<WaitlistEntry>`.
1561#[derive(Debug, Serialize, Deserialize)]
1562pub struct AdminDecideWaitlistArgs {
1563 pub id: String,
1564 pub approve: bool,
1565 /// The staff member, by email.
1566 pub staff: String,
1567 /// A line for the invite email, up to [`MAX_WAITLIST_NOTE`] characters.
1568 #[serde(default)]
1569 pub note: Option<String>,
1570}
1571
1572/// The most characters an approval's note keeps.
1573pub const MAX_WAITLIST_NOTE: usize = 500;
1574
1575/// `admin_invites`: every invite, newest first, at most
1576/// [`ADMIN_INVITES_LIMIT`], optionally only those whose code starts with
1577/// `query`, or whose email, inviter or redeemer contains it. Returns
1578/// `Vec<Invite>`.
1579#[derive(Debug, Default, Serialize, Deserialize)]
1580pub struct AdminInvitesArgs {
1581 #[serde(default)]
1582 pub query: Option<String>,
1583}
1584
1585/// `admin_revoke_invite`: revokes any pending invite. Returns
1586/// `Outcome<Invite>`.
1587#[derive(Debug, Serialize, Deserialize)]
1588pub struct AdminRevokeInviteArgs {
1589 pub id: String,
1590 pub staff: String,
1591}
1592
1593/// `admin_mint_invite`: staff make an invite that uses nobody's
1594/// allowance, optionally bound to (and emailed to) an address. Returns
1595/// `Outcome<Invite>`, with the code.
1596#[derive(Debug, Serialize, Deserialize)]
1597pub struct AdminMintInviteArgs {
1598 #[serde(default)]
1599 pub email: Option<String>,
1600 pub staff: String,
1601}
1602
1603/// Who staff grant invites to.
1604#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1605#[serde(rename_all = "snake_case")]
1606pub enum GrantTarget {
1607 User,
1608 Workspace,
1609}
1610
1611impl GrantTarget {
1612 pub fn as_str(self) -> &'static str {
1613 match self {
1614 GrantTarget::User => "user",
1615 GrantTarget::Workspace => "workspace",
1616 }
1617 }
1618}
1619
1620/// `admin_grant_invites`: gives a person (by username) or a workspace (by
1621/// slug) `amount` more invites; a negative amount takes some back. Returns
1622/// `Outcome<Allowance>`: theirs afterwards.
1623#[derive(Debug, Serialize, Deserialize)]
1624pub struct AdminGrantInvitesArgs {
1625 pub target: GrantTarget,
1626 pub name: String,
1627 pub amount: i32,
1628 #[serde(default)]
1629 pub note: String,
1630 pub staff: String,
1631}
1632
1633/// The most invites one grant gives or takes back.
1634pub const MAX_INVITE_GRANT: i32 = 1000;
1635
1636/// Invites staff granted.
1637#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1638#[serde(rename_all = "camelCase")]
1639pub struct InviteGrant {
1640 pub amount: i32,
1641 pub note: Option<String>,
1642 pub granted_by: String,
1643 /// RFC 3339.
1644 pub created_at: String,
1645}
1646
1647/// Someone a person invited, and whom they invited in turn.
1648#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1649#[serde(rename_all = "camelCase")]
1650pub struct InviteTreeNode {
1651 pub username: String,
1652 /// When they used the invite. RFC 3339.
1653 pub joined_at: String,
1654 pub invited: Vec<InviteTreeNode>,
1655}
1656
1657/// `admin_invite_tree` (takes `UsernameArgs`): where a person came from
1658/// and whom they brought, for tracing abuse. Returns `Option<InviteTree>`.
1659///
1660/// `admin_workspace_invites` (takes `SlugArgs`): a workspace's granted
1661/// invites, grants and invites. Returns `Option<InviteTree>` with
1662/// `username` the slug and no `invited_by`.
1663#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1664#[serde(rename_all = "camelCase")]
1665pub struct InviteTree {
1666 pub username: String,
1667 /// Who invited them, then who invited that person, and so on. Empty
1668 /// for an account made without an invite.
1669 pub invited_by: Vec<String>,
1670 /// The staff member who minted their invite, when staff did.
1671 pub staff: Option<String>,
1672 pub allowance: Allowance,
1673 pub grants: Vec<InviteGrant>,
1674 /// Their invites, newest first.
1675 pub invites: Vec<Invite>,
1676 /// Whom they invited, three levels down.
1677 pub invited: Vec<InviteTreeNode>,
1678 /// The shared invite link the account was made with, if it was.
1679 #[serde(default)]
1680 pub shared: Option<SharedInviteSource>,
1681}
1682
1683// --- Shared invite links, staff only ---
1684//
1685// One link for a group (a conference's judges, a post, a community): up
1686// to `max_uses` new accounts, until it expires or staff revoke it,
1687// optionally only for addresses at some domains. Each use makes a new
1688// account, which then makes its own workspace; a shared link never joins
1689// anyone to an existing workspace, and uses nobody's allowance. Its code
1690// looks and is stored like any invite code (only a hash, and a sealed copy
1691// staff can copy again while it is live); the link is
1692// `https://g1t.sh/register?invite=<code>`. See
1693// services/identity/src/shared_invites.rs.
1694
1695/// How long a shared invite link works when staff give no date.
1696pub const SHARED_INVITE_TTL_DAYS: u64 = 14;
1697/// The furthest ahead a shared invite link's last day may be set.
1698pub const SHARED_INVITE_MAX_DAYS: u64 = 365;
1699/// The most accounts one shared invite link makes.
1700pub const MAX_SHARED_INVITE_USES: u32 = 1000;
1701/// The most characters a shared invite link's label keeps.
1702pub const MAX_SHARED_INVITE_LABEL: usize = 80;
1703/// The most email domains one shared invite link may be limited to.
1704pub const MAX_SHARED_INVITE_DOMAINS: usize = 10;
1705
1706/// Where a shared invite link stands. Only a live one makes accounts.
1707#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1708#[serde(rename_all = "snake_case")]
1709pub enum SharedInviteStatus {
1710 Live,
1711 /// Every use is taken.
1712 UsedUp,
1713 Expired,
1714 Revoked,
1715}
1716
1717/// The shared invite link an account was made with.
1718#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1719pub struct SharedInviteSource {
1720 pub id: String,
1721 pub label: String,
1722}
1723
1724/// An account made with a shared invite link.
1725#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1726#[serde(rename_all = "camelCase")]
1727pub struct SharedInviteAccount {
1728 /// Null once the account is purged.
1729 pub username: Option<String>,
1730 /// When it was made with the link. RFC 3339.
1731 pub joined_at: String,
1732}
1733
1734/// One shared invite link, as staff see it.
1735#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1736#[serde(rename_all = "camelCase")]
1737pub struct SharedInvite {
1738 /// `sinv_…`.
1739 pub id: String,
1740 /// Whom it is for, such as `Cloudflare judges`.
1741 pub label: String,
1742 /// The code, while it is live (and IDENTITY_KEY is set).
1743 pub code: Option<String>,
1744 /// The code's first group, such as `g1t-k7m2`.
1745 pub hint: String,
1746 pub max_uses: u32,
1747 /// Accounts made with it so far.
1748 pub uses: u32,
1749 /// Only addresses at these domains may use it; empty for any.
1750 pub domains: Vec<String>,
1751 pub status: SharedInviteStatus,
1752 /// The staff member who made it, by email.
1753 pub staff: String,
1754 /// RFC 3339.
1755 pub created_at: String,
1756 /// RFC 3339.
1757 pub expires_at: String,
1758 pub revoked_at: Option<String>,
1759 pub revoked_by: Option<String>,
1760 /// The accounts made with it, oldest first.
1761 pub accounts: Vec<SharedInviteAccount>,
1762}
1763
1764/// `admin_shared_invites` takes `{}`: shared invite links, newest first,
1765/// at most 200, each with the accounts it made. Returns
1766/// `Vec<SharedInvite>`.
1767///
1768/// `admin_create_shared_invite`: staff make a shared invite link. Recorded
1769/// in sudo's audit log. Returns `Outcome<SharedInvite>`, with the code.
1770#[derive(Debug, Default, Serialize, Deserialize)]
1771pub struct AdminCreateSharedInviteArgs {
1772 /// Required, up to [`MAX_SHARED_INVITE_LABEL`] characters.
1773 pub label: String,
1774 /// 1 to [`MAX_SHARED_INVITE_USES`].
1775 pub max_uses: u32,
1776 /// The last day it works, `YYYY-MM-DD` (UTC; it works until the end of
1777 /// that day), at most [`SHARED_INVITE_MAX_DAYS`] ahead. Null for
1778 /// [`SHARED_INVITE_TTL_DAYS`] from now.
1779 #[serde(default)]
1780 pub expires_on: Option<String>,
1781 /// Email domains it is limited to, such as `cloudflare.com`; empty for
1782 /// any address. Up to [`MAX_SHARED_INVITE_DOMAINS`].
1783 #[serde(default)]
1784 pub domains: Vec<String>,
1785 /// The staff member, by email.
1786 pub staff: String,
1787}
1788
1789/// `admin_revoke_shared_invite`: stops a shared invite link making any
1790/// more accounts. Those it made stay. Recorded in sudo's audit log.
1791/// Returns `Outcome<SharedInvite>`.
1792#[derive(Debug, Serialize, Deserialize)]
1793pub struct AdminRevokeSharedInviteArgs {
1794 pub id: String,
1795 pub staff: String,
1796}
1797
1798#[cfg(test)]
1799mod deletion_tests {
1800 use super::{WorkspaceDeletion, protected_names};
1801
1802 #[test]
1803 fn only_billing_or_protection_stands_in_the_way() {
1804 let clear = WorkspaceDeletion {
1805 repositories: 2,
1806 projects: 1,
1807 members: 3,
1808 ..WorkspaceDeletion::default()
1809 };
1810 assert!(!clear.blocked());
1811 assert_eq!(clear.reason("acme"), None);
1812 let owing = WorkspaceDeletion {
1813 billing: Some("Pay first.".into()),
1814 ..WorkspaceDeletion::default()
1815 };
1816 assert!(owing.blocked());
1817 assert_eq!(owing.reason("acme").as_deref(), Some("Pay first."));
1818 let protected = WorkspaceDeletion {
1819 billing: Some("Pay first.".into()),
1820 protected: true,
1821 ..WorkspaceDeletion::default()
1822 };
1823 assert!(protected.blocked());
1824 assert_eq!(
1825 protected.reason("flagon-io").as_deref(),
1826 Some("flagon-io is protected and can never be deleted.")
1827 );
1828 }
1829
1830 #[test]
1831 fn flagon_is_protected_whatever_the_variable_says() {
1832 assert_eq!(protected_names(None), ["flagon-io"]);
1833 assert_eq!(protected_names(Some("")), ["flagon-io"]);
1834 assert_eq!(protected_names(Some(" , ")), ["flagon-io"]);
1835 assert_eq!(
1836 protected_names(Some("Flagon-IO, acme ,wsp_1")),
1837 ["flagon-io", "acme", "wsp_1"]
1838 );
1839 }
1840}