Skip to main content

teamcraft/
lib.rs

1//! TeamCraft – an open-source product lifecycle management (PLM) system.
2//!
3//! The crate is organised in layers:
4//!
5//! * [`domain`] – pure rules (roles, lifecycle, numbering, validation)
6//! * [`services`] – business logic on top of PostgreSQL, used by both front ends
7//! * [`web`] – server-rendered HTML user interface (cookie sessions)
8//! * [`api`] – JSON REST API under `/api/v1` (bearer tokens)
9//! * [`mcp`] – Model Context Protocol server at `/api/v1/mcp` for AI assistants
10//! * [`assistant`] – built-in assistant (Claude via the Anthropic API) using the MCP tools
11
12// The `json!` endpoint index in `api::index` (`GET /api/v1`) outgrew the
13// default limit of 128.
14#![recursion_limit = "256"]
15
16pub mod api;
17pub mod assets;
18pub mod assistant;
19pub mod auth;
20pub mod backup;
21pub mod backupcrypt;
22pub mod bomtable;
23pub mod cadformat;
24pub mod cadrefs;
25pub mod catprod;
26pub mod config;
27pub mod db;
28pub mod delivery;
29pub mod domain;
30pub mod error;
31pub mod fusion;
32#[doc(hidden)]
33pub mod fuzz_harness;
34pub mod htmltext;
35pub mod httprange;
36pub mod invasm;
37pub mod invpart;
38pub mod invplace;
39pub mod llm;
40pub mod localserver;
41pub mod malware;
42pub mod massprops;
43pub mod mattermost;
44pub mod mcp;
45pub mod mesh;
46pub mod metrics;
47pub mod models;
48pub mod notify;
49pub mod nxasm;
50pub mod nxpart;
51pub mod oidc;
52pub mod pagecontext;
53pub mod pdftext;
54pub mod preview;
55pub mod resultscan;
56pub mod services;
57pub mod shape;
58pub mod simmesh;
59pub mod solversummary;
60pub mod stepbom;
61pub mod swpart;
62pub mod templates;
63pub mod textindex;
64pub mod thumbnail;
65pub mod util;
66pub mod vault;
67pub mod web;
68pub mod webhooks;
69
70use std::{any::Any, sync::Arc};
71
72use anyhow::Context;
73use axum::{
74    extract::State,
75    http::{header, HeaderName, HeaderValue, StatusCode},
76    response::{IntoResponse, Response},
77    routing::get,
78    Json, Router,
79};
80use serde_json::json;
81use sqlx::PgPool;
82use tower_http::{
83    catch_panic::CatchPanicLayer,
84    set_header::SetResponseHeaderLayer,
85    trace::{DefaultOnResponse, TraceLayer},
86};
87use tracing::Level;
88
89use crate::{config::Config, oidc::OidcClient, preview::Previews, vault::Vault};
90
91/// Shared state of the HTTP server.
92#[derive(Clone)]
93pub struct AppState {
94    pub db: PgPool,
95    pub config: Arc<Config>,
96    pub templates: Arc<minijinja::Environment<'static>>,
97    pub vault: Vault,
98    pub oidc: Option<Arc<OidcClient>>,
99    /// Cached 3D preview meshes (see `preview`).
100    pub previews: Arc<Previews>,
101    /// The built-in assistant; `None` without `TEAMCRAFT_ANTHROPIC_API_KEY`.
102    pub assistant: Option<Arc<assistant::Assistant>>,
103    /// Sends outgoing event webhooks ("Send test", "Retry"; the background
104    /// task has its own).
105    pub webhooks: webhooks::Dispatcher,
106    /// Failed password sign-ins per username and client address.
107    pub sign_in: Arc<auth::SignInThrottle>,
108    /// Request counters for `GET /metrics`.
109    pub metrics: Arc<metrics::Metrics>,
110    /// One-time code of the first-start setup, new at every start (see
111    /// `auth::setup_code`); logged with the setup link.
112    pub setup_code: Arc<str>,
113}
114
115impl AppState {
116    pub async fn new(config: Config, db: PgPool) -> anyhow::Result<AppState> {
117        let vault = Vault::open(&config.vault_dir)
118            .await
119            .with_context(|| {
120                format!(
121                    "cannot open the file vault at {}",
122                    config.vault_dir.display()
123                )
124            })?
125            .with_scanner(config.clamd.clone());
126        let mut templates =
127            templates::environment(&config.instance_name).context("loading templates failed")?;
128        if let Some(a) = &config.assistant {
129            // privacy wording of the assistant panels: where the data goes
130            templates.add_global(
131                "assistant_destination",
132                format!(
133                    "the AI provider configured by your administrator ({}, {})",
134                    a.provider.as_str(),
135                    a.host()
136                ),
137            );
138        }
139        let oidc = match &config.oidc {
140            Some(o) => Some(Arc::new(OidcClient::new(o.clone(), &config.public_url)?)),
141            None => None,
142        };
143        let previews = Arc::new(Previews::new(&vault, config.preview));
144        crate::pdftext::configure(config.preview.max_memory_bytes);
145        let assistant = match &config.assistant {
146            Some(a) => Some(Arc::new({
147                if let Some(warning) = a.insecure_key_warning() {
148                    tracing::warn!("{warning}");
149                }
150                assistant::Assistant::new(a).context("setting up the assistant failed")?
151            })),
152            None => None,
153        };
154        let webhooks = webhooks::Dispatcher::from_config(&config)
155            .context("setting up the webhook delivery failed")?;
156        let sign_in = Arc::new(auth::SignInThrottle::new(
157            config.signin_max_failures,
158            auth::SIGN_IN_WINDOW,
159        ));
160        Ok(AppState {
161            db,
162            sign_in,
163            metrics: Arc::default(),
164            setup_code: auth::setup_code().into(),
165            config: Arc::new(config),
166            templates: Arc::new(templates),
167            vault,
168            oidc,
169            previews,
170            assistant,
171            webhooks,
172        })
173    }
174}
175
176/// Content-Security-Policy of every response that does not set its own
177/// (the desktop sign-in page derives its policy from it).
178pub const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; img-src 'self' data:; \
179     style-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'; \
180     base-uri 'self'; form-action 'self'";
181
182/// Builds the complete HTTP application.
183pub fn router(state: AppState) -> Router {
184    let hsts = state.config.cookie_secure;
185    let app = Router::new()
186        .route("/healthz", get(healthz))
187        .route("/readyz", get(readyz))
188        .route("/metrics", get(metrics_endpoint))
189        // the identity provider posts here; outside the web pages' cross-site
190        // guard, the signed logout token is the credential (issue #173)
191        .route(
192            "/auth/oidc/backchannel-logout",
193            axum::routing::post(web::oidc_backchannel_logout),
194        )
195        .nest("/api/v1", api::router(&state))
196        .merge(web::router(&state))
197        .layer(SetResponseHeaderLayer::if_not_present(
198            header::X_CONTENT_TYPE_OPTIONS,
199            HeaderValue::from_static("nosniff"),
200        ))
201        .layer(SetResponseHeaderLayer::if_not_present(
202            header::X_FRAME_OPTIONS,
203            HeaderValue::from_static("DENY"),
204        ))
205        .layer(SetResponseHeaderLayer::if_not_present(
206            header::REFERRER_POLICY,
207            HeaderValue::from_static("same-origin"),
208        ))
209        .layer(SetResponseHeaderLayer::if_not_present(
210            header::CONTENT_SECURITY_POLICY,
211            HeaderValue::from_static(CONTENT_SECURITY_POLICY),
212        ))
213        .layer(SetResponseHeaderLayer::if_not_present(
214            HeaderName::from_static("permissions-policy"),
215            HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
216        ))
217        .layer(tower::util::option_layer(hsts.then(|| {
218            SetResponseHeaderLayer::if_not_present(
219                header::STRICT_TRANSPORT_SECURITY,
220                HeaderValue::from_static("max-age=31536000"),
221            )
222        })));
223    guarded(app, state.metrics.clone())
224        .layer(
225            // One INFO line per request. Only the path is recorded: query
226            // strings can carry one-time OIDC codes and search terms.
227            TraceLayer::new_for_http()
228                .make_span_with(|req: &axum::http::Request<axum::body::Body>| {
229                    tracing::info_span!("http", method = %req.method(), path = %req.uri().path())
230                })
231                .on_request(())
232                .on_response(DefaultOnResponse::new().level(Level::INFO)),
233        )
234        .with_state(state)
235}
236
237/// Liveness probe: the process is up and serving HTTP.
238async fn healthz() -> &'static str {
239    "ok"
240}
241
242/// Readiness probe: database reachable and vault writable.
243async fn readyz(State(state): State<AppState>) -> Response {
244    let db = sqlx::query_scalar::<_, i32>("SELECT 1")
245        .fetch_one(&state.db)
246        .await;
247    let vault = state.vault.check_writable().await;
248    let ok = db.is_ok() && vault.is_ok();
249    let body = json!({
250        "status": if ok { "ok" } else { "unavailable" },
251        "database": if db.is_ok() { "ok" } else { "error" },
252        "vault": if vault.is_ok() { "ok" } else { "error" },
253        "version": env!("CARGO_PKG_VERSION"),
254    });
255    let status = if ok {
256        StatusCode::OK
257    } else {
258        StatusCode::SERVICE_UNAVAILABLE
259    };
260    (status, Json(body)).into_response()
261}
262
263fn panic_response(err: Box<dyn Any + Send + 'static>) -> Response {
264    let detail = if let Some(s) = err.downcast_ref::<String>() {
265        s.clone()
266    } else if let Some(s) = err.downcast_ref::<&str>() {
267        s.to_string()
268    } else {
269        "unknown panic".to_string()
270    };
271    tracing::error!(panic = %detail, "request handler panicked");
272    notify::report_error(&format!("panic: {detail}"));
273    (
274        StatusCode::INTERNAL_SERVER_ERROR,
275        Json(json!({ "error": { "code": "internal", "message": "Internal server error." } })),
276    )
277        .into_response()
278}
279
280/// Prometheus metrics: 404 unless `TEAMCRAFT_METRICS_TOKEN` is set, 401
281/// without that token as bearer token (see `metrics`).
282async fn metrics_endpoint(
283    State(state): State<AppState>,
284    headers: axum::http::HeaderMap,
285) -> Response {
286    let Some(expected) = state.config.metrics_token.as_deref() else {
287        return StatusCode::NOT_FOUND.into_response();
288    };
289    let given = headers
290        .get(header::AUTHORIZATION)
291        .and_then(|v| v.to_str().ok());
292    if !metrics::token_matches(given, expected) {
293        return (
294            StatusCode::UNAUTHORIZED,
295            [
296                (header::WWW_AUTHENTICATE, "Bearer"),
297                (header::CACHE_CONTROL, "no-store"),
298            ],
299            "metrics token required\n",
300        )
301            .into_response();
302    }
303    let count = |gauge: &'static str, sql: &'static str| {
304        let pool = state.db.clone();
305        async move {
306            match sqlx::query_scalar::<_, i64>(sql).fetch_one(&pool).await {
307                Ok(n) => n as f64,
308                Err(e) => {
309                    // the gauge shows NaN; the log says why
310                    tracing::warn!(gauge, error = %e, "metrics: counting the backlog failed");
311                    f64::NAN
312                }
313            }
314        }
315    };
316    let (webhooks, mail, chat) = tokio::join!(
317        count(
318            "teamcraft_webhook_deliveries_pending",
319            "SELECT COUNT(*) FROM webhook_deliveries WHERE status = 'pending'"
320        ),
321        count(
322            "teamcraft_notification_emails_pending",
323            "SELECT COUNT(*) FROM notifications WHERE email_state = 'pending'"
324        ),
325        count(
326            "teamcraft_notification_chat_pending",
327            "SELECT COUNT(*) FROM notifications WHERE chat_state = 'pending'"
328        ),
329    );
330    let (previews_running, previews_waiting) = state.previews.queue();
331    let gauges = [
332        (
333            "teamcraft_db_pool_connections",
334            "Open database connections.",
335            f64::from(state.db.size()),
336        ),
337        (
338            "teamcraft_db_pool_idle_connections",
339            "Idle database connections.",
340            state.db.num_idle() as f64,
341        ),
342        (
343            "teamcraft_webhook_deliveries_pending",
344            "Webhook deliveries waiting to be sent.",
345            webhooks,
346        ),
347        (
348            "teamcraft_notification_emails_pending",
349            "E-mails waiting to be sent.",
350            mail,
351        ),
352        (
353            "teamcraft_notification_chat_pending",
354            "Chat messages waiting to be sent.",
355            chat,
356        ),
357        (
358            "teamcraft_preview_conversions_running",
359            "3D preview conversions running now (this server).",
360            previews_running as f64,
361        ),
362        (
363            "teamcraft_preview_conversions_waiting",
364            "3D preview conversions waiting for a free slot (this server).",
365            previews_waiting as f64,
366        ),
367    ];
368    (
369        [
370            (
371                header::CONTENT_TYPE,
372                "text/plain; version=0.0.4; charset=utf-8",
373            ),
374            (header::CACHE_CONTROL, "no-store"),
375        ],
376        state.metrics.render(env!("CARGO_PKG_VERSION"), &gauges),
377    )
378        .into_response()
379}
380
381/// Turns a panic into a 500 page and counts every answered request for
382/// `/metrics`. The counter sits outside the panic catcher, so a panicking
383/// handler is counted as `5xx` (see the test below).
384fn guarded<S: Clone + Send + Sync + 'static>(
385    router: Router<S>,
386    metrics: Arc<metrics::Metrics>,
387) -> Router<S> {
388    router.layer(CatchPanicLayer::custom(panic_response)).layer(
389        axum::middleware::from_fn_with_state(metrics, count_requests),
390    )
391}
392
393/// Counts every answered request for `/metrics`. The latency ends when the
394/// response headers are ready; a streamed body (downloads) is not included.
395async fn count_requests(
396    State(metrics): State<Arc<metrics::Metrics>>,
397    request: axum::extract::Request,
398    next: axum::middleware::Next,
399) -> Response {
400    let started = std::time::Instant::now();
401    let response = next.run(request).await;
402    metrics.record(response.status().as_u16(), started.elapsed());
403    response
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use tower::ServiceExt;
410
411    async fn boom() -> &'static str {
412        panic!("handler bug")
413    }
414
415    /// The point of the layer order: a panic is caught inside the counter,
416    /// so it arrives there as a 500 and is counted as `5xx`.
417    #[tokio::test]
418    async fn a_panicking_request_is_counted_as_5xx() {
419        let metrics = Arc::new(metrics::Metrics::default());
420        let app = guarded(
421            Router::new()
422                .route("/boom", get(boom))
423                .route("/ok", get(healthz)),
424            metrics.clone(),
425        );
426        let request = |uri: &str| {
427            axum::http::Request::builder()
428                .uri(uri)
429                .body(axum::body::Body::empty())
430                .unwrap()
431        };
432        let answer = app.clone().oneshot(request("/boom")).await.unwrap();
433        assert_eq!(answer.status(), StatusCode::INTERNAL_SERVER_ERROR);
434        let answer = app.oneshot(request("/ok")).await.unwrap();
435        assert_eq!(answer.status(), StatusCode::OK);
436        let text = metrics.render("t", &[]);
437        assert!(
438            text.contains("teamcraft_http_requests_total{class=\"5xx\"} 1"),
439            "{text}"
440        );
441        assert!(text.contains("teamcraft_http_requests_total{class=\"2xx\"} 1"));
442        assert!(text.contains("teamcraft_http_request_duration_seconds_count 2"));
443    }
444}