OXYGENHUB
◆ v0.6.0 oxygenhub / crates / hub / src / db / accounts.rs
37.2 KiB · Rust · last changed Agent grants: agents act for their owner with no key (keyless step 5) 18 days ago source blame history raw
1
//! Accounts, organisations, teams, collaborators, identities, tokens,
2
//! invitations, settings and the audit log (hub spec §5).
3
4
use super::{now_ms, Pool};
5
use sqlx::FromRow;
6
7
#[derive(Clone, Debug, FromRow)]
8
pub struct Account {
9
    pub id: i64,
10
    pub username: String,
11
    pub display_name: String,
12
    pub email: String,
13
    pub email_verified: bool,
14
    pub password_hash: String,
15
    pub session_salt: String,
16
    pub totp_secret: Option<String>,
17
    pub recovery_codes: String,
18
    pub is_admin: bool,
19
    pub banned: bool,
20
    /// Disabled by an admin: refused like a ban, and enabled again (0031).
21
    #[sqlx(default)]
22
    pub disabled: bool,
23
    pub created_ms: i64,
24
    pub last_seen_ms: i64,
25
    pub email_notifications: bool,
26
    pub unsubscribe_key: String,
27
    /// Shown on the profile page (migration 0008).
28
    #[sqlx(default)]
29
    pub bio: String,
30
    #[sqlx(default)]
31
    pub website: String,
32
    #[sqlx(default)]
33
    pub location: String,
34
    /// `png:<hash>` or `jpeg:<hash>` when a picture was uploaded.
35
    pub avatar: String,
36
    /// Accounts elsewhere (migration 0039, #105): a Bluesky handle, a
37
    /// Mastodon `user@instance`, a GitHub username; empty when not set.
38
    #[sqlx(default)]
39
    pub bluesky: String,
40
    #[sqlx(default)]
41
    pub mastodon: String,
42
    #[sqlx(default)]
43
    pub github: String,
44
}
45
46
impl Account {
47
    /// Whether the account may not sign in or act: banned or disabled.
48
    pub fn blocked(&self) -> bool {
49
        self.banned || self.disabled
50
    }
51
52
    pub fn name(&self) -> &str {
53
        if self.display_name.is_empty() {
54
            &self.username
55
        } else {
56
            &self.display_name
57
        }
58
    }
59
60
    pub fn totp_enabled(&self) -> bool {
61
        self.totp_secret.is_some()
62
    }
63
}
64
65
#[derive(Clone, Debug, FromRow)]
66
pub struct Organisation {
67
    pub id: i64,
68
    pub name: String,
69
    pub display_name: String,
70
    pub description: String,
71
    pub default_role: String,
72
    pub created_ms: i64,
73
    /// `png:<hash>` or `jpeg:<hash>` when a picture was uploaded.
74
    pub avatar: String,
75
    /// Its repositories' Flow priority (oxygenhub#244): `low`, `normal`,
76
    /// `high`, or empty to follow the site's (migration 0073).
77
    #[sqlx(default)]
78
    pub flow_priority: String,
79
}
80
81
pub async fn set_org_flow_priority(pool: &Pool, org_id: i64, priority: &str) -> sqlx::Result<()> {
82
    sqlx::query("UPDATE organisations SET flow_priority = $1 WHERE id = $2").bind(priority).bind(org_id).execute(pool).await?;
83
    Ok(())
84
}
85
86
#[derive(Clone, Debug, FromRow)]
87
pub struct Team {
88
    pub id: i64,
89
    pub org_id: i64,
90
    pub name: String,
91
}
92
93
#[derive(Clone, Debug, FromRow)]
94
pub struct Token {
95
    pub id: i64,
96
    pub account_id: i64,
97
    pub name: String,
98
    pub hash: String,
99
    pub scopes: String,
100
    pub repos: String,
101
    pub created_ms: i64,
102
    pub expires_ms: Option<i64>,
103
    pub last_used_ms: Option<i64>,
104
    /// A renewing token's lifetime: each use extends it to now plus this.
105
    pub renew_ms: Option<i64>,
106
    /// An agent uses it: what is done with it is told to its owner
107
    /// (migration 0065, oxygenhub#183).
108
    #[sqlx(default)]
109
    pub agent: bool,
110
}
111
112
impl Token {
113
    pub fn scope_list(&self) -> Vec<&str> {
114
        self.scopes.split(',').filter(|s| !s.is_empty()).collect()
115
    }
116
117
    pub fn has_scope(&self, scope: &str) -> bool {
118
        self.scope_list().contains(&scope)
119
    }
120
121
    /// Whether the token may touch `owner/name`: every repository when the
122
    /// list is empty.
123
    pub fn covers(&self, slug: &str) -> bool {
124
        self.repos.is_empty() || self.repos.split(',').any(|r| r.trim().eq_ignore_ascii_case(slug))
125
    }
126
127
    pub fn expired(&self, now: i64) -> bool {
128
        self.expires_ms.is_some_and(|e| e < now)
129
    }
130
}
131
132
#[derive(Clone, Debug, FromRow)]
133
pub struct LinkedIdentity {
134
    pub key: String,
135
    pub account_id: i64,
136
    pub name: String,
137
    pub email: String,
138
    pub object: Vec<u8>,
139
    pub linked_ms: i64,
140
}
141
142
#[derive(Clone, Debug, FromRow)]
143
pub struct AuditRow {
144
    pub id: i64,
145
    pub at_ms: i64,
146
    pub actor: String,
147
    pub action: String,
148
    pub target: String,
149
    pub detail: String,
150
}
151
152
// ---------------------------------------------------------------- accounts
153
154
pub async fn account_by_name(pool: &Pool, username: &str) -> sqlx::Result<Option<Account>> {
155
    sqlx::query_as("SELECT * FROM accounts WHERE username = $1").bind(username).fetch_optional(pool).await
156
}
157
158
pub async fn account_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Account>> {
159
    sqlx::query_as("SELECT * FROM accounts WHERE id = $1").bind(id).fetch_optional(pool).await
160
}
161
162
pub async fn accounts(pool: &Pool) -> sqlx::Result<Vec<Account>> {
163
    sqlx::query_as("SELECT * FROM accounts ORDER BY username").fetch_all(pool).await
164
}
165
166
pub async fn account_count(pool: &Pool) -> sqlx::Result<i64> {
167
    sqlx::query_scalar("SELECT COUNT(*) FROM accounts").fetch_one(pool).await
168
}
169
170
pub async fn create_account(
171
    pool: &Pool,
172
    username: &str,
173
    email: &str,
174
    password_hash: &str,
175
    session_salt: &str,
176
    is_admin: bool,
177
) -> sqlx::Result<Account> {
178
    sqlx::query_as(
179
        "INSERT INTO accounts (username, email, password_hash, session_salt, is_admin, created_ms) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
180
    )
181
    .bind(username)
182
    .bind(email)
183
    .bind(password_hash)
184
    .bind(session_salt)
185
    .bind(is_admin)
186
    .bind(now_ms())
187
    .fetch_one(pool)
188
    .await
189
}
190
191
pub async fn set_profile(pool: &Pool, id: i64, display_name: &str, email: &str) -> sqlx::Result<()> {
192
    // A changed address is unverified until its own link is used.
193
    sqlx::query(
194
        "UPDATE accounts SET display_name = $1, email_verified = CASE WHEN email = $2 THEN email_verified ELSE FALSE END, email = $3 WHERE id = $4",
195
    )
196
    .bind(display_name)
197
    .bind(email)
198
    .bind(email)
199
    .bind(id)
200
    .execute(pool)
201
    .await?;
202
    Ok(())
203
}
204
205
/// The public profile fields.
206
/// The accounts elsewhere a profile shows (#105), already normalised.
207
pub async fn set_links(pool: &Pool, id: i64, bluesky: &str, mastodon: &str, github: &str) -> sqlx::Result<()> {
208
    sqlx::query("UPDATE accounts SET bluesky = $1, mastodon = $2, github = $3 WHERE id = $4")
209
        .bind(bluesky)
210
        .bind(mastodon)
211
        .bind(github)
212
        .bind(id)
213
        .execute(pool)
214
        .await?;
215
    Ok(())
216
}
217
218
pub async fn set_bio(pool: &Pool, id: i64, bio: &str, website: &str, location: &str) -> sqlx::Result<()> {
219
    sqlx::query("UPDATE accounts SET bio = $1, website = $2, location = $3 WHERE id = $4")
220
        .bind(bio)
221
        .bind(website)
222
        .bind(location)
223
        .bind(id)
224
        .execute(pool)
225
        .await?;
226
    Ok(())
227
}
228
229
pub async fn set_password(pool: &Pool, id: i64, password_hash: &str, session_salt: &str) -> sqlx::Result<()> {
230
    sqlx::query("UPDATE accounts SET password_hash = $1, session_salt = $2 WHERE id = $3")
231
        .bind(password_hash)
232
        .bind(session_salt)
233
        .bind(id)
234
        .execute(pool)
235
        .await?;
236
    Ok(())
237
}
238
239
pub async fn set_session_salt(pool: &Pool, id: i64, session_salt: &str) -> sqlx::Result<()> {
240
    sqlx::query("UPDATE accounts SET session_salt = $1 WHERE id = $2").bind(session_salt).bind(id).execute(pool).await?;
241
    Ok(())
242
}
243
244
pub async fn set_totp(pool: &Pool, id: i64, secret: Option<&str>, recovery_codes: &str) -> sqlx::Result<()> {
245
    sqlx::query("UPDATE accounts SET totp_secret = $1, recovery_codes = $2 WHERE id = $3")
246
        .bind(secret)
247
        .bind(recovery_codes)
248
        .bind(id)
249
        .execute(pool)
250
        .await?;
251
    Ok(())
252
}
253
254
pub async fn set_admin(pool: &Pool, id: i64, is_admin: bool) -> sqlx::Result<()> {
255
    sqlx::query("UPDATE accounts SET is_admin = $1 WHERE id = $2").bind(is_admin).bind(id).execute(pool).await?;
256
    Ok(())
257
}
258
259
pub async fn set_banned(pool: &Pool, id: i64, banned: bool) -> sqlx::Result<()> {
260
    sqlx::query("UPDATE accounts SET banned = $1 WHERE id = $2").bind(banned).bind(id).execute(pool).await?;
261
    Ok(())
262
}
263
264
pub async fn set_disabled(pool: &Pool, id: i64, disabled: bool) -> sqlx::Result<()> {
265
    sqlx::query("UPDATE accounts SET disabled = $1 WHERE id = $2").bind(disabled).bind(id).execute(pool).await?;
266
    Ok(())
267
}
268
269
/// Delete an account (oxygenhub#81): its row goes, and with it (by the
270
/// schema's cascades) its tokens, keys, sessions' salt, memberships, stars
271
/// and notifications; what it wrote keeps its author's name. The username
272
/// is retired so nobody can register it and pass for the account.
273
pub async fn delete_account(pool: &Pool, id: i64, username: &str) -> sqlx::Result<()> {
274
    let mut tx = super::begin_write(pool).await?;
275
    sqlx::query("INSERT INTO retired_usernames (username, retired_ms) VALUES ($1, $2) ON CONFLICT DO NOTHING")
276
        .bind(username)
277
        .bind(now_ms())
278
        .execute(&mut *tx)
279
        .await?;
280
    sqlx::query("DELETE FROM accounts WHERE id = $1").bind(id).execute(&mut *tx).await?;
281
    tx.commit().await
282
}
283
284
/// The organisations whose only owner is this account: deleting it would
285
/// leave them with nobody to manage them.
286
pub async fn orgs_owned_only_by(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<String>> {
287
    sqlx::query_scalar(
288
        "SELECT o.name FROM organisations o JOIN org_members m ON m.org_id = o.id \
289
         WHERE m.account_id = $1 AND m.role = 'owner' \
290
           AND (SELECT COUNT(*) FROM org_members x WHERE x.org_id = o.id AND x.role = 'owner') = 1 \
291
         ORDER BY o.name",
292
    )
293
    .bind(account_id)
294
    .fetch_all(pool)
295
    .await
296
}
297
298
/// Whether `name` belonged to a deleted account.
299
pub async fn username_retired(pool: &Pool, name: &str) -> sqlx::Result<bool> {
300
    Ok(sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM retired_usernames WHERE username = $1").bind(name).fetch_one(pool).await? > 0)
301
}
302
303
pub async fn touch_seen(pool: &Pool, id: i64) -> sqlx::Result<()> {
304
    sqlx::query("UPDATE accounts SET last_seen_ms = $1 WHERE id = $2").bind(now_ms()).bind(id).execute(pool).await?;
305
    Ok(())
306
}
307
308
// ----------------------------------------------------------- organisations
309
310
pub async fn org_by_name(pool: &Pool, name: &str) -> sqlx::Result<Option<Organisation>> {
311
    sqlx::query_as("SELECT * FROM organisations WHERE name = $1").bind(name).fetch_optional(pool).await
312
}
313
314
pub async fn orgs(pool: &Pool) -> sqlx::Result<Vec<Organisation>> {
315
    sqlx::query_as("SELECT * FROM organisations ORDER BY name").fetch_all(pool).await
316
}
317
318
/// An organisation with the account's role in it.
319
#[derive(FromRow)]
320
struct Membership {
321
    #[sqlx(flatten)]
322
    org: Organisation,
323
    role: String,
324
}
325
326
pub async fn orgs_of(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<(Organisation, String)>> {
327
    let rows: Vec<Membership> = sqlx::query_as(
328
        "SELECT o.*, m.role FROM organisations o JOIN org_members m ON m.org_id = o.id WHERE m.account_id = $1 ORDER BY o.name",
329
    )
330
    .bind(account_id)
331
    .fetch_all(pool)
332
    .await?;
333
    Ok(rows.into_iter().map(|m| (m.org, m.role)).collect())
334
}
335
336
pub async fn create_org(pool: &Pool, name: &str, display_name: &str, owner: i64) -> sqlx::Result<Organisation> {
337
    let mut tx = super::begin_write(pool).await?;
338
    let org: Organisation = sqlx::query_as("INSERT INTO organisations (name, display_name, created_ms) VALUES ($1, $2, $3) RETURNING *")
339
        .bind(name)
340
        .bind(display_name)
341
        .bind(now_ms())
342
        .fetch_one(&mut *tx)
343
        .await?;
344
    sqlx::query("INSERT INTO org_members (org_id, account_id, role) VALUES ($1, $2, 'owner')")
345
        .bind(org.id)
346
        .bind(owner)
347
        .execute(&mut *tx)
348
        .await?;
349
    tx.commit().await?;
350
    Ok(org)
351
}
352
353
pub async fn set_org(pool: &Pool, id: i64, display_name: &str, description: &str, default_role: &str) -> sqlx::Result<()> {
354
    sqlx::query("UPDATE organisations SET display_name = $1, description = $2, default_role = $3 WHERE id = $4")
355
        .bind(display_name)
356
        .bind(description)
357
        .bind(default_role)
358
        .bind(id)
359
        .execute(pool)
360
        .await?;
361
    Ok(())
362
}
363
364
/// `(account, role)` for every member.
365
pub async fn org_members(pool: &Pool, org_id: i64) -> sqlx::Result<Vec<(Account, String)>> {
366
    let rows: Vec<(i64, String)> =
367
        sqlx::query_as("SELECT account_id, role FROM org_members WHERE org_id = $1").bind(org_id).fetch_all(pool).await?;
368
    let mut out = Vec::new();
369
    for (id, role) in rows {
370
        if let Some(a) = account_by_id(pool, id).await? {
371
            out.push((a, role));
372
        }
373
    }
374
    out.sort_by(|a, b| a.0.username.cmp(&b.0.username));
375
    Ok(out)
376
}
377
378
pub async fn org_role(pool: &Pool, org_id: i64, account_id: i64) -> sqlx::Result<Option<String>> {
379
    sqlx::query_scalar("SELECT role FROM org_members WHERE org_id = $1 AND account_id = $2")
380
        .bind(org_id)
381
        .bind(account_id)
382
        .fetch_optional(pool)
383
        .await
384
}
385
386
pub async fn set_org_member(pool: &Pool, org_id: i64, account_id: i64, role: &str) -> sqlx::Result<()> {
387
    sqlx::query("INSERT INTO org_members (org_id, account_id, role) VALUES ($1, $2, $3) ON CONFLICT (org_id, account_id) DO UPDATE SET role = excluded.role")
388
        .bind(org_id)
389
        .bind(account_id)
390
        .bind(role)
391
        .execute(pool)
392
        .await?;
393
    Ok(())
394
}
395
396
pub async fn remove_org_member(pool: &Pool, org_id: i64, account_id: i64) -> sqlx::Result<()> {
397
    sqlx::query("DELETE FROM org_members WHERE org_id = $1 AND account_id = $2").bind(org_id).bind(account_id).execute(pool).await?;
398
    Ok(())
399
}
400
401
pub async fn teams(pool: &Pool, org_id: i64) -> sqlx::Result<Vec<Team>> {
402
    sqlx::query_as("SELECT * FROM teams WHERE org_id = $1 ORDER BY name").bind(org_id).fetch_all(pool).await
403
}
404
405
pub async fn team_by_name(pool: &Pool, org_id: i64, name: &str) -> sqlx::Result<Option<Team>> {
406
    sqlx::query_as("SELECT * FROM teams WHERE org_id = $1 AND name = $2").bind(org_id).bind(name).fetch_optional(pool).await
407
}
408
409
pub async fn create_team(pool: &Pool, org_id: i64, name: &str) -> sqlx::Result<Team> {
410
    sqlx::query_as("INSERT INTO teams (org_id, name) VALUES ($1, $2) RETURNING *").bind(org_id).bind(name).fetch_one(pool).await
411
}
412
413
pub async fn delete_team(pool: &Pool, id: i64) -> sqlx::Result<()> {
414
    sqlx::query("DELETE FROM teams WHERE id = $1").bind(id).execute(pool).await?;
415
    Ok(())
416
}
417
418
pub async fn team_members(pool: &Pool, team_id: i64) -> sqlx::Result<Vec<Account>> {
419
    sqlx::query_as("SELECT a.* FROM accounts a JOIN team_members t ON t.account_id = a.id WHERE t.team_id = $1 ORDER BY a.username")
420
        .bind(team_id)
421
        .fetch_all(pool)
422
        .await
423
}
424
425
pub async fn add_team_member(pool: &Pool, team_id: i64, account_id: i64) -> sqlx::Result<()> {
426
    sqlx::query("INSERT INTO team_members (team_id, account_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
427
        .bind(team_id)
428
        .bind(account_id)
429
        .execute(pool)
430
        .await?;
431
    Ok(())
432
}
433
434
pub async fn remove_team_member(pool: &Pool, team_id: i64, account_id: i64) -> sqlx::Result<()> {
435
    sqlx::query("DELETE FROM team_members WHERE team_id = $1 AND account_id = $2").bind(team_id).bind(account_id).execute(pool).await?;
436
    Ok(())
437
}
438
439
// ----------------------------------------------------------- collaborators
440
441
/// Who an issue of this repository can be assigned to, by username: its
442
/// owner (an account), its collaborators (directly or through a team) and,
443
/// when an organisation owns it, the organisation's members. Blocked
444
/// accounts are left out.
445
pub async fn assignable(pool: &Pool, repo_id: i64, owner: &str) -> sqlx::Result<Vec<String>> {
446
    sqlx::query_scalar(
447
        "SELECT username FROM accounts WHERE banned = FALSE AND disabled = FALSE AND id IN (\
448
           SELECT id FROM accounts WHERE username = $1 \
449
           UNION SELECT account_id FROM collaborators WHERE repo_id = $2 AND account_id IS NOT NULL \
450
           UNION SELECT tm.account_id FROM team_members tm JOIN collaborators c ON c.team_id = tm.team_id WHERE c.repo_id = $2 \
451
           UNION SELECT m.account_id FROM org_members m JOIN organisations o ON o.id = m.org_id WHERE o.name = $1) \
452
         ORDER BY lower(username), username",
453
    )
454
    .bind(owner)
455
    .bind(repo_id)
456
    .fetch_all(pool)
457
    .await
458
}
459
460
#[derive(Clone, Debug)]
461
pub struct Collaborator {
462
    pub account: Option<Account>,
463
    pub team: Option<Team>,
464
    pub role: String,
465
}
466
467
pub async fn collaborators(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<Collaborator>> {
468
    let rows: Vec<(Option<i64>, Option<i64>, String)> =
469
        sqlx::query_as("SELECT account_id, team_id, role FROM collaborators WHERE repo_id = $1").bind(repo_id).fetch_all(pool).await?;
470
    let mut out = Vec::new();
471
    for (account_id, team_id, role) in rows {
472
        let account = match account_id {
473
            Some(id) => account_by_id(pool, id).await?,
474
            None => None,
475
        };
476
        let team = match team_id {
477
            Some(id) => sqlx::query_as("SELECT * FROM teams WHERE id = $1").bind(id).fetch_optional(pool).await?,
478
            None => None,
479
        };
480
        out.push(Collaborator { account, team, role });
481
    }
482
    Ok(out)
483
}
484
485
pub async fn set_collaborator(pool: &Pool, repo_id: i64, account_id: Option<i64>, team_id: Option<i64>, role: &str) -> sqlx::Result<()> {
486
    if let Some(a) = account_id {
487
        sqlx::query("INSERT INTO collaborators (repo_id, account_id, role) VALUES ($1, $2, $3) ON CONFLICT (repo_id, account_id) WHERE account_id IS NOT NULL DO UPDATE SET role = excluded.role")
488
            .bind(repo_id)
489
            .bind(a)
490
            .bind(role)
491
            .execute(pool)
492
            .await?;
493
    } else if let Some(t) = team_id {
494
        sqlx::query("INSERT INTO collaborators (repo_id, team_id, role) VALUES ($1, $2, $3) ON CONFLICT (repo_id, team_id) WHERE team_id IS NOT NULL DO UPDATE SET role = excluded.role")
495
            .bind(repo_id)
496
            .bind(t)
497
            .bind(role)
498
            .execute(pool)
499
            .await?;
500
    }
501
    Ok(())
502
}
503
504
pub async fn remove_collaborator(pool: &Pool, repo_id: i64, account_id: Option<i64>, team_id: Option<i64>) -> sqlx::Result<()> {
505
    sqlx::query("DELETE FROM collaborators WHERE repo_id = $1 AND ((account_id IS NOT NULL AND account_id = $2) OR (team_id IS NOT NULL AND team_id = $3))")
506
        .bind(repo_id)
507
        .bind(account_id)
508
        .bind(team_id)
509
        .execute(pool)
510
        .await?;
511
    Ok(())
512
}
513
514
/// The direct or team role an account holds on a repository, the highest.
515
pub async fn collaborator_role(pool: &Pool, repo_id: i64, account_id: i64) -> sqlx::Result<Option<String>> {
516
    let rows: Vec<String> = sqlx::query_scalar(
517
        "SELECT role FROM collaborators WHERE repo_id = $1 AND (account_id = $2 OR team_id IN (SELECT team_id FROM team_members WHERE account_id = $3))",
518
    )
519
    .bind(repo_id)
520
    .bind(account_id)
521
    .bind(account_id)
522
    .fetch_all(pool)
523
    .await?;
524
    Ok(rows.into_iter().max_by_key(|r| crate::auth::Role::parse(r).map(|r| r as u8).unwrap_or(0)))
525
}
526
527
// ------------------------------------------------------------------ tokens
528
529
pub async fn tokens_of(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<Token>> {
530
    sqlx::query_as("SELECT * FROM tokens WHERE account_id = $1 ORDER BY created_ms DESC").bind(account_id).fetch_all(pool).await
531
}
532
533
/// Mark one of `account_id`'s tokens as an agent's, or not.
534
pub async fn set_token_agent(pool: &Pool, account_id: i64, id: i64, agent: bool) -> sqlx::Result<bool> {
535
    let r = sqlx::query("UPDATE tokens SET agent = $1 WHERE id = $2 AND account_id = $3")
536
        .bind(agent)
537
        .bind(id)
538
        .bind(account_id)
539
        .execute(pool)
540
        .await?;
541
    Ok(r.rows_affected() > 0)
542
}
543
544
pub async fn token_by_hash(pool: &Pool, hash: &str) -> sqlx::Result<Option<Token>> {
545
    sqlx::query_as("SELECT * FROM tokens WHERE hash = $1").bind(hash).fetch_optional(pool).await
546
}
547
548
pub async fn create_token(
549
    pool: &Pool,
550
    account_id: i64,
551
    name: &str,
552
    hash: &str,
553
    scopes: &str,
554
    repos: &str,
555
    expires_ms: Option<i64>,
556
) -> sqlx::Result<Token> {
557
    sqlx::query_as(
558
        "INSERT INTO tokens (account_id, name, hash, scopes, repos, created_ms, expires_ms) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
559
    )
560
    .bind(account_id)
561
    .bind(name)
562
    .bind(hash)
563
    .bind(scopes)
564
    .bind(repos)
565
    .bind(now_ms())
566
    .bind(expires_ms)
567
    .fetch_one(pool)
568
    .await
569
}
570
571
pub async fn delete_token(pool: &Pool, account_id: i64, id: i64) -> sqlx::Result<()> {
572
    sqlx::query("DELETE FROM tokens WHERE id = $1 AND account_id = $2").bind(id).bind(account_id).execute(pool).await?;
573
    Ok(())
574
}
575
576
/// Record a use; a renewing token's expiry moves to now plus its lifetime.
577
pub async fn touch_token(pool: &Pool, id: i64) -> sqlx::Result<()> {
578
    sqlx::query(
579
        "UPDATE tokens SET last_used_ms = $1, \
580
         expires_ms = CASE WHEN renew_ms IS NULL THEN expires_ms WHEN COALESCE(expires_ms, 0) > $1 + renew_ms THEN expires_ms ELSE $1 + renew_ms END \
581
         WHERE id = $2",
582
    )
583
    .bind(now_ms())
584
    .bind(id)
585
    .execute(pool)
586
    .await?;
587
    Ok(())
588
}
589
590
/// Make a token renewing: it lasts `renew_ms` past its last use.
591
pub async fn set_token_renewal(pool: &Pool, id: i64, renew_ms: i64) -> sqlx::Result<()> {
592
    sqlx::query("UPDATE tokens SET renew_ms = $1 WHERE id = $2").bind(renew_ms).bind(id).execute(pool).await?;
593
    Ok(())
594
}
595
596
// ------------------------------------------------------- device sign-in
597
598
/// A device code an app asked for (oxygenhub#67): pending until the user
599
/// approves or denies it on the web.
600
#[derive(Clone, Debug, FromRow)]
601
pub struct DeviceCode {
602
    pub id: i64,
603
    pub device_hash: String,
604
    pub user_code: String,
605
    pub client: String,
606
    pub scopes: String,
607
    pub created_ms: i64,
608
    pub expires_ms: i64,
609
    pub last_poll_ms: i64,
610
    pub account_id: Option<i64>,
611
    pub approved_scopes: String,
612
    pub denied: bool,
613
    /// The address that asked for the code, as the hub saw it.
614
    pub requester: String,
615
}
616
617
impl DeviceCode {
618
    pub fn scope_list(&self) -> Vec<&str> {
619
        self.scopes.split(',').filter(|s| !s.is_empty()).collect()
620
    }
621
}
622
623
pub async fn create_device_code(
624
    pool: &Pool,
625
    device_hash: &str,
626
    user_code: &str,
627
    client: &str,
628
    scopes: &str,
629
    expires_ms: i64,
630
    requester: &str,
631
) -> sqlx::Result<DeviceCode> {
632
    // Expired codes go whenever a new one is made.
633
    sqlx::query("DELETE FROM device_codes WHERE expires_ms < $1").bind(now_ms()).execute(pool).await?;
634
    sqlx::query_as(
635
        "INSERT INTO device_codes (device_hash, user_code, client, scopes, created_ms, expires_ms, requester) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
636
    )
637
    .bind(device_hash)
638
    .bind(user_code)
639
    .bind(client)
640
    .bind(scopes)
641
    .bind(now_ms())
642
    .bind(expires_ms)
643
    .bind(requester)
644
    .fetch_one(pool)
645
    .await
646
}
647
648
pub async fn device_by_user_code(pool: &Pool, user_code: &str) -> sqlx::Result<Option<DeviceCode>> {
649
    sqlx::query_as("SELECT * FROM device_codes WHERE user_code = $1").bind(user_code).fetch_optional(pool).await
650
}
651
652
pub async fn device_by_hash(pool: &Pool, device_hash: &str) -> sqlx::Result<Option<DeviceCode>> {
653
    sqlx::query_as("SELECT * FROM device_codes WHERE device_hash = $1").bind(device_hash).fetch_optional(pool).await
654
}
655
656
/// Approve a pending code for an account with these scopes; false when it
657
/// was no longer pending.
658
pub async fn approve_device(pool: &Pool, id: i64, account_id: i64, scopes: &str) -> sqlx::Result<bool> {
659
    let r = sqlx::query(
660
        "UPDATE device_codes SET account_id = $1, approved_scopes = $2 WHERE id = $3 AND account_id IS NULL AND denied = FALSE AND expires_ms >= $4",
661
    )
662
    .bind(account_id)
663
    .bind(scopes)
664
    .bind(id)
665
    .bind(now_ms())
666
    .execute(pool)
667
    .await?;
668
    Ok(r.rows_affected() == 1)
669
}
670
671
pub async fn deny_device(pool: &Pool, id: i64) -> sqlx::Result<()> {
672
    sqlx::query("UPDATE device_codes SET denied = TRUE WHERE id = $1 AND account_id IS NULL").bind(id).execute(pool).await?;
673
    Ok(())
674
}
675
676
pub async fn device_polled(pool: &Pool, id: i64) -> sqlx::Result<()> {
677
    sqlx::query("UPDATE device_codes SET last_poll_ms = $1 WHERE id = $2").bind(now_ms()).bind(id).execute(pool).await?;
678
    Ok(())
679
}
680
681
/// Remove a code; true when this call removed it (so one poll gets the
682
/// token, however many race).
683
pub async fn delete_device(pool: &Pool, id: i64) -> sqlx::Result<bool> {
684
    let r = sqlx::query("DELETE FROM device_codes WHERE id = $1").bind(id).execute(pool).await?;
685
    Ok(r.rows_affected() == 1)
686
}
687
688
// -------------------------------------------------------------- identities
689
690
pub async fn identities_of(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<LinkedIdentity>> {
691
    sqlx::query_as("SELECT * FROM identities WHERE account_id = $1 ORDER BY linked_ms DESC").bind(account_id).fetch_all(pool).await
692
}
693
694
pub async fn identity_by_key(pool: &Pool, key: &str) -> sqlx::Result<Option<LinkedIdentity>> {
695
    sqlx::query_as("SELECT * FROM identities WHERE key = $1").bind(key).fetch_optional(pool).await
696
}
697
698
/// Every linked key with its account's username, for attribution.
699
pub async fn identity_accounts(pool: &Pool) -> sqlx::Result<Vec<(String, String)>> {
700
    sqlx::query_as("SELECT i.key, a.username FROM identities i JOIN accounts a ON a.id = i.account_id").fetch_all(pool).await
701
}
702
703
pub async fn link_identity(pool: &Pool, account_id: i64, key: &str, name: &str, email: &str, object: &[u8]) -> sqlx::Result<()> {
704
    sqlx::query("INSERT INTO identities (key, account_id, name, email, object, linked_ms) VALUES ($1, $2, $3, $4, $5, $6)")
705
        .bind(key)
706
        .bind(account_id)
707
        .bind(name)
708
        .bind(email)
709
        .bind(object)
710
        .bind(now_ms())
711
        .execute(pool)
712
        .await?;
713
    Ok(())
714
}
715
716
pub async fn unlink_identity(pool: &Pool, account_id: i64, key: &str) -> sqlx::Result<()> {
717
    sqlx::query("DELETE FROM identities WHERE key = $1 AND account_id = $2").bind(key).bind(account_id).execute(pool).await?;
718
    Ok(())
719
}
720
721
pub async fn create_challenge(pool: &Pool, account_id: i64, bytes_hex: &str) -> sqlx::Result<i64> {
722
    sqlx::query("DELETE FROM challenges WHERE created_ms < $1").bind(now_ms() - 10 * 60 * 1000).execute(pool).await?;
723
    let id: i64 = sqlx::query_scalar("INSERT INTO challenges (account_id, bytes, created_ms) VALUES ($1, $2, $3) RETURNING id")
724
        .bind(account_id)
725
        .bind(bytes_hex)
726
        .bind(now_ms())
727
        .fetch_one(pool)
728
        .await?;
729
    Ok(id)
730
}
731
732
/// Take (and delete) a pending challenge of this account.
733
pub async fn take_challenge(pool: &Pool, account_id: i64, id: i64) -> sqlx::Result<Option<String>> {
734
    let bytes: Option<String> = sqlx::query_scalar("SELECT bytes FROM challenges WHERE id = $1 AND account_id = $2 AND created_ms >= $3")
735
        .bind(id)
736
        .bind(account_id)
737
        .bind(now_ms() - 10 * 60 * 1000)
738
        .fetch_optional(pool)
739
        .await?;
740
    sqlx::query("DELETE FROM challenges WHERE id = $1").bind(id).execute(pool).await?;
741
    Ok(bytes)
742
}
743
744
// ------------------------------------------------------------- invitations
745
746
pub async fn create_invitation(pool: &Pool, code: &str, created_by: Option<i64>) -> sqlx::Result<()> {
747
    sqlx::query("INSERT INTO invitations (code, created_by, created_ms) VALUES ($1, $2, $3)")
748
        .bind(code)
749
        .bind(created_by)
750
        .bind(now_ms())
751
        .execute(pool)
752
        .await?;
753
    Ok(())
754
}
755
756
pub async fn invitation_unused(pool: &Pool, code: &str) -> sqlx::Result<bool> {
757
    let n: i64 =
758
        sqlx::query_scalar("SELECT COUNT(*) FROM invitations WHERE code = $1 AND used_by IS NULL").bind(code).fetch_one(pool).await?;
759
    Ok(n > 0)
760
}
761
762
/// Use an invitation up if it is still unused; whether it was.
763
pub async fn claim_invitation(pool: &Pool, code: &str, account_id: i64) -> sqlx::Result<bool> {
764
    let r = sqlx::query("UPDATE invitations SET used_by = $1 WHERE code = $2 AND used_by IS NULL")
765
        .bind(account_id)
766
        .bind(code)
767
        .execute(pool)
768
        .await?;
769
    Ok(r.rows_affected() > 0)
770
}
771
772
pub async fn use_invitation(pool: &Pool, code: &str, account_id: i64) -> sqlx::Result<()> {
773
    sqlx::query("UPDATE invitations SET used_by = $1 WHERE code = $2").bind(account_id).bind(code).execute(pool).await?;
774
    Ok(())
775
}
776
777
pub async fn invitations(pool: &Pool) -> sqlx::Result<Vec<(String, Option<i64>, i64)>> {
778
    sqlx::query_as("SELECT code, used_by, created_ms FROM invitations ORDER BY created_ms DESC").fetch_all(pool).await
779
}
780
781
// ---------------------------------------------------------------- settings
782
783
pub async fn setting(pool: &Pool, key: &str) -> sqlx::Result<Option<String>> {
784
    sqlx::query_scalar("SELECT value FROM settings WHERE key = $1").bind(key).fetch_optional(pool).await
785
}
786
787
pub async fn set_setting(pool: &Pool, key: &str, value: &str) -> sqlx::Result<()> {
788
    sqlx::query("INSERT INTO settings (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
789
        .bind(key)
790
        .bind(value)
791
        .execute(pool)
792
        .await?;
793
    Ok(())
794
}
795
796
// ------------------------------------------------------------------- audit
797
798
pub async fn audit(pool: &Pool, actor: Option<&Account>, action: &str, target: &str, detail: &str) -> sqlx::Result<()> {
799
    sqlx::query("INSERT INTO audit (at_ms, actor_id, actor, action, target, detail) VALUES ($1, $2, $3, $4, $5, $6)")
800
        .bind(now_ms())
801
        .bind(actor.map(|a| a.id))
802
        .bind(actor.map(|a| a.username.as_str()).unwrap_or(""))
803
        .bind(action)
804
        .bind(target)
805
        .bind(detail)
806
        .execute(pool)
807
        .await?;
808
    Ok(())
809
}
810
811
/// A page of the audit log, newest first, older than `before` (an id) when given.
812
pub async fn audit_page(pool: &Pool, before: Option<i64>, limit: i64) -> sqlx::Result<Vec<AuditRow>> {
813
    sqlx::query_as("SELECT id, at_ms, actor, action, target, detail FROM audit WHERE ($1 IS NULL OR id < $2) ORDER BY id DESC LIMIT $3")
814
        .bind(before)
815
        .bind(before)
816
        .bind(limit)
817
        .fetch_all(pool)
818
        .await
819
}
820
821
pub async fn audit_rows(pool: &Pool, limit: i64) -> sqlx::Result<Vec<AuditRow>> {
822
    sqlx::query_as("SELECT id, at_ms, actor, action, target, detail FROM audit ORDER BY at_ms DESC, id DESC LIMIT $1")
823
        .bind(limit)
824
        .fetch_all(pool)
825
        .await
826
}
827
828
/// The repositories an account can see beyond the public ones: its own,
829
/// its organisations', and those it collaborates on.
830
pub async fn visible_repo_ids(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<i64>> {
831
    sqlx::query_scalar(
832
        "SELECT r.id FROM repositories r WHERE r.owner IN (SELECT username FROM accounts WHERE id = $1) \
833
         OR r.owner IN (SELECT o.name FROM organisations o JOIN org_members m ON m.org_id = o.id WHERE m.account_id = $2) \
834
         OR r.id IN (SELECT repo_id FROM collaborators WHERE account_id = $3 OR team_id IN (SELECT team_id FROM team_members WHERE account_id = $4))",
835
    )
836
    .bind(account_id)
837
    .bind(account_id)
838
    .bind(account_id)
839
    .bind(account_id)
840
    .fetch_all(pool)
841
    .await
842
}
843
844
// ------------------------------------------------------ account links
845
846
/// A verification or reset link (hub spec §5.1.1).
847
#[derive(Clone, Debug, FromRow)]
848
pub struct AccountLink {
849
    pub id: i64,
850
    pub account_id: i64,
851
    pub kind: String,
852
    pub hash: String,
853
    pub email: String,
854
    pub created_by: Option<i64>,
855
    pub created_ms: i64,
856
    pub expires_ms: i64,
857
    pub used_ms: Option<i64>,
858
}
859
860
/// Make a link; returns its secret (shown or sent once, stored as a hash).
861
pub async fn create_link(
862
    pool: &Pool,
863
    account_id: i64,
864
    kind: &str,
865
    email: &str,
866
    created_by: Option<i64>,
867
    ttl_ms: i64,
868
) -> sqlx::Result<String> {
869
    let secret = crate::auth::random_hex(32);
870
    let now = now_ms();
871
    sqlx::query(
872
        "INSERT INTO account_links (account_id, kind, hash, email, created_by, created_ms, expires_ms) VALUES ($1, $2, $3, $4, $5, $6, $7)",
873
    )
874
    .bind(account_id)
875
    .bind(kind)
876
    .bind(crate::auth::token_hash(&secret))
877
    .bind(email)
878
    .bind(created_by)
879
    .bind(now)
880
    .bind(now + ttl_ms)
881
    .execute(pool)
882
    .await?;
883
    Ok(secret)
884
}
885
886
/// An unused, unexpired link of this kind with this secret.
887
pub async fn live_link(pool: &Pool, kind: &str, secret: &str) -> sqlx::Result<Option<AccountLink>> {
888
    sqlx::query_as("SELECT * FROM account_links WHERE kind = $1 AND hash = $2 AND used_ms IS NULL AND expires_ms > $3")
889
        .bind(kind)
890
        .bind(crate::auth::token_hash(secret))
891
        .bind(now_ms())
892
        .fetch_optional(pool)
893
        .await
894
}
895
896
/// Consume a link; false when it was already used (a race lost).
897
pub async fn use_link(pool: &Pool, id: i64) -> sqlx::Result<bool> {
898
    let r = sqlx::query("UPDATE account_links SET used_ms = $1 WHERE id = $2 AND used_ms IS NULL")
899
        .bind(now_ms())
900
        .bind(id)
901
        .execute(pool)
902
        .await?;
903
    Ok(r.rows_affected() == 1)
904
}
905
906
/// Void every unused link of a kind for an account.
907
pub async fn void_links(pool: &Pool, account_id: i64, kind: &str) -> sqlx::Result<()> {
908
    sqlx::query("UPDATE account_links SET used_ms = $1 WHERE account_id = $2 AND kind = $3 AND used_ms IS NULL")
909
        .bind(now_ms())
910
        .bind(account_id)
911
        .bind(kind)
912
        .execute(pool)
913
        .await?;
914
    Ok(())
915
}
916
917
/// When the account's newest link of a kind (for this address, when given) was made, for rate limits.
918
pub async fn last_link_ms(pool: &Pool, account_id: i64, kind: &str, email: Option<&str>) -> sqlx::Result<Option<i64>> {
919
    match email {
920
        Some(e) => {
921
            sqlx::query_scalar("SELECT MAX(created_ms) FROM account_links WHERE account_id = $1 AND kind = $2 AND email = $3")
922
                .bind(account_id)
923
                .bind(kind)
924
                .bind(e)
925
                .fetch_one(pool)
926
                .await
927
        }
928
        None => {
929
            sqlx::query_scalar("SELECT MAX(created_ms) FROM account_links WHERE account_id = $1 AND kind = $2")
930
                .bind(account_id)
931
                .bind(kind)
932
                .fetch_one(pool)
933
                .await
934
        }
935
    }
936
}
937
938
/// How many links of a kind the account got since `since_ms`.
939
pub async fn links_since(pool: &Pool, account_id: i64, kind: &str, since_ms: i64) -> sqlx::Result<i64> {
940
    sqlx::query_scalar("SELECT COUNT(*) FROM account_links WHERE account_id = $1 AND kind = $2 AND created_ms >= $3")
941
        .bind(account_id)
942
        .bind(kind)
943
        .bind(since_ms)
944
        .fetch_one(pool)
945
        .await
946
}
947
948
pub async fn set_email_verified(pool: &Pool, id: i64, verified: bool) -> sqlx::Result<()> {
949
    sqlx::query("UPDATE accounts SET email_verified = $1 WHERE id = $2").bind(verified).bind(id).execute(pool).await?;
950
    Ok(())
951
}
952
953
/// The account with this verified email (case-insensitive), if exactly one.
954
pub async fn account_by_verified_email(pool: &Pool, email: &str) -> sqlx::Result<Option<Account>> {
955
    let found: Vec<Account> = sqlx::query_as("SELECT * FROM accounts WHERE email_verified = TRUE AND lower(email) = lower($1) LIMIT 2")
956
        .bind(email)
957
        .fetch_all(pool)
958
        .await?;
959
    Ok(if found.len() == 1 { found.into_iter().next() } else { None })
960
}
961
962
/// Set or clear the picture of an account (`account`) or organisation (`org`).
963
pub async fn set_avatar(pool: &Pool, kind: &str, id: i64, value: &str) -> sqlx::Result<()> {
964
    let table = if kind == "org" { "organisations" } else { "accounts" };
965
    sqlx::query(&format!("UPDATE {table} SET avatar = $1 WHERE id = $2")).bind(value).bind(id).execute(pool).await?;
966
    Ok(())
967
}
968
969
// ------------------------------------------------------------ agent grants
970
971
/// An agent an account lets act for it (oxygenhub#241, migration 0075).
972
#[derive(Clone, Debug, FromRow)]
973
pub struct AgentGrant {
974
    pub id: i64,
975
    pub account_id: i64,
976
    pub agent: String,
977
    pub subject: String,
978
    /// The owner's KeyId (hex) that signed the grant.
979
    pub grantor: String,
980
    pub scope: String,
981
    /// The signed Oxygen grant, as certificates carry it.
982
    pub signed: Vec<u8>,
983
    pub token_hash: String,
984
    pub created_ms: i64,
985
    pub expires_ms: i64,
986
    pub revoked_ms: Option<i64>,
987
    pub last_used_ms: Option<i64>,
988
}
989
990
impl AgentGrant {
991
    /// Whether certificates may still be issued under it at `now`.
992
    pub fn live(&self, now: i64) -> bool {
993
        self.revoked_ms.is_none() && now < self.expires_ms
994
    }
995
}
996
997
pub struct NewAgentGrant<'a> {
998
    pub account_id: i64,
999
    pub agent: &'a str,
1000
    pub subject: &'a str,
1001
    pub grantor: &'a str,
1002
    pub scope: &'a str,
1003
    pub signed: &'a [u8],
1004
    pub token_hash: &'a str,
1005
    pub expires_ms: i64,
1006
}
1007
1008
pub async fn create_agent_grant(pool: &Pool, g: NewAgentGrant<'_>) -> sqlx::Result<i64> {
1009
    sqlx::query_scalar(
1010
        "INSERT INTO agent_grants (account_id, agent, subject, grantor, scope, signed, token_hash, created_ms, expires_ms) \
1011
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id",
1012
    )
1013
    .bind(g.account_id)
1014
    .bind(g.agent)
1015
    .bind(g.subject)
1016
    .bind(g.grantor)
1017
    .bind(g.scope)
1018
    .bind(g.signed)
1019
    .bind(g.token_hash)
1020
    .bind(now_ms())
1021
    .bind(g.expires_ms)
1022
    .fetch_one(pool)
1023
    .await
1024
}
1025
1026
pub async fn agent_grants_of(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<AgentGrant>> {
1027
    sqlx::query_as("SELECT * FROM agent_grants WHERE account_id = $1 ORDER BY created_ms DESC, id DESC")
1028
        .bind(account_id)
1029
        .fetch_all(pool)
1030
        .await
1031
}
1032
1033
pub async fn agent_grant_by_token(pool: &Pool, token_hash: &str) -> sqlx::Result<Option<AgentGrant>> {
1034
    sqlx::query_as("SELECT * FROM agent_grants WHERE token_hash = $1").bind(token_hash).fetch_optional(pool).await
1035
}
1036
1037
pub async fn touch_agent_grant(pool: &Pool, id: i64) -> sqlx::Result<()> {
1038
    sqlx::query("UPDATE agent_grants SET last_used_ms = $1 WHERE id = $2").bind(now_ms()).bind(id).execute(pool).await?;
1039
    Ok(())
1040
}
1041
1042
/// Revoke one of the account's grants; true when this call revoked it.
1043
pub async fn revoke_agent_grant(pool: &Pool, account_id: i64, id: i64) -> sqlx::Result<bool> {
1044
    let r = sqlx::query("UPDATE agent_grants SET revoked_ms = $1 WHERE id = $2 AND account_id = $3 AND revoked_ms IS NULL")
1045
        .bind(now_ms())
1046
        .bind(id)
1047
        .bind(account_id)
1048
        .execute(pool)
1049
        .await?;
1050
    Ok(r.rows_affected() == 1)
1051
}