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;
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#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn parses_several_entries() {
115        let seeds = parse_seeds("alice@example.test:token-a, bob@example.test:token-b").unwrap();
116        assert_eq!(
117            seeds,
118            vec![
119                AgentSeed {
120                    email: "alice@example.test".into(),
121                    token: "token-a".into()
122                },
123                AgentSeed {
124                    email: "bob@example.test".into(),
125                    token: "token-b".into()
126                },
127            ]
128        );
129    }
130
131    #[test]
132    fn an_absent_variable_provisions_nothing() {
133        assert!(parse_seeds("").unwrap().is_empty());
134        assert!(parse_seeds("  ,  ").unwrap().is_empty());
135    }
136
137    #[test]
138    fn a_colon_inside_the_token_survives() {
139        let seeds = parse_seeds("alice@example.test:ab:cd").unwrap();
140        assert_eq!(seeds[0].token, "ab:cd", "only the first colon separates");
141    }
142
143    #[test]
144    fn malformed_entries_name_themselves() {
145        let error = parse_seeds("alice@example.test").unwrap_err().to_string();
146        assert!(error.contains("alice@example.test"), "the message should quote the entry: {error}");
147
148        assert!(parse_seeds("alice@example.test:").is_err(), "an empty token is not usable");
149        assert!(parse_seeds(":token").is_err(), "an agent with no user has nobody to report for");
150    }
151}