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