opensearch-api 0.1.0

High-performance REST API gateway for OpenSearch with security, observability and multi-tenant support
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use anyhow::Result;
use axum::{
    Router,
    extract::{Path, Query, State},
    http::StatusCode,
    middleware,
    response::Json,
    routing::get,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tower_http::{
    compression::CompressionLayer,
    cors::{Any, CorsLayer},
    trace::TraceLayer,
};
use tracing::{Level, info};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};

mod audit;
mod auth;
mod config;
mod docs;
mod license;
mod metrics;

use config::Config;

#[derive(Clone)]
struct AppState {
    config: Arc<Config>,
    client: reqwest::Client,
}

#[derive(Serialize)]
struct HealthResponse {
    status: String,
    opensearch_url: String,
    version: String,
}

#[derive(Serialize, Deserialize)]
struct Document {
    #[serde(flatten)]
    fields: serde_json::Value,
}

#[derive(Deserialize)]
struct SearchQuery {
    q: String,
    #[serde(default = "default_size")]
    size: usize,
    #[serde(default)]
    from: usize,
}

fn default_size() -> usize {
    10
}

#[derive(Serialize)]
struct IndexResponse {
    id: String,
    index: String,
    result: String,
}

#[derive(Serialize)]
struct SearchResponse {
    hits: Vec<serde_json::Value>,
    total: usize,
    took: u64,
}

#[derive(Serialize)]
struct ErrorResponse {
    error: String,
    message: String,
}

#[tokio::main]
async fn main() -> Result<()> {
    // Load configuration
    let config = Config::from_env().expect("Failed to load configuration");

    // Initialize tracing
    tracing_subscriber::registry()
        .with(fmt::layer())
        .with(
            EnvFilter::builder()
                .with_default_directive(Level::INFO.into())
                .from_env_lossy(),
        )
        .init();

    // Create HTTP client
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .build()?;

    // Create shared state
    let state = Arc::new(AppState {
        config: Arc::new(config),
        client,
    });

    // Setup métricas no OpenSearch
    if let Err(e) = metrics::setup_metrics_indices(&state).await {
        tracing::warn!("Não foi possível criar templates de métricas: {}", e);
    }

    // Inicia coleta de métricas do sistema
    let metrics_state = state.clone();
    tokio::spawn(async move {
        metrics::collect_system_metrics(metrics_state).await;
    });

    // Build router - APENAS proxy transparente
    let app = Router::new()
        // Mantém apenas health para monitoramento
        .route("/health", get(health_check))
        // TUDO MAIS vai para o proxy transparente
        .fallback(opensearch_proxy)
        // Middleware de métricas
        .layer(middleware::from_fn_with_state(
            state.clone(),
            metrics::metrics_middleware,
        ))
        .layer(
            CorsLayer::new()
                .allow_origin(Any)
                .allow_methods(Any)
                .allow_headers(Any),
        )
        .layer(CompressionLayer::new())
        .layer(TraceLayer::new_for_http())
        .with_state(state.clone());

    info!("OpenSearch API starting on http://{}", &state.config.addr);
    info!(
        "Connected to OpenSearch at: {}",
        &state.config.opensearch_url
    );

    // Run the server
    let listener = tokio::net::TcpListener::bind(&state.config.addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

async fn root() -> &'static str {
    "OpenSearch API v0.1.0"
}

async fn health_check(
    State(state): State<Arc<AppState>>,
) -> Result<Json<HealthResponse>, StatusCode> {
    // Check OpenSearch connectivity
    let response = state
        .client
        .get(&state.config.opensearch_url)
        .send()
        .await
        .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;

    if !response.status().is_success() {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }

    Ok(Json(HealthResponse {
        status: "healthy".to_string(),
        opensearch_url: state.config.opensearch_url.clone(),
        version: "0.1.0".to_string(),
    }))
}

async fn index_document(
    auth_user: auth::AuthUser, // EXIGE autenticação
    State(state): State<Arc<AppState>>,
    Path(index_name): Path<String>,
    Json(document): Json<Document>,
) -> Result<Json<IndexResponse>, (StatusCode, Json<ErrorResponse>)> {
    // Log do acesso com identificação do usuário
    tracing::info!(
        "User {} (role: {}) indexing document in {}",
        auth_user.id,
        auth_user.role,
        index_name
    );
    let url = format!("{}/{}/_doc", state.config.opensearch_url, index_name);

    let response = state
        .client
        .post(&url)
        .json(&document.fields)
        .send()
        .await
        .map_err(|e| {
            (
                StatusCode::BAD_GATEWAY,
                Json(ErrorResponse {
                    error: "opensearch_error".to_string(),
                    message: e.to_string(),
                }),
            )
        })?;

    let status = response.status();
    let body: serde_json::Value = response.json().await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: "parse_error".to_string(),
                message: e.to_string(),
            }),
        )
    })?;

    if !status.is_success() {
        return Err((
            StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            Json(ErrorResponse {
                error: "opensearch_error".to_string(),
                message: body
                    .get("error")
                    .map(|e| e.to_string())
                    .unwrap_or_else(|| "Unknown error".to_string()),
            }),
        ));
    }

    Ok(Json(IndexResponse {
        id: body["_id"].as_str().unwrap_or("").to_string(),
        index: index_name,
        result: body["result"].as_str().unwrap_or("unknown").to_string(),
    }))
}

async fn search_documents(
    auth_user: auth::AuthUser, // EXIGE autenticação
    State(state): State<Arc<AppState>>,
    Path(index_name): Path<String>,
    Query(params): Query<SearchQuery>,
) -> Result<Json<SearchResponse>, (StatusCode, Json<ErrorResponse>)> {
    tracing::info!(
        "User {} searching in {} for: {}",
        auth_user.id,
        index_name,
        params.q
    );
    let query = serde_json::json!({
        "query": {
            "multi_match": {
                "query": params.q,
                "fields": ["*"]
            }
        },
        "size": params.size,
        "from": params.from
    });

    let url = format!("{}/{}/_search", state.config.opensearch_url, index_name);

    let response = state
        .client
        .post(&url)
        .json(&query)
        .send()
        .await
        .map_err(|e| {
            (
                StatusCode::BAD_GATEWAY,
                Json(ErrorResponse {
                    error: "opensearch_error".to_string(),
                    message: e.to_string(),
                }),
            )
        })?;

    let status = response.status();
    let body: serde_json::Value = response.json().await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: "parse_error".to_string(),
                message: e.to_string(),
            }),
        )
    })?;

    if !status.is_success() {
        return Err((
            StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            Json(ErrorResponse {
                error: "opensearch_error".to_string(),
                message: body
                    .get("error")
                    .map(|e| e.to_string())
                    .unwrap_or_else(|| "Unknown error".to_string()),
            }),
        ));
    }

    let hits = body["hits"]["hits"]
        .as_array()
        .map(|arr| arr.iter().map(|hit| hit["_source"].clone()).collect())
        .unwrap_or_default();

    let total = body["hits"]["total"]["value"].as_u64().unwrap_or(0) as usize;

    let took = body["took"].as_u64().unwrap_or(0);

    Ok(Json(SearchResponse { hits, total, took }))
}

async fn list_indices(
    auth_user: auth::AuthUser, // EXIGE autenticação
    State(state): State<Arc<AppState>>,
) -> Result<Json<Vec<serde_json::Value>>, (StatusCode, Json<ErrorResponse>)> {
    tracing::info!("User {} listing indices", auth_user.id);
    let url = format!("{}/_cat/indices?format=json", state.config.opensearch_url);

    let response = state.client.get(&url).send().await.map_err(|e| {
        (
            StatusCode::BAD_GATEWAY,
            Json(ErrorResponse {
                error: "opensearch_error".to_string(),
                message: e.to_string(),
            }),
        )
    })?;

    let indices: Vec<serde_json::Value> = response.json().await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: "parse_error".to_string(),
                message: e.to_string(),
            }),
        )
    })?;

    Ok(Json(indices))
}

async fn get_index_info(
    auth_user: auth::AuthUser, // EXIGE autenticação
    State(state): State<Arc<AppState>>,
    Path(index_name): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    tracing::info!(
        "User {} getting info for index: {}",
        auth_user.id,
        index_name
    );
    let url = format!("{}/{}", state.config.opensearch_url, index_name);

    let response = state.client.get(&url).send().await.map_err(|e| {
        (
            StatusCode::BAD_GATEWAY,
            Json(ErrorResponse {
                error: "opensearch_error".to_string(),
                message: e.to_string(),
            }),
        )
    })?;

    let status = response.status();
    let body: serde_json::Value = response.json().await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: "parse_error".to_string(),
                message: e.to_string(),
            }),
        )
    })?;

    if !status.is_success() {
        return Err((
            StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            Json(ErrorResponse {
                error: "opensearch_error".to_string(),
                message: body
                    .get("error")
                    .map(|e| e.to_string())
                    .unwrap_or_else(|| "Unknown error".to_string()),
            }),
        ));
    }

    Ok(Json(body))
}
// Proxy transparente para OpenSearch - configurado como fallback
async fn opensearch_proxy(
    State(state): State<Arc<AppState>>,
    headers: axum::http::HeaderMap,
    method: axum::http::Method,
    uri: axum::http::Uri,
    body: axum::body::Bytes,
) -> impl axum::response::IntoResponse {
    use axum::http::{StatusCode, header};

    // Extrai API key do header Authorization
    let api_key = headers
        .get(header::AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .and_then(|h| h.strip_prefix("Bearer "));

    // Valida API key
    let is_valid = match api_key {
        Some(key) => {
            // Verifica se a key está nas configuradas
            std::env::var("API_TOKENS")
                .unwrap_or_default()
                .split(',')
                .any(|token| token.trim() == key)
        }
        None => false,
    };

    if !is_valid {
        return axum::response::Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .body(axum::body::Body::from(
                "Unauthorized: Invalid or missing API key",
            ))
            .unwrap();
    }

    let path = uri.path();
    let query = uri.query().unwrap_or("");

    // Log da requisição
    tracing::info!("Proxy request: {} {}", method, path);

    // Constrói URL completa para o OpenSearch
    let url = if query.is_empty() {
        format!("{}{}", state.config.opensearch_url, path)
    } else {
        format!("{}{}?{}", state.config.opensearch_url, path, query)
    };

    // Cria requisição para OpenSearch
    let mut opensearch_req = state.client.request(method, &url);

    // Adiciona headers relevantes (exceto Authorization)
    for (key, value) in headers.iter() {
        if key != header::AUTHORIZATION && key != header::HOST && key != header::CONNECTION {
            opensearch_req = opensearch_req.header(key, value);
        }
    }

    // Adiciona body se não estiver vazio
    if !body.is_empty() {
        opensearch_req = opensearch_req.body(body);
    }

    // Envia requisição ao OpenSearch
    let response = match opensearch_req.send().await {
        Ok(resp) => resp,
        Err(e) => {
            tracing::error!("OpenSearch error: {}", e);
            return axum::response::Response::builder()
                .status(StatusCode::BAD_GATEWAY)
                .body(axum::body::Body::from(format!("OpenSearch error: {}", e)))
                .unwrap();
        }
    };

    // Extrai status e headers da resposta
    let status = response.status();
    let resp_headers = response.headers().clone();

    // Extrai body da resposta
    let response_body = match response.bytes().await {
        Ok(bytes) => bytes,
        Err(e) => {
            return axum::response::Response::builder()
                .status(StatusCode::BAD_GATEWAY)
                .body(axum::body::Body::from(format!(
                    "Error reading response: {}",
                    e
                )))
                .unwrap();
        }
    };

    // Constrói resposta mantendo status e headers originais
    let mut final_response = axum::response::Response::builder().status(status.as_u16());

    // Copia headers relevantes
    for (key, value) in resp_headers.iter() {
        if key != header::CONNECTION && key != header::TRANSFER_ENCODING {
            final_response = final_response.header(key, value);
        }
    }

    // Retorna resposta com body
    final_response
        .body(axum::body::Body::from(response_body))
        .unwrap()
}