src/server.rs 9.4 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},
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
}
32
33
impl ServerConfig {
34
    fn from_env() -> Self {
35
        let api_key = std::env::var("SIPP_API_KEY").ok();
36
        let auth_endpoints = match std::env::var("SIPP_AUTH_ENDPOINTS") {
37
            Ok(val) if val.trim().eq_ignore_ascii_case("none") => HashSet::new(),
38
            Ok(val) => val.split(',').map(|s| s.trim().to_lowercase()).collect(),
39
            Err(_) => ["api_delete", "api_list"].iter().map(|s| s.to_string()).collect(),
40
        };
41
        ServerConfig { api_key, auth_endpoints }
42
    }
43
44
    fn requires_auth(&self, name: &str) -> bool {
45
        self.auth_endpoints.contains("all") || self.auth_endpoints.contains(name)
46
    }
47
}
48
49
#[derive(Clone)]
50
struct AppState {
51
    db: Db,
52
    highlighter: Arc<Highlighter>,
53
    server_config: ServerConfig,
54
}
55
56
#[derive(Template)]
57
#[template(path = "index.html")]
58
struct IndexTemplate;
59
60
#[derive(Template)]
61
#[template(path = "snippet.html")]
62
struct SnippetTemplate {
63
    name: String,
64
    content: String,
65
    highlighted_content: String,
66
}
67
68
#[derive(Template)]
69
#[template(path = "about.html")]
70
struct AboutTemplate;
71
72
#[derive(Deserialize)]
73
struct CreateSnippetForm {
74
    name: String,
75
    content: String,
76
}
77
78
async fn index() -> WebTemplate<IndexTemplate> {
79
    WebTemplate(IndexTemplate)
80
}
81
82
async fn about() -> WebTemplate<AboutTemplate> {
83
    WebTemplate(AboutTemplate)
84
}
85
86
async fn view_snippet(
87
    State(state): State<AppState>,
88
    Path(short_id): Path<String>,
89
) -> Result<WebTemplate<SnippetTemplate>, (StatusCode, Html<String>)> {
90
    match db::get_snippet_by_short_id(&state.db, &short_id) {
91
        Some(snippet) => {
92
            let highlighted_content = state.highlighter.highlight(&snippet.name, &snippet.content);
93
            Ok(WebTemplate(SnippetTemplate {
94
                name: snippet.name,
95
                content: snippet.content,
96
                highlighted_content,
97
            }))
98
        }
99
        None => Err((
100
            StatusCode::NOT_FOUND,
101
            Html("<h1>Snippet not found</h1>".to_string()),
102
        )),
103
    }
104
}
105
106
async fn create_snippet(
107
    State(state): State<AppState>,
108
    Form(form): Form<CreateSnippetForm>,
109
) -> impl IntoResponse {
110
    let snippet = db::create_snippet(&state.db, &form.name, &form.content);
111
    Redirect::to(&format!("/s/{}", snippet.short_id))
112
}
113
114
async fn require_api_key(
115
    State(state): State<AppState>,
116
    headers: HeaderMap,
117
    request: Request,
118
    next: Next,
119
) -> Result<Response, (StatusCode, Json<serde_json::Value>)> {
120
    let server_key = match &state.server_config.api_key {
121
        Some(k) => k,
122
        None => return Err((
123
            StatusCode::FORBIDDEN,
124
            Json(serde_json::json!({"error": "No API key configured on server"})),
125
        )),
126
    };
127
    let provided = headers
128
        .get("x-api-key")
129
        .and_then(|v| v.to_str().ok());
130
    match provided {
131
        Some(k) if k.as_bytes().ct_eq(server_key.as_bytes()).into() => Ok(next.run(request).await),
132
        _ => Err((
133
            StatusCode::UNAUTHORIZED,
134
            Json(serde_json::json!({"error": "Invalid or missing API key"})),
135
        )),
136
    }
137
}
138
139
async fn api_list_snippets(
140
    State(state): State<AppState>,
141
) -> Json<Vec<Snippet>> {
142
    Json(db::get_all_snippets(&state.db))
143
}
144
145
async fn api_get_snippet(
146
    State(state): State<AppState>,
147
    Path(short_id): Path<String>,
148
) -> Result<Json<Snippet>, (StatusCode, Json<serde_json::Value>)> {
149
    match db::get_snippet_by_short_id(&state.db, &short_id) {
150
        Some(snippet) => Ok(Json(snippet)),
151
        None => Err((StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Snippet not found"})))),
152
    }
153
}
154
155
#[derive(Deserialize)]
156
struct ApiCreateSnippet {
157
    name: String,
158
    content: String,
159
}
160
161
async fn api_create_snippet(
162
    State(state): State<AppState>,
163
    Json(body): Json<ApiCreateSnippet>,
164
) -> (StatusCode, Json<Snippet>) {
165
    let snippet = db::create_snippet(&state.db, &body.name, &body.content);
166
    (StatusCode::CREATED, Json(snippet))
167
}
168
169
async fn api_delete_snippet(
170
    State(state): State<AppState>,
171
    Path(short_id): Path<String>,
172
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
173
    if db::delete_snippet_by_short_id(&state.db, &short_id) {
174
        Ok(Json(serde_json::json!({"deleted": true})))
175
    } else {
176
        Err((StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Snippet not found"}))))
177
    }
178
}
179
180
fn build_api_routes(state: &AppState) -> Router<AppState> {
181
    let config = &state.server_config;
182
183
    let auth_layer = middleware::from_fn_with_state(state.clone(), require_api_key);
184
185
    // /api/snippets — GET (api_list) and POST (api_create)
186
    let list_authed = config.requires_auth("api_list");
187
    let create_authed = config.requires_auth("api_create");
188
189
    // /api/snippets/{short_id} — GET (api_get) and DELETE (api_delete)
190
    let get_authed = config.requires_auth("api_get");
191
    let delete_authed = config.requires_auth("api_delete");
192
193
    // Build authed router
194
    let mut authed = Router::new();
195
    if list_authed {
196
        authed = authed.route("/api/snippets", get(api_list_snippets));
197
    }
198
    if create_authed {
199
        authed = authed.route("/api/snippets", post(api_create_snippet));
200
    }
201
    if get_authed {
202
        authed = authed.route("/api/snippets/{short_id}", get(api_get_snippet));
203
    }
204
    if delete_authed {
205
        authed = authed.route("/api/snippets/{short_id}", delete(api_delete_snippet));
206
    }
207
    let authed = authed.route_layer(auth_layer);
208
209
    // Build open router
210
    let mut open = Router::new();
211
    if !list_authed {
212
        open = open.route("/api/snippets", get(api_list_snippets));
213
    }
214
    if !create_authed {
215
        open = open.route("/api/snippets", post(api_create_snippet));
216
    }
217
    if !get_authed {
218
        open = open.route("/api/snippets/{short_id}", get(api_get_snippet));
219
    }
220
    if !delete_authed {
221
        open = open.route("/api/snippets/{short_id}", delete(api_delete_snippet));
222
    }
223
224
    authed.merge(open)
225
}
226
227
fn mime_from_path(path: &str) -> &'static str {
228
    match path.rsplit('.').next().unwrap_or("") {
229
        "css" => "text/css",
230
        "js" => "application/javascript",
231
        "html" => "text/html",
232
        "png" => "image/png",
233
        "ico" => "image/x-icon",
234
        "svg" => "image/svg+xml",
235
        "woff" => "font/woff",
236
        "woff2" => "font/woff2",
237
        "ttf" => "font/ttf",
238
        "otf" => "font/otf",
239
        "json" | "webmanifest" => "application/json",
240
        "jpg" | "jpeg" => "image/jpeg",
241
        _ => "application/octet-stream",
242
    }
243
}
244
245
async fn serve_assets(Path(path): Path<String>) -> Response {
246
    match Assets::get(&path) {
247
        Some(file) => {
248
            let mime = mime_from_path(&path);
249
            ([(header::CONTENT_TYPE, mime)], file.data).into_response()
250
        }
251
        None => StatusCode::NOT_FOUND.into_response(),
252
    }
253
}
254
255
async fn serve_static(Path(path): Path<String>) -> Response {
256
    match Static::get(&path) {
257
        Some(file) => {
258
            let mime = mime_from_path(&path);
259
            ([(header::CONTENT_TYPE, mime)], file.data).into_response()
260
        }
261
        None => StatusCode::NOT_FOUND.into_response(),
262
    }
263
}
264
265
pub async fn run(host: String, port: u16) {
266
    dotenvy::dotenv().ok();
267
268
    let server_config = ServerConfig::from_env();
269
270
    // Validate endpoint names
271
    let known = ["api_list", "api_create", "api_get", "api_delete", "all", "none"];
272
    for name in &server_config.auth_endpoints {
273
        if !known.contains(&name.as_str()) {
274
            eprintln!("Warning: unknown auth endpoint name '{}' in SIPP_AUTH_ENDPOINTS", name);
275
        }
276
    }
277
278
    if !server_config.auth_endpoints.is_empty() && server_config.api_key.is_none() {
279
        eprintln!("Warning: SIPP_AUTH_ENDPOINTS is set but SIPP_API_KEY is not configured");
280
    }
281
282
    if server_config.auth_endpoints.is_empty() {
283
        println!("Auth: disabled (no endpoints require authentication)");
284
    } else {
285
        let names: Vec<&str> = server_config.auth_endpoints.iter().map(|s| s.as_str()).collect();
286
        println!("Auth: enabled for endpoints: {}", names.join(", "));
287
    }
288
289
    let state = AppState {
290
        db: db::init_db(),
291
        highlighter: Arc::new(Highlighter::new()),
292
        server_config,
293
    };
294
295
    let api_routes = build_api_routes(&state);
296
297
    let app = Router::new()
298
        .route("/", get(index))
299
        .route("/about", get(about))
300
        .route("/s/{short_id}", get(view_snippet))
301
        .route("/snippets", post(create_snippet))
302
        .merge(api_routes)
303
        .route("/assets/{*path}", get(serve_assets))
304
        .route("/static/{*path}", get(serve_static))
305
        .with_state(state);
306
307
    let addr = format!("{}:{}", host, port);
308
    let listener = tokio::net::TcpListener::bind(&addr)
309
        .await
310
        .unwrap_or_else(|_| panic!("Failed to bind to {}", addr));
311
312
    println!("Server running at http://{}:{}", host, port);
313
314
    axum::serve(listener, app)
315
        .await
316
        .expect("Failed to start server");
317
}