Skip to main content

comindly_api/
server.rs

1use serde::{Deserialize, Serialize};
2
3/// A way to sign in: an emailed link, a code, or an OpenID Connect provider; a server offers one or
4/// more, each for invited people only.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "lowercase")]
7pub enum SignIn {
8    Email,
9    Code,
10    Oidc,
11}
12
13/// What someone may do, each role including the ones below it.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Role {
17    /// Members, repositories, settings, secrets and indexing.
18    Admin,
19    /// Writes to the ledger and conventions.
20    Member,
21    /// Reads.
22    Viewer,
23}
24
25impl Role {
26    pub fn as_str(self) -> &'static str {
27        match self {
28            Role::Admin => "admin",
29            Role::Member => "member",
30            Role::Viewer => "viewer",
31        }
32    }
33
34    fn rank(self) -> u8 {
35        match self {
36            Role::Admin => 2,
37            Role::Member => 1,
38            Role::Viewer => 0,
39        }
40    }
41
42    /// This role may do what `other` may.
43    pub fn at_least(self, other: Role) -> bool {
44        self.rank() >= other.rank()
45    }
46}
47
48/// How a request proved who it is.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Via {
51    Session,
52    AdminToken,
53    /// A personal access token: enough for agents, not for managing the account.
54    Token,
55}
56
57#[derive(Debug, Serialize, Deserialize)]
58pub struct Member {
59    pub email: String,
60    pub role: Role,
61    pub fixed: bool,
62    pub created: String,
63    pub last_seen: Option<String>,
64    /// A service account: no person, no sign-in, only tokens an admin creates.
65    #[serde(default)]
66    pub service: bool,
67    /// A service account's display name; its handle is in `email`.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub name: Option<String>,
70}
71
72/// Service accounts are members at this reserved domain, which no mailbox or identity provider has.
73pub const SERVICE_DOMAIN: &str = "service.invalid";
74
75/// The member address of service account `name`: lowercase letters, digits and dashes, 1-40.
76pub fn service_email(name: &str) -> Option<String> {
77    let name = name.trim();
78    let ok = (1..=40).contains(&name.len())
79        && name
80            .chars()
81            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
82        && !name.starts_with('-')
83        && !name.ends_with('-');
84    ok.then(|| format!("{name}@{SERVICE_DOMAIN}"))
85}
86
87/// The handle a display name gives: "Build Bot 2" → `build-bot-2`.
88pub fn service_handle(display: &str) -> String {
89    let mut out = String::new();
90    for c in display.trim().chars().flat_map(char::to_lowercase) {
91        if c.is_ascii_alphanumeric() {
92            out.push(c);
93        } else if !out.ends_with('-') && !out.is_empty() {
94            out.push('-');
95        }
96    }
97    out.trim_end_matches('-')
98        .chars()
99        .take(40)
100        .collect::<String>()
101        .trim_end_matches('-')
102        .to_string()
103}
104
105/// The service account's name, when `email` is one.
106pub fn service_name(email: &str) -> Option<&str> {
107    email
108        .strip_suffix(SERVICE_DOMAIN)
109        .and_then(|n| n.strip_suffix('@'))
110        .filter(|n| !n.is_empty())
111}
112
113/// `POST /api/v1/members/service`: create a service account.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct NewService {
116    pub name: String,
117    pub role: Role,
118}
119
120/// `POST /api/v1/members/service/token`: a token for a service account.
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ServiceTokenRequest {
123    pub name: String,
124    pub token_name: String,
125    /// Days until it expires; `None` never.
126    #[serde(default)]
127    pub expires_in_days: Option<u32>,
128    /// Addresses (`203.0.113.7`) or ranges (`203.0.113.0/24`) it works from; empty is anywhere.
129    #[serde(default)]
130    pub allowed: Vec<String>,
131}
132
133/// `POST /api/v1/members/tokens/revoke`: an admin revokes a member's token, or all with no `id`.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct MemberTokenRevoke {
136    pub email: String,
137    #[serde(default)]
138    pub id: Option<String>,
139}
140
141#[derive(Debug, Serialize, Deserialize)]
142pub struct Invite {
143    pub email: String,
144    pub role: Role,
145    pub created_by: String,
146    pub expires: String,
147}
148
149#[derive(Debug, Serialize, Deserialize)]
150pub struct AccessToken {
151    pub id: String,
152    pub name: String,
153    pub created: String,
154    pub last_used: Option<String>,
155    /// `None` for a token that never expires.
156    pub expires: Option<String>,
157    pub expired: bool,
158    /// Addresses or ranges it works from; empty is anywhere.
159    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160    pub allowed: Vec<String>,
161}
162
163/// One row of the audit log; details never hold token values or codes.
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct AuditEntry {
166    pub at: String,
167    pub actor: String,
168    pub action: String,
169    pub detail: String,
170}
171
172/// Which audit entries to list: `before` is the `next` cursor of the previous page.
173#[derive(Debug, Default, Serialize, Deserialize)]
174pub struct AuditQuery {
175    pub limit: Option<usize>,
176    pub before: Option<String>,
177    pub actor: Option<String>,
178    pub action: Option<String>,
179}
180
181#[derive(Debug, Serialize, Deserialize)]
182pub struct AuditPage {
183    pub entries: Vec<AuditEntry>,
184    /// The cursor for the next (older) page, when there is one.
185    pub next: Option<String>,
186}
187
188/// A secret's state for the UI; its value never leaves the server.
189#[derive(Debug, Serialize, Deserialize)]
190pub struct SecretInfo {
191    pub name: String,
192    pub source: String,
193    pub hint: Option<String>,
194    pub updated: Option<String>,
195    pub updated_by: Option<String>,
196}
197
198/// What a member sees before approving a command-line sign-in.
199#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct DeviceRequest {
201    pub client: String,
202    pub expires: String,
203}
204
205/// Where a command-line sign-in stands.
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub enum DevicePoll {
208    Pending,
209    Approved {
210        token: String,
211        email: String,
212        expires: Option<String>,
213    },
214    Denied,
215    Expired,
216}
217
218/// How long a token lasts unless chosen otherwise, and a command-line sign-in's always.
219pub const TOKEN_DAYS: u32 = 90;
220
221#[cfg(test)]
222mod service_tests {
223    use super::*;
224
225    #[test]
226    fn handles_come_from_display_names() {
227        assert_eq!(service_handle("Build Bot 2"), "build-bot-2");
228        assert_eq!(service_handle("  CI / nightly!! "), "ci-nightly");
229        assert_eq!(service_handle("!!!"), "");
230        assert_eq!(
231            service_email("build-bot").as_deref(),
232            Some("build-bot@service.invalid")
233        );
234        assert_eq!(service_name("build-bot@service.invalid"), Some("build-bot"));
235        assert_eq!(service_name("ada@example.com"), None);
236    }
237}