1use anyhow::{Context, Result};
19use sqlx::PgPool;
20
21use crate::auth::hash_token;
22
23#[derive(Debug, PartialEq, Eq)]
25pub struct AgentSeed {
26 pub email: String,
27 pub token: String,
28}
29
30pub 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 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
56pub async fn apply_seeds(pool: &PgPool, seeds: &[AgentSeed]) -> Result<()> {
61 for seed in seeds {
62 let mut tx = pool.begin().await?;
63
64 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 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 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}