Skip to main content

kasl_server/
provision.rs

1//! Getting the first agents onto a server that has no admin UI yet.
2//!
3//! Until accounts and token issuing arrive with the people milestone, the
4//! operator declares agents in the environment:
5//!
6//! ```text
7//! KASL_AGENTS=alice@example.com:s3cr3t-token,bob@example.com:another-token
8//! ```
9//!
10//! On startup each entry becomes a user and an agent holding that token's
11//! hash. Deliberately not a public enrollment endpoint: a server whose only
12//! way in is a secret the operator already knows cannot be joined by anyone
13//! who does not.
14//!
15//! This is a bootstrap, and it says so - when the admin UI issues tokens, the
16//! variable stops being the way in and the ingest contract does not change.
17
18use anyhow::{Context, Result};
19use sqlx::PgPool;
20
21use crate::{auth::hash_token, session::hash_password};
22
23/// One `email:token` pair from the environment.
24#[derive(Debug, PartialEq, Eq)]
25pub struct AgentSeed {
26    pub email: String,
27    pub token: String,
28}
29
30/// Parses `KASL_AGENTS`. An empty or absent value yields nothing, which is the
31/// normal state of a server whose agents are already in the database.
32pub fn parse_seeds(raw: &str) -> Result<Vec<AgentSeed>> {
33    let mut seeds = Vec::new();
34
35    for entry in raw.split(',').map(str::trim).filter(|entry| !entry.is_empty()) {
36        // `rsplit_once` so a colon inside the token - plausible in a generated
37        // secret - stays part of it.
38        let (email, token) = entry
39            .split_once(':')
40            .with_context(|| format!("KASL_AGENTS entry `{entry}` is not `email:token`"))?;
41        let (email, token) = (email.trim(), token.trim());
42
43        if email.is_empty() || token.is_empty() {
44            anyhow::bail!("KASL_AGENTS entry `{entry}` has an empty email or token");
45        }
46
47        seeds.push(AgentSeed {
48            email: email.to_string(),
49            token: token.to_string(),
50        });
51    }
52
53    Ok(seeds)
54}
55
56/// Creates or updates the declared users and agents.
57///
58/// Idempotent: restarting the server with the same variable changes nothing,
59/// and rotating a token in the variable rotates it in the database.
60pub async fn apply_seeds(pool: &PgPool, seeds: &[AgentSeed]) -> Result<()> {
61    for seed in seeds {
62        let mut tx = pool.begin().await?;
63
64        // The display name is the local part until someone sets a real one;
65        // the admin UI will own this field later.
66        let display_name = seed.email.split('@').next().unwrap_or(&seed.email);
67
68        let user_id: uuid::Uuid = sqlx::query_scalar(
69            "INSERT INTO users (email, display_name) VALUES ($1, $2)
70             ON CONFLICT (lower(email)) DO UPDATE SET active = true
71             RETURNING id",
72        )
73        .bind(&seed.email)
74        .bind(display_name)
75        .fetch_one(&mut *tx)
76        .await
77        .with_context(|| format!("failed to provision the user for {}", seed.email))?;
78
79        // One seeded agent per user, identified by its name: re-running with a
80        // new token replaces the hash instead of leaving the old one valid.
81        sqlx::query(
82            "INSERT INTO agents (user_id, name, token_hash, revoked_at) VALUES ($1, 'seeded', $2, NULL)
83             ON CONFLICT (token_hash) DO NOTHING",
84        )
85        .bind(user_id)
86        .bind(hash_token(&seed.token))
87        .execute(&mut *tx)
88        .await
89        .with_context(|| format!("failed to provision the agent for {}", seed.email))?;
90
91        sqlx::query("UPDATE agents SET revoked_at = now() WHERE user_id = $1 AND name = 'seeded' AND token_hash <> $2 AND revoked_at IS NULL")
92            .bind(user_id)
93            .bind(hash_token(&seed.token))
94            .execute(&mut *tx)
95            .await
96            .with_context(|| format!("failed to revoke the previous token for {}", seed.email))?;
97
98        tx.commit().await?;
99    }
100
101    if !seeds.is_empty() {
102        // Count only: the tokens are secrets and the addresses are personal.
103        tracing::info!(agents = seeds.len(), "provisioned agents from KASL_AGENTS");
104    }
105
106    Ok(())
107}
108
109/// Creates the first administrator, or resets an existing one's password.
110///
111/// The account is upserted rather than refused when it exists: an operator who
112/// locked themselves out has no other way back in, and demanding they first
113/// delete a row by hand in psql helps nobody. Promoting to admin is part of it
114/// for the same reason - the alternative is a server with data in it and no way
115/// to administer it.
116pub async fn ensure_admin(pool: &sqlx::PgPool, email: &str, password: &str) -> Result<()> {
117    let email = email.trim();
118    if email.is_empty() {
119        anyhow::bail!("an administrator needs an email address");
120    }
121    // Not a policy, a floor. Real password rules belong with the account
122    // management UI, where they can be explained to the person typing.
123    if password.chars().count() < 8 {
124        anyhow::bail!("the password must be at least 8 characters");
125    }
126
127    let hash = hash_password(password)?;
128    sqlx::query(
129        "INSERT INTO users (email, display_name, role, password_hash, active)
130         VALUES ($1, $1, 'admin', $2, true)
131         ON CONFLICT (lower(email)) DO UPDATE SET password_hash = EXCLUDED.password_hash, role = 'admin', active = true",
132    )
133    .bind(email)
134    .bind(&hash)
135    .execute(pool)
136    .await
137    .context("failed to create the administrator")?;
138
139    Ok(())
140}
141
142/// Parses `KASL_ADMIN`, which is `email:password`.
143///
144/// Absent or empty yields nothing: a server whose admin already exists has no
145/// reason to carry the password in its environment forever.
146pub fn parse_admin(raw: &str) -> Result<Option<(String, String)>> {
147    let raw = raw.trim();
148    if raw.is_empty() {
149        return Ok(None);
150    }
151    // `split_once`, so a colon inside the password stays in the password.
152    let (email, password) = raw.split_once(':').context("KASL_ADMIN is not `email:password`")?;
153    if password.is_empty() {
154        anyhow::bail!("KASL_ADMIN carries no password");
155    }
156    Ok(Some((email.trim().to_string(), password.to_string())))
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn parses_several_entries() {
165        let seeds = parse_seeds("alice@example.test:token-a, bob@example.test:token-b").unwrap();
166        assert_eq!(
167            seeds,
168            vec![
169                AgentSeed {
170                    email: "alice@example.test".into(),
171                    token: "token-a".into()
172                },
173                AgentSeed {
174                    email: "bob@example.test".into(),
175                    token: "token-b".into()
176                },
177            ]
178        );
179    }
180
181    #[test]
182    fn an_absent_variable_provisions_nothing() {
183        assert!(parse_seeds("").unwrap().is_empty());
184        assert!(parse_seeds("  ,  ").unwrap().is_empty());
185    }
186
187    #[test]
188    fn a_colon_inside_the_token_survives() {
189        let seeds = parse_seeds("alice@example.test:ab:cd").unwrap();
190        assert_eq!(seeds[0].token, "ab:cd", "only the first colon separates");
191    }
192
193    #[test]
194    fn malformed_entries_name_themselves() {
195        let error = parse_seeds("alice@example.test").unwrap_err().to_string();
196        assert!(error.contains("alice@example.test"), "the message should quote the entry: {error}");
197
198        assert!(parse_seeds("alice@example.test:").is_err(), "an empty token is not usable");
199        assert!(parse_seeds(":token").is_err(), "an agent with no user has nobody to report for");
200    }
201}