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
|
//! Administering the short API tokens (see src/tokens.rs).
//!
//! **These routes answer only a caller on this machine**: the TCP peer
//! address must be 127.0.x.x or ::1, the connection must be direct (no
//! `X-Forwarded-For` / `Forwarded` / `X-Real-IP`, which a reverse proxy
//! on the same host would add), and a request with no known peer is
//! refused. Anything else is a 403 (`not_local`). That guard is shared
//! with `/get-test-token` (src/routes/dev.rs) rather than reinvented:
//! minting credentials must never be reachable from the network, and
//! there is no configuration switch that can change that.
//!
//! What is deliberately absent:
//!
//! - **no token in a query string.** Creating one is a POST, introspection
//! reads the caller's own `Authorization: Bearer`, and nothing here
//! takes a secret as a parameter, because query strings end up in
//! nginx's access log and in `next` links;
//! - **no secret is ever returned again.** `POST /tokens` shows the token
//! exactly once, in its reply; `GET /tokens` lists handles, subjects and
//! timestamps, never the token or its hash;
//! - **no way to impersonate with `x-gn4-user`.** That header is set by
//! this server on responses; it is never read as a credential.
use axum::Json;
use axum::extract::{ConnectInfo, Extension, Path};
use axum::http::{HeaderMap, StatusCode};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use crate::auth::AuthToken;
use crate::config::Config;
use crate::error::ApiError;
use crate::response::{Ctx, Envelope};
use crate::routes::dev::{is_local, via_proxy};
use crate::tokens::{self, Record};
/// One registry row as the API reports it: no secret, no hash.
#[derive(Serialize, utoipa::ToSchema)]
pub struct TokenView {
pub id: String,
pub subject: String,
pub scope: String,
/// The first characters of the secret, so an operator can match a
/// row to a token they are holding without the row storing it.
pub prefix: String,
pub created_at: i64,
pub expires_at: Option<i64>,
pub last_used_at: Option<i64>,
pub note: Option<String>,
pub revoked_at: Option<i64>,
pub status: String,
}
impl TokenView {
fn of(record: &Record) -> Self {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let status = if record.revoked() {
"revoked"
} else if record.expired(now) {
"expired"
} else {
"active"
};
Self {
id: record.id.clone(),
subject: record.subject.clone(),
scope: record.scope.clone(),
prefix: record.prefix.clone(),
created_at: record.created_at,
expires_at: record.expires_at,
last_used_at: record.last_used_at,
note: record.note.clone(),
revoked_at: record.revoked_at,
status: status.to_string(),
}
}
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct MintRequest {
/// Human handle, unique: `zachs-1`, `agent-ravanan-3`.
pub id: String,
/// Who the token is for (the gn-auth user id it acts as).
pub subject: String,
/// Registry-declared scope; v1 mints `public`.
#[serde(default)]
pub scope: Option<String>,
/// Lifetime in days; omitted means `tokens::DEFAULT_TTL_DAYS`.
#[serde(default)]
pub ttl_days: Option<i64>,
#[serde(default)]
pub note: Option<String>,
}
#[derive(Serialize, utoipa::ToSchema)]
pub struct Minted {
/// Shown once, and only once: it is not stored anywhere.
pub token: String,
pub id: String,
pub subject: String,
pub scope: String,
pub prefix: String,
pub created_at: i64,
pub expires_at: Option<i64>,
pub status: String,
}
/// The localhost guard as middleware, applied to the whole token router
/// in src/lib.rs.
///
/// A layer rather than a check inside each handler, deliberately: axum
/// extracts a handler's arguments *before* its body runs, so a per-handler
/// check would still answer a remote caller with a 415 for a malformed
/// body. This refuses the request before anything is parsed, which is what
/// "only responds to localhost" has to mean.
pub async fn local_only(
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::response::IntoResponse;
let peer = request
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.cloned();
let rid = request
.extensions()
.get::<crate::response::RequestInfo>()
.cloned()
.unwrap_or_else(|| crate::response::RequestInfo::new(None));
if let Err(error) = require_local(&peer.map(Extension), request.headers(), &rid, "tokens") {
return error.into_response();
}
next.run(request).await
}
/// The localhost guard, shared by every route in this module.
fn require_local(
peer: &Option<Extension<ConnectInfo<SocketAddr>>>,
headers: &HeaderMap,
rid: &crate::response::RequestInfo,
operation: &str,
) -> Result<(), ApiError> {
let local = peer
.as_ref()
.is_some_and(|Extension(ConnectInfo(address))| is_local(address));
if !local || via_proxy(headers) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"not_local",
"Not authorized",
"Token administration only answers callers on this machine (127.0.x.x or ::1), \
directly and not through a proxy."
.to_string(),
operation,
)
.with_request_id(rid.clone()));
}
Ok(())
}
fn registry(config: &Config) -> Result<tokens::Registry, ApiError> {
tokens::registry(&config.api_tokens_db).map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"token_registry",
"Token registry unavailable",
error,
"tokens",
)
})
}
#[utoipa::path(get, path = "/tokens", summary = "List the short API tokens (localhost only)", description = "Answers only a caller on this machine (127.0.x.x or ::1, directly, not through a proxy); anything else is a 403. Never returns a token or its hash.", responses(
(status = 200, description = "Every registered token", body = Envelope<Vec<TokenView>>),
(status = 403, description = "The request did not come from localhost", body = ApiError)
), security())]
pub async fn list_tokens(
ctx: Ctx,
peer: Option<Extension<ConnectInfo<SocketAddr>>>,
headers: HeaderMap,
) -> Result<Json<Envelope<Vec<TokenView>>>, ApiError> {
let rid = ctx.request_info();
// Defence in depth: the router layer has already refused non-local
// callers before anything was parsed (see `local_only`).
require_local(&peer, &headers, &rid, "list_tokens")?;
let config = Config::load();
let records = tokio::task::spawn_blocking(move || registry(&config).and_then(|r| {
r.list().map_err(|error| ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"token_registry",
"Token registry error",
error,
"list_tokens",
))
}))
.await
.map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"Internal error",
error.to_string(),
"list_tokens",
)
.with_request_id(rid.clone())
})??;
Ok(Json(ctx.envelope(records.iter().map(TokenView::of).collect())))
}
#[utoipa::path(post, path = "/tokens", summary = "Mint a short API token (localhost only)", description = "Answers only a caller on this machine (127.0.x.x or ::1, directly, not through a proxy). The token is returned exactly once and only its SHA-256 is stored.", responses(
(status = 200, description = "The new token, shown once", body = Envelope<Minted>),
(status = 403, description = "The request did not come from localhost", body = ApiError),
(status = 409, description = "That id is already taken", body = ApiError)
), security())]
pub async fn mint_token(
ctx: Ctx,
peer: Option<Extension<ConnectInfo<SocketAddr>>>,
headers: HeaderMap,
Json(request): Json<MintRequest>,
) -> Result<Json<Envelope<Minted>>, ApiError> {
let rid = ctx.request_info();
require_local(&peer, &headers, &rid, "mint_token")?;
let config = Config::load();
let scope = request.scope.unwrap_or_else(|| "public".to_string());
let minted = tokio::task::spawn_blocking(move || {
let registry = registry(&config)?;
let (secret, record) = registry
.mint(
request.id.trim(),
request.subject.trim(),
&scope,
request.ttl_days,
request.note.as_deref(),
)
.map_err(|error| {
// SQLite says "UNIQUE constraint failed" for a taken id; that
// is a 409, not a server error.
let status = if error.contains("UNIQUE") {
StatusCode::CONFLICT
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
ApiError::new(
status,
"token_not_minted",
"Could not mint the token",
format!("{}: {error}", request.id),
"mint_token",
)
})?;
let view = TokenView::of(&record);
Ok::<_, ApiError>(Minted {
token: secret,
id: view.id,
subject: view.subject,
scope: view.scope,
prefix: view.prefix,
created_at: view.created_at,
expires_at: view.expires_at,
status: view.status,
})
})
.await
.map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"Internal error",
error.to_string(),
"mint_token",
)
.with_request_id(rid.clone())
})??;
Ok(Json(ctx.envelope(minted)))
}
#[utoipa::path(delete, path = "/tokens/{id}", summary = "Revoke a short API token (localhost only)", description = "Answers only a caller on this machine. Revocation takes effect on the next request, without a restart.", params(("id" = String, Path, description = "The token's handle, e.g. zachs-1")), responses(
(status = 200, description = "The revoked token", body = Envelope<TokenView>),
(status = 403, description = "The request did not come from localhost", body = ApiError),
(status = 404, description = "No such token", body = ApiError)
), security())]
pub async fn revoke_token(
ctx: Ctx,
peer: Option<Extension<ConnectInfo<SocketAddr>>>,
headers: HeaderMap,
Path(id): Path<String>,
) -> Result<Json<Envelope<TokenView>>, ApiError> {
let rid = ctx.request_info();
require_local(&peer, &headers, &rid, "revoke_token")?;
let config = Config::load();
let wanted = id.clone();
let revoked = tokio::task::spawn_blocking(move || {
let registry = registry(&config)?;
let changed = registry.revoke(&wanted).map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"token_registry",
"Token registry error",
error,
"revoke_token",
)
})?;
if !changed {
return Err(ApiError::new(
StatusCode::NOT_FOUND,
"no_such_token",
"No such token",
format!("There is no active token with id {wanted}."),
"revoke_token",
));
}
let record = registry
.list()
.map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"token_registry",
"Token registry error",
error,
"revoke_token",
)
})?
.into_iter()
.find(|record| record.id == wanted);
Ok::<_, ApiError>(record)
})
.await
.map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"Internal error",
error.to_string(),
"revoke_token",
)
.with_request_id(rid.clone())
})??;
match revoked {
Some(record) => Ok(Json(ctx.envelope(TokenView::of(&record)))),
None => Err(ApiError::new(
StatusCode::NOT_FOUND,
"no_such_token",
"No such token",
format!("There is no token with id {id}."),
"revoke_token",
)),
}
}
/// Who is this credential, and how long has it got? Works for both
/// schemes: a JWT answers with its claims, an opaque token with its
/// registry row. The credential is read from the `Authorization` header
/// by [`AuthToken`] -- never from a query parameter.
#[derive(Serialize, utoipa::ToSchema)]
pub struct WhoAmI {
pub scheme: String,
pub subject: String,
pub scope: String,
/// Present for an opaque token, absent for a JWT.
pub id: Option<String>,
pub created_at: Option<i64>,
pub expires_at: Option<i64>,
pub last_used_at: Option<i64>,
}
#[utoipa::path(get, path = "/tokens/who", summary = "Describe the presented credential (localhost only)", description = "Answers only a caller on this machine (127.0.x.x or ::1, directly, not through a proxy), for either a gn-auth JWT or a gn4ai_ token, read from the Authorization header.", responses(
(status = 200, description = "The credential's identity and lifetime", body = Envelope<WhoAmI>),
(status = 401, description = "Missing or invalid credential", body = ApiError),
(status = 403, description = "The request did not come from localhost", body = ApiError)
), security(("bearer" = [])))]
pub async fn who_am_i(
ctx: Ctx,
peer: Option<Extension<ConnectInfo<SocketAddr>>>,
headers: HeaderMap,
token: AuthToken,
) -> Result<Json<Envelope<WhoAmI>>, ApiError> {
let rid = ctx.request_info();
require_local(&peer, &headers, &rid, "who_am_i")?;
let mut who = WhoAmI {
scheme: token.scheme.as_str().to_string(),
subject: token.sub.clone(),
scope: token.scope.clone(),
id: token.id.clone(),
created_at: None,
expires_at: None,
last_used_at: None,
};
if token.scheme == crate::auth::Scheme::Opaque {
let config = Config::load();
let secret = token.raw.clone();
let record = tokio::task::spawn_blocking(move || {
registry(&config).and_then(|r| {
r.describe(&secret).map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"token_registry",
"Token registry error",
error,
"who_am_i",
)
})
})
})
.await
.map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"Internal error",
error.to_string(),
"who_am_i",
)
.with_request_id(rid.clone())
})??;
if let Some(record) = record {
who.created_at = Some(record.created_at);
who.expires_at = record.expires_at;
who.last_used_at = record.last_used_at;
}
}
Ok(Json(ctx.envelope(who)))
}
|