systemprompt-api 0.4.1

Axum-based HTTP server and API gateway for systemprompt.io AI governance infrastructure. Exposes governed agents, MCP, A2A, and admin endpoints with rate limiting and RBAC.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use async_trait::async_trait;
use axum::body::Body;
use axum::extract::Request;
use axum::http::HeaderMap;
use std::sync::Arc;

use crate::services::middleware::context::ContextExtractor;
use systemprompt_database::DbPool;
use systemprompt_identifiers::{
    AgentName, ContextId, SessionId, SessionSource, TaskId, TraceId, UserId,
};
use systemprompt_models::execution::context::{ContextExtractionError, RequestContext};
use systemprompt_security::{HeaderExtractor, TokenExtractor};
use systemprompt_traits::{AnalyticsProvider, CreateSessionInput};
use systemprompt_users::UserService;

use super::token::{JwtExtractor, JwtUserContext};

struct BuildContextParams {
    jwt_context: JwtUserContext,
    session_id: SessionId,
    user_id: UserId,
    trace_id: TraceId,
    context_id: ContextId,
    agent_name: AgentName,
    task_id: Option<TaskId>,
    auth_token: Option<String>,
}

#[derive(Clone)]
pub struct JwtContextExtractor {
    jwt_extractor: Arc<JwtExtractor>,
    token_extractor: TokenExtractor,
    db_pool: DbPool,
    analytics_provider: Option<Arc<dyn AnalyticsProvider>>,
}

impl std::fmt::Debug for JwtContextExtractor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JwtContextExtractor")
            .field("jwt_extractor", &self.jwt_extractor)
            .field("token_extractor", &self.token_extractor)
            .field("db_pool", &"DbPool")
            .field("analytics_provider", &self.analytics_provider.is_some())
            .finish()
    }
}

impl JwtContextExtractor {
    pub fn new(jwt_secret: &str, db_pool: &DbPool) -> Self {
        Self {
            jwt_extractor: Arc::new(JwtExtractor::new(jwt_secret)),
            token_extractor: TokenExtractor::browser_only(),
            db_pool: Arc::clone(db_pool),
            analytics_provider: None,
        }
    }

    pub fn with_analytics_provider(mut self, provider: Arc<dyn AnalyticsProvider>) -> Self {
        self.analytics_provider = Some(provider);
        self
    }

    fn extract_jwt_context(
        &self,
        headers: &HeaderMap,
    ) -> Result<JwtUserContext, ContextExtractionError> {
        let token = self
            .token_extractor
            .extract(headers)
            .map_err(|_| ContextExtractionError::MissingAuthHeader)?;
        self.jwt_extractor
            .extract_user_context(&token)
            .map_err(|e| ContextExtractionError::InvalidToken(e.to_string()))
    }

    async fn validate_user_exists(
        &self,
        jwt_context: &JwtUserContext,
        route_context: &str,
    ) -> Result<(), ContextExtractionError> {
        let user_service = UserService::new(&self.db_pool).map_err(|e| {
            ContextExtractionError::DatabaseError(format!("Failed to create user service: {e}"))
        })?;
        let user_exists = user_service
            .find_by_id(&jwt_context.user_id)
            .await
            .map_err(|e| {
                ContextExtractionError::DatabaseError(format!(
                    "Failed to check user existence: {e}"
                ))
            })?;

        if user_exists.is_none() {
            tracing::info!(
                session_id = %jwt_context.session_id.as_str(),
                user_id = %jwt_context.user_id.as_str(),
                route = %route_context,
                "JWT validation failed: User no longer exists in database"
            );

            return Err(ContextExtractionError::UserNotFound(format!(
                "User {} no longer exists",
                jwt_context.user_id.as_str()
            )));
        }
        Ok(())
    }

    async fn validate_session_exists(
        &self,
        jwt_context: &JwtUserContext,
        headers: &HeaderMap,
        route_context: &str,
    ) -> Result<(), ContextExtractionError> {
        let Some(analytics_provider) = &self.analytics_provider else {
            return Ok(());
        };

        let session_exists = analytics_provider
            .find_session_by_id(&jwt_context.session_id)
            .await
            .map_err(|e| {
                ContextExtractionError::DatabaseError(format!("Failed to check session: {e}"))
            })?
            .is_some();

        if session_exists {
            return Ok(());
        }

        tracing::info!(
            session_id = %jwt_context.session_id.as_str(),
            user_id = %jwt_context.user_id.as_str(),
            route = %route_context,
            "Creating missing session for legacy token"
        );

        let config = systemprompt_models::Config::get().map_err(|e| {
            ContextExtractionError::DatabaseError(format!("Failed to get config: {e}"))
        })?;
        let expires_at =
            chrono::Utc::now() + chrono::Duration::seconds(config.jwt_access_token_expiration);
        let analytics = analytics_provider.extract_analytics(headers, None);
        let session_source = jwt_context
            .client_id
            .as_ref()
            .map_or(SessionSource::Api, |c| {
                SessionSource::from_client_id(c.as_str())
            });

        analytics_provider
            .create_session(CreateSessionInput {
                session_id: &jwt_context.session_id,
                user_id: Some(&jwt_context.user_id),
                analytics: &analytics,
                session_source,
                is_bot: false,
                expires_at,
            })
            .await
            .map_err(|e| {
                ContextExtractionError::DatabaseError(format!("Failed to create session: {e}"))
            })?;

        Ok(())
    }

    fn extract_common_headers(
        &self,
        headers: &HeaderMap,
    ) -> (TraceId, Option<TaskId>, Option<String>, AgentName) {
        (
            HeaderExtractor::extract_trace_id(headers),
            HeaderExtractor::extract_task_id(headers),
            self.token_extractor.extract(headers).ok(),
            HeaderExtractor::extract_agent_name(headers),
        )
    }

    fn build_context(params: BuildContextParams) -> RequestContext {
        let BuildContextParams {
            jwt_context,
            session_id,
            user_id,
            trace_id,
            context_id,
            agent_name,
            task_id,
            auth_token,
        } = params;
        let mut ctx = RequestContext::new(session_id, trace_id, context_id, agent_name)
            .with_user_id(user_id)
            .with_user_type(jwt_context.user_type);

        if let Some(client_id) = jwt_context.client_id {
            ctx = ctx.with_client_id(client_id);
        }
        if let Some(t_id) = task_id {
            ctx = ctx.with_task_id(t_id);
        }
        if let Some(token) = auth_token {
            ctx = ctx.with_auth_token(token);
        }
        ctx
    }

    pub async fn extract_standard(
        &self,
        headers: &HeaderMap,
    ) -> Result<RequestContext, ContextExtractionError> {
        let has_auth = headers.get("authorization").is_some();
        let has_context_headers =
            headers.get("x-user-id").is_some() && headers.get("x-session-id").is_some();

        if has_context_headers && !has_auth {
            return Err(ContextExtractionError::ForbiddenHeader {
                header: "X-User-ID/X-Session-ID".to_string(),
                reason: "Context headers require valid JWT for authentication".to_string(),
            });
        }

        let jwt_context = self.extract_jwt_context(headers)?;

        if jwt_context.session_id.as_str().is_empty() {
            return Err(ContextExtractionError::MissingSessionId);
        }
        if jwt_context.user_id.as_str().is_empty() {
            return Err(ContextExtractionError::MissingUserId);
        }

        self.validate_user_exists(&jwt_context, "").await?;
        self.validate_session_exists(&jwt_context, headers, "")
            .await?;

        let session_id = headers
            .get("x-session-id")
            .and_then(|h| h.to_str().ok())
            .map_or_else(
                || jwt_context.session_id.clone(),
                |s| SessionId::new(s.to_string()),
            );

        let user_id = headers
            .get("x-user-id")
            .and_then(|h| h.to_str().ok())
            .map_or_else(
                || jwt_context.user_id.clone(),
                |s| UserId::new(s.to_string()),
            );

        let context_id = headers
            .get("x-context-id")
            .and_then(|h| h.to_str().ok())
            .map_or_else(
                || ContextId::new(String::new()),
                |s| ContextId::new(s.to_string()),
            );

        let (trace_id, task_id, auth_token, agent_name) = self.extract_common_headers(headers);

        Ok(Self::build_context(BuildContextParams {
            jwt_context,
            session_id,
            user_id,
            trace_id,
            context_id,
            agent_name,
            task_id,
            auth_token,
        }))
    }

    pub async fn extract_mcp_a2a(
        &self,
        headers: &HeaderMap,
    ) -> Result<RequestContext, ContextExtractionError> {
        self.extract_standard(headers).await
    }

    pub async fn extract_for_gateway(
        &self,
        jwt_token: &systemprompt_identifiers::JwtToken,
    ) -> Result<RequestContext, ContextExtractionError> {
        let jwt_context = self
            .jwt_extractor
            .extract_user_context(jwt_token.as_str())
            .map_err(|e| ContextExtractionError::InvalidToken(e.to_string()))?;

        if jwt_context.session_id.as_str().is_empty() {
            return Err(ContextExtractionError::MissingSessionId);
        }
        if jwt_context.user_id.as_str().is_empty() {
            return Err(ContextExtractionError::MissingUserId);
        }

        self.validate_user_exists(&jwt_context, "gateway").await?;

        let session_id = jwt_context.session_id.clone();
        let user_id = jwt_context.user_id.clone();

        Ok(Self::build_context(BuildContextParams {
            jwt_context,
            session_id,
            user_id,
            trace_id: TraceId::generate(),
            context_id: ContextId::new(String::new()),
            agent_name: AgentName::system(),
            task_id: None,
            auth_token: Some(jwt_token.as_str().to_string()),
        }))
    }

    async fn extract_from_request_impl(
        &self,
        request: Request<Body>,
    ) -> Result<(RequestContext, Request<Body>), ContextExtractionError> {
        use crate::services::middleware::context::sources::{
            ContextIdSource, PayloadSource, TASK_BASED_CONTEXT_MARKER,
        };

        let headers = request.headers().clone();
        let has_auth = headers.get("authorization").is_some();

        if headers.get("x-context-id").is_some() && !has_auth {
            return Err(ContextExtractionError::ForbiddenHeader {
                header: "X-Context-ID".to_string(),
                reason: "Context ID must be in request body (A2A spec). Use contextId field in \
                         message."
                    .to_string(),
            });
        }

        let jwt_context = self.extract_jwt_context(&headers)?;

        if jwt_context.session_id.as_str().is_empty() {
            return Err(ContextExtractionError::MissingSessionId);
        }
        if jwt_context.user_id.as_str().is_empty() {
            return Err(ContextExtractionError::MissingUserId);
        }

        self.validate_user_exists(&jwt_context, " (A2A route)")
            .await?;
        self.validate_session_exists(&jwt_context, &headers, " (A2A route)")
            .await?;

        let (body_bytes, reconstructed_request) =
            PayloadSource::read_and_reconstruct(request).await?;

        let context_source = PayloadSource::extract_context_source(&body_bytes)?;
        let (context_id, task_id_from_payload) = match context_source {
            ContextIdSource::Direct(id) => (ContextId::new(id), None),
            ContextIdSource::FromTask { task_id } => (
                ContextId::new(TASK_BASED_CONTEXT_MARKER),
                Some(TaskId::new(task_id)),
            ),
        };

        let (trace_id, task_id_from_header, auth_token, agent_name) =
            self.extract_common_headers(&headers);

        let task_id = task_id_from_payload.or(task_id_from_header);

        let session_id = jwt_context.session_id.clone();
        let user_id = jwt_context.user_id.clone();
        let ctx = Self::build_context(BuildContextParams {
            jwt_context,
            session_id,
            user_id,
            trace_id,
            context_id,
            agent_name,
            task_id,
            auth_token,
        });

        Ok((ctx, reconstructed_request))
    }
}

#[async_trait]
impl ContextExtractor for JwtContextExtractor {
    async fn extract_from_headers(
        &self,
        headers: &HeaderMap,
    ) -> Result<RequestContext, ContextExtractionError> {
        self.extract_standard(headers).await
    }

    async fn extract_from_request(
        &self,
        request: Request<Body>,
    ) -> Result<(RequestContext, Request<Body>), ContextExtractionError> {
        self.extract_from_request_impl(request).await
    }

    async fn extract_user_only(
        &self,
        headers: &HeaderMap,
    ) -> Result<RequestContext, ContextExtractionError> {
        self.extract_standard(headers).await
    }
}