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