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