Skip to content

g1t/crates/contracts/src/identity.rs

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