src/server.rs 13.0 K raw
1
use askama::Template;
2
use askama_web::WebTemplate;
3
use subtle::ConstantTimeEq;
4
use axum::{
5
    Form, Json, Router,
6
    extract::{Path, Request, State},
7
    http::{HeaderMap, StatusCode, header},
8
    middleware::{self, Next},
9
    response::{Html, IntoResponse, Redirect, Response},
10
    routing::{delete, get, post, put},
11
};
12
use rust_embed::Embed;
13
use serde::Deserialize;
14
use crate::db::{self, Db, Snippet};
15
use crate::highlight::Highlighter;
16
use std::collections::HashSet;
17
use std::sync::Arc;
18
19
#[derive(Embed)]
20
#[folder = "assets/"]
21
struct Assets;
22
23
#[derive(Embed)]
24
#[folder = "static/"]
25
struct Static;
26
27
#[derive(Clone)]
28
struct ServerConfig {
29
    api_key: Option<String>,
30
    auth_endpoints: HashSet<String>,
31
    max_content_size: usize,
32
}
33
34
impl ServerConfig {
35
    fn from_env() -> Self {
36
        let api_key = std::env::var("SIPP_API_KEY").ok();
37
        let auth_endpoints = match std::env::var("SIPP_AUTH_ENDPOINTS") {
38
            Ok(val) if val.trim().eq_ignore_ascii_case("none") => HashSet::new(),
39
            Ok(val) => val.split(',').map(|s| s.trim().to_lowercase()).collect(),
40
            Err(_) => ["api_delete", "api_list", "api_update"].iter().map(|s| s.to_string()).collect(),
41
        };
42
        let max_content_size = std::env::var("SIPP_MAX_CONTENT_SIZE")
43
            .ok()
44
            .and_then(|v| v.parse().ok())
45
            .unwrap_or(512_000);
46
        ServerConfig { api_key, auth_endpoints, max_content_size }
47
    }
48
49
    fn requires_auth(&self, name: &str) -> bool {
50
        self.auth_endpoints.contains("all") || self.auth_endpoints.contains(name)
51
    }
52
}
53
54
#[derive(Clone)]
55
struct AppState {
56
    db: Db,
57
    highlighter: Arc<Highlighter>,
58
    server_config: ServerConfig,
59
}
60
61
#[derive(Template)]
62
#[template(path = "index.html")]
63
struct IndexTemplate;
64
65
#[derive(Template)]
66
#[template(path = "snippet.html")]
67
struct SnippetTemplate {
68
    name: String,
69
    content: String,
70
    highlighted_content: String,
71
}
72
73
#[derive(Deserialize)]
74
struct CreateSnippetForm {
75
    name: String,
76
    content: String,
77
}
78
79
async fn index() -> WebTemplate<IndexTemplate> {
80
    WebTemplate(IndexTemplate)
81
}
82
83
fn is_cli_user_agent(headers: &HeaderMap) -> bool {
84
    headers
85
        .get(header::USER_AGENT)
86
        .and_then(|v| v.to_str().ok())
87
        .map(|ua| {
88
            let ua = ua.to_lowercase();
89
            ua.starts_with("curl/") || ua.starts_with("wget/") || ua.starts_with("httpie/")
90
        })
91
        .unwrap_or(false)
92
}
93
94
async fn view_snippet(
95
    State(state): State<AppState>,
96
    Path(short_id): Path<String>,
97
    headers: HeaderMap,
98
) -> Result<Response, (StatusCode, Html<String>)> {
99
    match db::get_snippet_by_short_id(&state.db, &short_id) {
100
        Ok(Some(snippet)) => {
101
            if is_cli_user_agent(&headers) {
102
                Ok((
103
                    [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
104
                    snippet.content,
105
                )
106
                    .into_response())
107
            } else {
108
                let highlighted_content =
109
                    state.highlighter.highlight(&snippet.name, &snippet.content);
110
                Ok(WebTemplate(SnippetTemplate {
111
                    name: snippet.name,
112
                    content: snippet.content,
113
                    highlighted_content,
114
                })
115
                .into_response())
116
            }
117
        }
118
        Ok(None) => Err((
119
            StatusCode::NOT_FOUND,
120
            Html("<h1>Snippet not found</h1>".to_string()),
121
        )),
122
        Err(_) => Err((
123
            StatusCode::INTERNAL_SERVER_ERROR,
124
            Html("<h1>Internal server error</h1>".to_string()),
125
        )),
126
    }
127
}
128
129
async fn create_snippet(
130
    State(state): State<AppState>,
131
    Form(form): Form<CreateSnippetForm>,
132
) -> Result<Redirect, (StatusCode, Html<String>)> {
133
    if form.content.len() > state.server_config.max_content_size {
134
        return Err((
135
            StatusCode::PAYLOAD_TOO_LARGE,
136
            Html(format!(
137
                "<h1>Content too large</h1><p>Maximum size is {} bytes</p>",
138
                state.server_config.max_content_size
139
            )),
140
        ));
141
    }
142
    match db::create_snippet(&state.db, &form.name, &form.content) {
143
        Ok(snippet) => Ok(Redirect::to(&format!("/s/{}", snippet.short_id))),
144
        Err(_) => Err((
145
            StatusCode::INTERNAL_SERVER_ERROR,
146
            Html("<h1>Internal server error</h1>".to_string()),
147
        )),
148
    }
149
}
150
151
async fn require_api_key(
152
    State(state): State<AppState>,
153
    headers: HeaderMap,
154
    request: Request,
155
    next: Next,
156
) -> Result<Response, (StatusCode, Json<serde_json::Value>)> {
157
    let server_key = match &state.server_config.api_key {
158
        Some(k) => k,
159
        None => return Err((
160
            StatusCode::FORBIDDEN,
161
            Json(serde_json::json!({"error": "No API key configured on server"})),
162
        )),
163
    };
164
    let provided = headers
165
        .get("x-api-key")
166
        .and_then(|v| v.to_str().ok());
167
    match provided {
168
        Some(k) if k.as_bytes().ct_eq(server_key.as_bytes()).into() => Ok(next.run(request).await),
169
        _ => Err((
170
            StatusCode::UNAUTHORIZED,
171
            Json(serde_json::json!({"error": "Invalid or missing API key"})),
172
        )),
173
    }
174
}
175
176
async fn api_list_snippets(
177
    State(state): State<AppState>,
178
) -> Result<Json<Vec<Snippet>>, (StatusCode, Json<serde_json::Value>)> {
179
    match db::get_all_snippets(&state.db) {
180
        Ok(snippets) => Ok(Json(snippets)),
181
        Err(_) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Internal server error"})))),
182
    }
183
}
184
185
async fn api_get_snippet(
186
    State(state): State<AppState>,
187
    Path(short_id): Path<String>,
188
) -> Result<Json<Snippet>, (StatusCode, Json<serde_json::Value>)> {
189
    match db::get_snippet_by_short_id(&state.db, &short_id) {
190
        Ok(Some(snippet)) => Ok(Json(snippet)),
191
        Ok(None) => Err((StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Snippet not found"})))),
192
        Err(_) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Internal server error"})))),
193
    }
194
}
195
196
#[derive(Deserialize)]
197
struct ApiCreateSnippet {
198
    name: String,
199
    content: String,
200
}
201
202
async fn api_create_snippet(
203
    State(state): State<AppState>,
204
    Json(body): Json<ApiCreateSnippet>,
205
) -> Result<(StatusCode, Json<Snippet>), (StatusCode, Json<serde_json::Value>)> {
206
    if body.content.len() > state.server_config.max_content_size {
207
        return Err((
208
            StatusCode::PAYLOAD_TOO_LARGE,
209
            Json(serde_json::json!({
210
                "error": format!("Content too large. Maximum size is {} bytes", state.server_config.max_content_size)
211
            })),
212
        ));
213
    }
214
    match db::create_snippet(&state.db, &body.name, &body.content) {
215
        Ok(snippet) => Ok((StatusCode::CREATED, Json(snippet))),
216
        Err(_) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Internal server error"})))),
217
    }
218
}
219
220
async fn api_delete_snippet(
221
    State(state): State<AppState>,
222
    Path(short_id): Path<String>,
223
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
224
    match db::delete_snippet_by_short_id(&state.db, &short_id) {
225
        Ok(true) => Ok(Json(serde_json::json!({"deleted": true}))),
226
        Ok(false) => Err((StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Snippet not found"})))),
227
        Err(_) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Internal server error"})))),
228
    }
229
}
230
231
async fn api_update_snippet(
232
    State(state): State<AppState>,
233
    Path(short_id): Path<String>,
234
    Json(body): Json<ApiCreateSnippet>,
235
) -> Result<Json<Snippet>, (StatusCode, Json<serde_json::Value>)> {
236
    if body.content.len() > state.server_config.max_content_size {
237
        return Err((
238
            StatusCode::PAYLOAD_TOO_LARGE,
239
            Json(serde_json::json!({
240
                "error": format!("Content too large. Maximum size is {} bytes", state.server_config.max_content_size)
241
            })),
242
        ));
243
    }
244
    match db::update_snippet_by_short_id(&state.db, &short_id, &body.name, &body.content) {
245
        Ok(Some(snippet)) => Ok(Json(snippet)),
246
        Ok(None) => Err((StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Snippet not found"})))),
247
        Err(_) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Internal server error"})))),
248
    }
249
}
250
251
fn build_api_routes(state: &AppState) -> Router<AppState> {
252
    let config = &state.server_config;
253
254
    let auth_layer = middleware::from_fn_with_state(state.clone(), require_api_key);
255
256
    // /api/snippets — GET (api_list) and POST (api_create)
257
    let list_authed = config.requires_auth("api_list");
258
    let create_authed = config.requires_auth("api_create");
259
260
    // /api/snippets/{short_id} — GET (api_get), PUT (api_update), and DELETE (api_delete)
261
    let get_authed = config.requires_auth("api_get");
262
    let update_authed = config.requires_auth("api_update");
263
    let delete_authed = config.requires_auth("api_delete");
264
265
    // Build authed router
266
    let mut authed = Router::new();
267
    if list_authed {
268
        authed = authed.route("/api/snippets", get(api_list_snippets));
269
    }
270
    if create_authed {
271
        authed = authed.route("/api/snippets", post(api_create_snippet));
272
    }
273
    if get_authed {
274
        authed = authed.route("/api/snippets/{short_id}", get(api_get_snippet));
275
    }
276
    if update_authed {
277
        authed = authed.route("/api/snippets/{short_id}", put(api_update_snippet));
278
    }
279
    if delete_authed {
280
        authed = authed.route("/api/snippets/{short_id}", delete(api_delete_snippet));
281
    }
282
    let authed = authed.route_layer(auth_layer);
283
284
    // Build open router
285
    let mut open = Router::new();
286
    if !list_authed {
287
        open = open.route("/api/snippets", get(api_list_snippets));
288
    }
289
    if !create_authed {
290
        open = open.route("/api/snippets", post(api_create_snippet));
291
    }
292
    if !get_authed {
293
        open = open.route("/api/snippets/{short_id}", get(api_get_snippet));
294
    }
295
    if !update_authed {
296
        open = open.route("/api/snippets/{short_id}", put(api_update_snippet));
297
    }
298
    if !delete_authed {
299
        open = open.route("/api/snippets/{short_id}", delete(api_delete_snippet));
300
    }
301
302
    authed.merge(open)
303
}
304
305
fn mime_from_path(path: &str) -> &'static str {
306
    match path.rsplit('.').next().unwrap_or("") {
307
        "css" => "text/css",
308
        "js" => "application/javascript",
309
        "html" => "text/html",
310
        "png" => "image/png",
311
        "ico" => "image/x-icon",
312
        "svg" => "image/svg+xml",
313
        "woff" => "font/woff",
314
        "woff2" => "font/woff2",
315
        "ttf" => "font/ttf",
316
        "otf" => "font/otf",
317
        "json" | "webmanifest" => "application/json",
318
        "jpg" | "jpeg" => "image/jpeg",
319
        _ => "application/octet-stream",
320
    }
321
}
322
323
async fn serve_assets(Path(path): Path<String>) -> Response {
324
    match Assets::get(&path) {
325
        Some(file) => {
326
            let mime = mime_from_path(&path);
327
            ([(header::CONTENT_TYPE, mime)], file.data).into_response()
328
        }
329
        None => StatusCode::NOT_FOUND.into_response(),
330
    }
331
}
332
333
async fn serve_static(Path(path): Path<String>) -> Response {
334
    match Static::get(&path) {
335
        Some(file) => {
336
            let mime = mime_from_path(&path);
337
            ([(header::CONTENT_TYPE, mime)], file.data).into_response()
338
        }
339
        None => StatusCode::NOT_FOUND.into_response(),
340
    }
341
}
342
343
pub async fn run(host: String, port: u16) {
344
    dotenvy::dotenv().ok();
345
346
    let server_config = ServerConfig::from_env();
347
348
    // Validate endpoint names
349
    let known = ["api_list", "api_create", "api_get", "api_update", "api_delete", "all", "none"];
350
    for name in &server_config.auth_endpoints {
351
        if !known.contains(&name.as_str()) {
352
            eprintln!("Warning: unknown auth endpoint name '{}' in SIPP_AUTH_ENDPOINTS", name);
353
        }
354
    }
355
356
    if !server_config.auth_endpoints.is_empty() && server_config.api_key.is_none() {
357
        eprintln!("Warning: SIPP_AUTH_ENDPOINTS is set but SIPP_API_KEY is not configured");
358
    }
359
360
    if server_config.auth_endpoints.is_empty() {
361
        println!("Auth: disabled (no endpoints require authentication)");
362
    } else {
363
        let names: Vec<&str> = server_config.auth_endpoints.iter().map(|s| s.as_str()).collect();
364
        println!("Auth: enabled for endpoints: {}", names.join(", "));
365
    }
366
367
    println!("Max content size: {} bytes", server_config.max_content_size);
368
369
    let state = AppState {
370
        db: db::init_db().expect("Failed to initialize database"),
371
        highlighter: Arc::new(Highlighter::new()),
372
        server_config,
373
    };
374
375
    let api_routes = build_api_routes(&state);
376
377
    let app = Router::new()
378
        .route("/", get(index))
379
        .route("/s/{short_id}", get(view_snippet))
380
        .route("/snippets", post(create_snippet))
381
        .merge(api_routes)
382
        .route("/assets/{*path}", get(serve_assets))
383
        .route("/static/{*path}", get(serve_static))
384
        .with_state(state);
385
386
    let addr = format!("{}:{}", host, port);
387
    let listener = tokio::net::TcpListener::bind(&addr)
388
        .await
389
        .unwrap_or_else(|_| panic!("Failed to bind to {}", addr));
390
391
    println!("Server running at http://{}:{}", host, port);
392
393
    axum::serve(listener, app)
394
        .await
395
        .expect("Failed to start server");
396
}