Skip to content

g1t/crates/contracts/src/identity.rs

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