Skip to main content

systemprompt_cli/session/creation/
helpers.rs

1//! Helpers minting CLI session rows and their analytics context.
2//!
3//! A local install's admin is resolved by **name**, never by email. An email is
4//! an attribute of a person, not a key: the local-trial path used to look up
5//! the literal `admin@localhost.dev`, which forced a migration to write that
6//! same string into `users.email` so the two would meet, and the address was
7//! then displayed as the operator's identity — including on the bridge
8//! device-link consent screen, immediately above a button that mints a durable
9//! personal access token. `system_admin.username` is the key the runtime
10//! already resolves on, so resolving by it agrees with the runtime by
11//! construction and leaves `email` free to hold something true. That path
12//! deliberately does not provision: on a local install a missing admin means
13//! bootstrap has not run, and inventing one is what produced the fabricated
14//! identity in the first place. Every address returned by
15//! `resolve_credentialed_user_email` comes from a session hint or from cloud
16//! credentials — real data either way.
17//!
18//! Copyright (c) systemprompt.io — Business Source License 1.1.
19//! See <https://systemprompt.io> for licensing details.
20
21use std::sync::Arc;
22
23use anyhow::{Context, Result};
24use chrono::Duration as ChronoDuration;
25use systemprompt_agent::repository::context::ContextRepository;
26use systemprompt_cloud::{
27    CliSession, CloudCredentials, CredentialsBootstrap, SessionBinding, SessionIdentity, SessionKey,
28};
29use systemprompt_config::SecretsBootstrap;
30use systemprompt_database::{Database, DbPool, PoolConfig};
31use systemprompt_identifiers::{ContextId, Email, ProfileName, SessionId, SessionToken};
32use systemprompt_models::auth::{Permission, RateLimitTier, UserType};
33use systemprompt_security::{SessionGenerator, SessionParams};
34use systemprompt_users::{UserRepository, UserService};
35
36use crate::session::resolution::ProfileContext;
37
38pub(super) struct ResolvedSecrets {
39    pub database_url: String,
40    pub database_write_url: Option<String>,
41}
42
43pub(super) fn load_secrets() -> Result<ResolvedSecrets> {
44    let secrets = SecretsBootstrap::get().map_err(|e| {
45        anyhow::anyhow!(
46            "Secrets not initialized: {}\n\nEnsure your profile has a valid secrets \
47             configuration.\nCheck that secrets.json exists or environment variables are set.",
48            e
49        )
50    })?;
51
52    Ok(ResolvedSecrets {
53        database_url: secrets.database_url.clone(),
54        database_write_url: secrets.database_write_url.clone(),
55    })
56}
57
58pub(super) async fn connect_database(secrets: &ResolvedSecrets) -> Result<DbPool> {
59    let db = Database::from_config_with_write(
60        "postgres",
61        &secrets.database_url,
62        secrets.database_write_url.as_deref(),
63        &PoolConfig::default(),
64    )
65    .await
66    .context("Failed to connect to database")?;
67    Ok(DbPool::from(Arc::new(db)))
68}
69
70pub async fn get_or_create_admin(
71    db_pool: &DbPool,
72    email: &str,
73    context_type: &str,
74) -> Result<systemprompt_users::User> {
75    let user_service = UserService::new(Arc::new(UserRepository::new(db_pool)?));
76
77    if let Some(user) = user_service
78        .find_by_email(email)
79        .await
80        .context("Failed to query user by email")?
81    {
82        if user.is_admin() {
83            return Ok(user);
84        }
85
86        tracing::info!(email = %email, context = %context_type, "Promoting existing user to admin");
87
88        return user_service
89            .assign_roles(&user.id, &["admin".to_owned()])
90            .await
91            .context("Failed to assign admin role to existing user");
92    }
93
94    let name = email.split('@').next().unwrap_or("admin").to_owned();
95
96    tracing::info!(email = %email, name = %name, context = %context_type, "Auto-provisioning user");
97
98    let user = match user_service
99        .create_if_absent(&name, email, None, None)
100        .await
101        .with_context(|| format!("Failed to create user in {context_type} database"))?
102    {
103        Some(user) => user,
104        None => user_service
105            .find_by_email(email)
106            .await
107            .context("Failed to query user by email")?
108            .with_context(|| format!("User {email} vanished between provisioning and lookup"))?,
109    };
110
111    user_service
112        .assign_roles(&user.id, &["admin".to_owned()])
113        .await
114        .context("Failed to assign admin role to new user")
115}
116
117pub fn generate_admin_token(
118    issuer: &str,
119    user: &systemprompt_users::User,
120    session_id: &SessionId,
121) -> Result<SessionToken> {
122    let generator = SessionGenerator::new(issuer);
123    generator
124        .generate(&SessionParams {
125            user_id: &user.id,
126            session_id,
127            email: &user.email,
128            duration: ChronoDuration::hours(crate::session::api::DEFAULT_CLI_SESSION_HOURS),
129            user_type: UserType::Admin,
130            permissions: vec![Permission::Admin],
131            roles: vec!["admin".to_owned()],
132            attributes: std::collections::BTreeMap::new(),
133            rate_limit_tier: RateLimitTier::Admin,
134        })
135        .context("Failed to generate session token")
136}
137
138pub async fn create_cli_context(
139    db_pool: DbPool,
140    user: &systemprompt_users::User,
141    session_id: &SessionId,
142    profile_name: &str,
143) -> Result<ContextId> {
144    let context_repo = ContextRepository::new(&db_pool)?;
145    context_repo
146        .get_or_create_cli_context(
147            &user.id,
148            session_id,
149            &format!("CLI Session - {}", profile_name),
150        )
151        .await
152        .context("Failed to create CLI context")
153}
154
155pub(super) struct SessionComponents {
156    pub session_token: SessionToken,
157    pub session_id: SessionId,
158    pub context_id: ContextId,
159}
160
161pub(super) fn build_cli_session(
162    profile_ctx: &ProfileContext<'_>,
163    session_key: &SessionKey,
164    components: SessionComponents,
165    admin_user: &systemprompt_users::User,
166    issuer: &str,
167) -> Result<CliSession> {
168    let profile_name = ProfileName::try_new(profile_ctx.name)
169        .map_err(|e| anyhow::anyhow!("Invalid profile name: {}", e))?;
170    let email =
171        Email::try_new(&admin_user.email).map_err(|e| anyhow::anyhow!("Invalid email: {}", e))?;
172
173    Ok(CliSession::builder(
174        SessionBinding::new(profile_name, issuer.to_owned()),
175        components.session_token,
176        components.session_id,
177        components.context_id,
178        SessionIdentity::new(admin_user.id.clone(), email, UserType::Admin),
179    )
180    .with_session_key(session_key)
181    .with_profile_path(profile_ctx.path.clone())
182    .build())
183}
184
185pub async fn resolve_local_admin(
186    db_pool: &DbPool,
187    admin_name: &str,
188) -> Result<systemprompt_users::User> {
189    let user_service = UserService::new(Arc::new(UserRepository::new(db_pool)?));
190
191    let user = user_service
192        .find_by_name(admin_name)
193        .await
194        .context("Failed to query the local admin user by name")?
195        .with_context(|| {
196            format!(
197                "Local admin user '{admin_name}' not found.\n\nRun 'systemprompt admin bootstrap \
198                 --email <your email>' to create it with a real address."
199            )
200        })?;
201
202    if !user.is_active() {
203        anyhow::bail!("Local admin user '{admin_name}' exists but is not active.");
204    }
205    if !user.is_admin() {
206        anyhow::bail!(
207            "User '{admin_name}' exists but does not hold the admin role. Run 'systemprompt admin \
208             bootstrap' to repair it."
209        );
210    }
211
212    Ok(user)
213}
214
215pub(super) async fn resolve_credentialed_user_email(
216    session_email_hint: Option<&str>,
217) -> Result<Email> {
218    if let Some(email) = session_email_hint {
219        return Email::try_new(email).context("session email hint is not a valid email address");
220    }
221
222    CredentialsBootstrap::try_init()
223        .await
224        .context("Failed to initialize credentials. Run 'systemprompt cloud auth login'.")?;
225
226    let creds = CredentialsBootstrap::require().map_err(|_e| {
227        anyhow::anyhow!(
228            "Cloud authentication required for new sessions.\n\nRun 'systemprompt cloud auth \
229             login' to authenticate."
230        )
231    })?;
232    Ok(creds.user_email.clone())
233}
234
235pub(super) async fn resolve_admin_with_fallback(
236    db_pool: &DbPool,
237    user_email: &str,
238    session_email_hint: Option<&str>,
239    context_type: &str,
240) -> Result<systemprompt_users::User> {
241    match get_or_create_admin(db_pool, user_email, context_type).await {
242        Ok(user) => Ok(user),
243        Err(e) if session_email_hint.is_some() => {
244            tracing::warn!(
245                email = %user_email,
246                error = %e,
247                "Session user lookup failed, falling back to cloud credentials"
248            );
249            if let Err(init_err) = CredentialsBootstrap::try_init().await {
250                tracing::debug!(error = %init_err, "Credentials init failed during fallback");
251            }
252            if let Ok(creds) = CredentialsBootstrap::require()
253                && creds.user_email.as_str() != user_email
254            {
255                return get_or_create_admin(db_pool, creds.user_email.as_str(), context_type).await;
256            }
257            Err(e)
258        },
259        Err(e) => Err(e),
260    }
261}
262
263pub async fn resolve_tenant_admin_with_fallback(
264    db_pool: &DbPool,
265    creds: &CloudCredentials,
266    user_email: &str,
267    session_email_hint: Option<&str>,
268) -> Result<systemprompt_users::User> {
269    match get_or_create_admin(db_pool, user_email, "tenant").await {
270        Ok(user) => Ok(user),
271        Err(e) if session_email_hint.is_some() && creds.user_email.as_str() != user_email => {
272            tracing::warn!(
273                email = %user_email,
274                error = %e,
275                "Session user lookup failed, falling back to cloud credentials"
276            );
277            get_or_create_admin(db_pool, creds.user_email.as_str(), "tenant").await
278        },
279        Err(e) => Err(e),
280    }
281}