Skip to main content

universal_exports/
keys.rs

1//! API keys: the key provider's place in sign-in, and the routes with which a person makes,
2//! lists and revokes their own keys (`/v1/user/keys`).
3//!
4//! A key is presented as a request's bearer. The key provider says whose it is; a personal key
5//! then acts as the person who made it, narrowed to the scopes named when it was made and
6//! judged again at every use, so a grant the person loses the key loses too. A key without a
7//! record is a service account's: it acts as that account, with the account's own grants. The
8//! key's value is shown once, when it is made, and is in no log, audit record or error.
9
10use std::sync::Arc;
11
12use ai6::wire::keys::{CreateKey, CreatedKey, KeyView};
13use ai6::{
14    ACTIONS, AccountPut, Accounts, ApiKeyRecord, Attempt, Authenticator, CONFIG_ACCOUNTS,
15    Directory, KeyScope, Person, Verdict,
16};
17use axum::Json;
18use axum::extract::{Path, Query, State};
19use axum::http::{HeaderMap, StatusCode};
20use serde::{Deserialize, Serialize};
21use uuid::Uuid;
22
23use crate::access_admin::AdminError;
24use crate::{
25    ApiError, Gateway, actor_of, bearer, person_by_id, resolve_signed_in, resource_action_allowed,
26    unix_timestamp,
27};
28
29/// The start of the name of the key provider's account behind a personal key. Accounts made
30/// through the account routes may not take it, so no service account is mistaken for a key.
31pub(crate) const PERSONAL_PREFIX: &str = "uk-";
32
33/// The key provider as the gateway uses it: it recognizes a key, finds the account a key
34/// belongs to, and makes and removes the accounts behind personal keys.
35#[derive(Clone)]
36pub struct KeyProvider {
37    authenticator: Arc<dyn Authenticator>,
38    directory: Arc<dyn Directory>,
39    accounts: Arc<dyn Accounts>,
40    /// Seconds a personal key lives when its maker names none; 0 never ends.
41    lifetime: f64,
42    /// Seconds within which a second use of a key is not written down again.
43    precision: f64,
44}
45
46impl KeyProvider {
47    /// The key provider `authenticator`, whose accounts `directory` finds and `accounts` keeps.
48    pub fn new(
49        authenticator: Arc<dyn Authenticator>,
50        directory: Arc<dyn Directory>,
51        accounts: Arc<dyn Accounts>,
52    ) -> Self {
53        Self {
54            authenticator,
55            directory,
56            accounts,
57            lifetime: DEFAULT_KEY_TTL,
58            precision: 5.0,
59        }
60    }
61
62    /// Sets how long a personal key lives when its maker names no expiry, in seconds (the
63    /// record's `key_ttl`; 0 means until revoked). Default: 90 days.
64    #[must_use]
65    pub fn with_lifetime(mut self, seconds: Option<f64>) -> Self {
66        self.lifetime = seconds.map_or(DEFAULT_KEY_TTL, |seconds| seconds.max(0.0));
67        self
68    }
69
70    /// Sets how closely a key's last use is kept, in seconds (the access cache's lifetime, the
71    /// record's `access_cache_ttl`). Default: 5.
72    #[must_use]
73    pub fn with_use_precision(mut self, seconds: Option<f64>) -> Self {
74        self.precision = seconds.map_or(5.0, |seconds| seconds.max(0.0));
75        self
76    }
77}
78
79/// The person a presented key acts as; `None` when no key provider claims the value, or it is
80/// refused (unknown, disabled, expired, revoked, or its person gone).
81pub(crate) async fn resolve(gateway: &Gateway, token: &str) -> Result<Option<Person>, ApiError> {
82    let Some(keys) = gateway
83        .access
84        .as_ref()
85        .and_then(|access| access.keys.clone())
86    else {
87        return Ok(None);
88    };
89    let attempt = Attempt {
90        secret: Some(token.to_owned()),
91        secure: Some(true),
92        ..Attempt::default()
93    };
94    let authenticator = keys.authenticator.clone();
95    let verdict = tokio::task::spawn_blocking(move || authenticator.authenticate(attempt))
96        .await
97        .map_err(|_| ApiError::internal())?
98        .map_err(|_| ApiError::internal())?;
99    let Verdict::Valid(lookup) = verdict else {
100        return Ok(None);
101    };
102    let now = unix_timestamp()?;
103    let record = match gateway.registry.clone() {
104        Some(registry) if lookup.by == "id" => {
105            let id = lookup.value.clone();
106            tokio::task::spawn_blocking(move || registry.api_key(&id))
107                .await
108                .map_err(|_| ApiError::internal())?
109                .map_err(|_| ApiError::internal())?
110        }
111        _ => None,
112    };
113    let Some(record) = record else {
114        let directory = keys.directory.clone();
115        let account = tokio::task::spawn_blocking(move || directory.lookup(lookup))
116            .await
117            .map_err(|_| ApiError::internal())?
118            .map_err(|_| ApiError::internal())?;
119        // An account behind a personal key whose record is gone has nobody to act as.
120        return Ok(account.filter(|account| !account.name.starts_with(PERSONAL_PREFIX)));
121    };
122    if record.expired_at(now) {
123        return Ok(None);
124    }
125    let Ok(mut person) = person_by_id(gateway, record.owner.clone()).await else {
126        return Ok(None);
127    };
128    let scopes: Vec<KeyScope> = record
129        .scopes
130        .iter()
131        .filter_map(|text| text.parse().ok())
132        .collect();
133    ai6::narrow_to_key(&mut person, &record.id, &scopes);
134    touch(gateway, keys.precision, &record.id, now).await;
135    Ok(Some(person))
136}
137
138/// Records a use of key `id`, as precisely as the access cache keeps an answer.
139async fn touch(gateway: &Gateway, within: f64, id: &str, now: f64) {
140    let Some(registry) = gateway.registry.clone() else {
141        return;
142    };
143    let id = id.to_owned();
144    // A use that cannot be written down does not refuse the request.
145    let _ = tokio::task::spawn_blocking(move || registry.touch_api_key(&id, now, within)).await;
146}
147
148fn key_provider(gateway: &Gateway) -> Result<KeyProvider, AdminError> {
149    gateway
150        .access
151        .as_ref()
152        .and_then(|access| access.keys.clone())
153        .ok_or_else(|| AdminError::Conflict("no key provider is configured".to_owned()))
154}
155
156fn registry(
157    gateway: &Gateway,
158) -> Result<Arc<dyn ai6::directorates::registry::backend::RegistryBackend>, AdminError> {
159    gateway
160        .registry
161        .clone()
162        .ok_or_else(|| AdminError::Api(ApiError::unavailable()))
163}
164
165async fn is_administrator(gateway: &Gateway, person: &Person) -> Result<bool, AdminError> {
166    Ok(resource_action_allowed(
167        gateway,
168        person.clone(),
169        CONFIG_ACCOUNTS.to_owned(),
170        "account.manage",
171    )
172    .await?)
173}
174
175async fn audit(
176    gateway: &Gateway,
177    person: &Person,
178    action: &str,
179    target: &str,
180) -> Result<(), AdminError> {
181    let registry = registry(gateway)?;
182    let record = ai6::AuditRecord {
183        id: Uuid::new_v4().to_string(),
184        actor: actor_of(person),
185        action: action.to_owned(),
186        operation: String::new(),
187        resource: Some(CONFIG_ACCOUNTS.to_owned()),
188        target: crate::roster::bounded(target, gateway.config.unex().text.roster_target_bytes),
189        at: unix_timestamp()?,
190    };
191    tokio::task::spawn_blocking(move || registry.record_audit(&record))
192        .await
193        .map_err(|_| AdminError::Api(ApiError::internal()))?
194        .map_err(|_| AdminError::Api(ApiError::internal()))
195}
196
197#[derive(Deserialize)]
198pub(crate) struct ListQuery {
199    #[serde(default)]
200    all: bool,
201}
202
203/// `GET /v1/user/keys`: the signed-in person's keys; with `?all=true`, everyone's, which needs
204/// `account.manage` at `config:accounts`.
205pub(crate) async fn list(
206    State(gateway): State<Gateway>,
207    headers: HeaderMap,
208    Query(query): Query<ListQuery>,
209) -> Result<Json<Vec<KeyView>>, AdminError> {
210    let person = resolve_signed_in(&gateway, bearer(&headers)?).await?;
211    if query.all && !is_administrator(&gateway, &person).await? {
212        return Err(ApiError::forbidden().into());
213    }
214    let registry = registry(&gateway)?;
215    let owner = (!query.all).then(|| person.id.clone());
216    let keys = tokio::task::spawn_blocking(move || registry.api_keys(owner.as_deref()))
217        .await
218        .map_err(|_| AdminError::Api(ApiError::internal()))?
219        .map_err(|_| AdminError::Api(ApiError::internal()))?;
220    Ok(Json(keys.into_iter().map(KeyView::from).collect()))
221}
222
223/// The default life of a key whose maker names none, in seconds.
224const DEFAULT_KEY_TTL: f64 = 90.0 * 24.0 * 3600.0;
225
226/// `POST /v1/user/keys`: makes a key for the signed-in person, narrowed to `scopes`, each of
227/// which the person holds now. A key cannot make a key.
228pub(crate) async fn create(
229    State(gateway): State<Gateway>,
230    headers: HeaderMap,
231    Json(body): Json<CreateKey>,
232) -> Result<(StatusCode, Json<CreatedKey>), AdminError> {
233    let person = resolve_signed_in(&gateway, bearer(&headers)?).await?;
234    let keys = key_provider(&gateway)?;
235    let registry = registry(&gateway)?;
236    let text = &gateway.config.unex().text;
237    if body.name.trim().is_empty()
238        || !text.access_name_bytes.allows(body.name.len())
239        || body.name.chars().any(char::is_control)
240    {
241        return Err(AdminError::Refused("name the key".to_owned()));
242    }
243    let mut scopes: Vec<KeyScope> = Vec::new();
244    for text in &body.scopes {
245        let scope: KeyScope = text
246            .parse()
247            .map_err(|error: ai6::KeyScopeError| AdminError::Refused(error.to_string()))?;
248        if scope.scope == "*" {
249            return Err(AdminError::Refused(
250                "name the resource a scope covers, not *".to_owned(),
251            ));
252        }
253        if !scopes.contains(&scope) {
254            scopes.push(scope);
255        }
256    }
257    if scopes.is_empty() {
258        return Err(AdminError::Refused(
259            "name at least one scope, ACTION@SCOPE".to_owned(),
260        ));
261    }
262    for scope in &scopes {
263        let action = ACTIONS
264            .iter()
265            .find(|action| **action == scope.action)
266            .copied()
267            .ok_or_else(|| AdminError::Refused(format!("{:?} is not an action", scope.action)))?;
268        if !resource_action_allowed(&gateway, person.clone(), scope.scope.clone(), action).await? {
269            return Err(AdminError::Refused(format!(
270                "you do not hold {scope}, so a key cannot"
271            )));
272        }
273    }
274    let now = unix_timestamp()?;
275    let lifetime = match body.expires_in {
276        Some(seconds) if seconds.is_nan() || seconds < 0.0 => {
277            return Err(AdminError::Refused(
278                "expires_in must be seconds, not negative".to_owned(),
279            ));
280        }
281        Some(seconds) => seconds,
282        None => keys.lifetime,
283    };
284    let expires_at = (lifetime > 0.0).then_some(now + lifetime);
285    let account = format!("{PERSONAL_PREFIX}{}", Uuid::new_v4().simple());
286    let put = AccountPut {
287        name: account.clone(),
288        expires_unix: expires_at.map(|at| at.ceil() as i64),
289        ..AccountPut::default()
290    };
291    let (id, secret) = {
292        let accounts = keys.accounts.clone();
293        let account = account.clone();
294        tokio::task::spawn_blocking(move || {
295            let secret = accounts.put(put)?.secret;
296            let id = accounts
297                .accounts()?
298                .into_iter()
299                .find(|info| info.name == account)
300                .map(|info| info.id);
301            Ok::<_, ai6::guatiao::library::ProviderError>((id, secret))
302        })
303        .await
304        .map_err(|_| AdminError::Api(ApiError::internal()))?
305        .map_err(|error| AdminError::Refused(error.to_string()))?
306    };
307    let (Some(id), Some(secret)) = (id, secret) else {
308        remove_account(&keys, &account).await;
309        return Err(AdminError::Api(ApiError::internal()));
310    };
311    let mut record = ApiKeyRecord::new(
312        id,
313        account.clone(),
314        person.id.clone(),
315        person
316            .display_name
317            .clone()
318            .unwrap_or_else(|| person.name.clone()),
319        body.name.trim(),
320        scopes.iter().map(ToString::to_string).collect(),
321        now,
322    );
323    record.expires_at = expires_at;
324    let stored = {
325        let (registry, record) = (registry.clone(), record.clone());
326        tokio::task::spawn_blocking(move || registry.put_api_key(&record))
327            .await
328            .map_err(|_| AdminError::Api(ApiError::internal()))?
329    };
330    if stored.is_err() {
331        remove_account(&keys, &account).await;
332        return Err(AdminError::Api(ApiError::internal()));
333    }
334    audit(
335        &gateway,
336        &person,
337        "key.create",
338        &format!(
339            "{} {} ({})",
340            record.id,
341            record.name,
342            record.scopes.join(", ")
343        ),
344    )
345    .await?;
346    Ok((
347        StatusCode::CREATED,
348        Json(CreatedKey {
349            key: record.into(),
350            secret,
351        }),
352    ))
353}
354
355/// Removes the key provider's account `account`, as far as it can be.
356async fn remove_account(keys: &KeyProvider, account: &str) {
357    let (accounts, account) = (keys.accounts.clone(), account.to_owned());
358    let _ = tokio::task::spawn_blocking(move || accounts.remove(account)).await;
359}
360
361#[derive(Serialize)]
362pub(crate) struct Revoked {
363    revoked: bool,
364}
365
366/// `DELETE /v1/user/keys/{id}`: ends a key now. A person revokes their own; an administrator
367/// (`account.manage` at `config:accounts`) anyone's. Another person's key is not found.
368pub(crate) async fn revoke(
369    State(gateway): State<Gateway>,
370    headers: HeaderMap,
371    Path(id): Path<String>,
372) -> Result<Json<Revoked>, AdminError> {
373    let person = resolve_signed_in(&gateway, bearer(&headers)?).await?;
374    let keys = key_provider(&gateway)?;
375    let registry = registry(&gateway)?;
376    let found = {
377        let (registry, id) = (registry.clone(), id.clone());
378        tokio::task::spawn_blocking(move || registry.api_key(&id))
379            .await
380            .map_err(|_| AdminError::Api(ApiError::internal()))?
381            .map_err(|_| AdminError::Api(ApiError::not_found()))?
382    };
383    let Some(record) = found else {
384        return Err(ApiError::not_found().into());
385    };
386    if record.owner != person.id && !is_administrator(&gateway, &person).await? {
387        return Err(ApiError::not_found().into());
388    }
389    // The account goes first: from that moment the provider refuses the key.
390    let (accounts, account) = (keys.accounts.clone(), record.account.clone());
391    tokio::task::spawn_blocking(move || accounts.remove(account))
392        .await
393        .map_err(|_| AdminError::Api(ApiError::internal()))?
394        .or_else(|error| {
395            if error.status == ai6::guatiao::Status::GUATIAO_ERR_NOT_FOUND {
396                Ok(())
397            } else {
398                Err(AdminError::Api(ApiError::unavailable()))
399            }
400        })?;
401    {
402        let (registry, id) = (registry.clone(), id.clone());
403        tokio::task::spawn_blocking(move || registry.remove_api_key(&id))
404            .await
405            .map_err(|_| AdminError::Api(ApiError::internal()))?
406            .map_err(|_| AdminError::Api(ApiError::internal()))?;
407    }
408    audit(
409        &gateway,
410        &person,
411        "key.revoke",
412        &format!("{} {} of {}", record.id, record.name, record.owner),
413    )
414    .await?;
415    Ok(Json(Revoked { revoked: true }))
416}
417
418impl std::fmt::Debug for KeyProvider {
419    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420        formatter.write_str("KeyProvider([REDACTED])")
421    }
422}