Skip to main content

universal_exports/
access_admin.rs

1//! The access policy the gateway enforces, and the routes that read and change it.
2//!
3//! [`LiveAccess`] holds the compiled policy and swaps it when the configuration provider's
4//! `access` and `operation_access` records change; a record that does not compile is kept out
5//! and the last good one stays in force. The routes read the stored records fresh and write
6//! them with a compare-and-swap against the revision the caller read, so two editors never
7//! overwrite each other.
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::fmt::Write as _;
11use std::sync::{Arc, PoisonError, RwLock};
12
13use ai6::directorates::m::records::EditorForm;
14use ai6::directorates::registry::backend::RegistryBackend;
15use ai6::wire::access::{
16    AccessView, Binding, Changed, Checked, ChiefBody, ChiefView, DelegableBody, DelegableView,
17    Inherited, OperationView, OrphanView, RoleView, RulesBody,
18};
19use ai6::wire::refusal::Refusal;
20use ai6::{
21    ACTIONS, AccessPolicy, AccessSet, AuditRecord, AuthorizationDecision, AuthorizationRequest,
22    Authorizer, CONFIG_ACCESS, ConfigProvider, ConfigRecord, ConfigScope, ConfigSnapshot, Editor,
23    EffectiveAccess, Lineage, Lookup, NOT_DELEGABLE, OperationAccess, Orphan, Person, RoleDef,
24    RosterErrorKind, RuleDef, TierKind, check_change, check_operation_change,
25    compile_with_operations, seeded_policy,
26};
27use axum::Json;
28use axum::extract::{Path, Query, State};
29use axum::http::{HeaderMap, StatusCode};
30use axum::response::{IntoResponse, Response};
31use serde::Deserialize;
32use sha2::{Digest, Sha256};
33use uuid::Uuid;
34
35use crate::tree::OperationTree;
36use crate::{
37    ApiError, Gateway, authorize_resource_action, bearer, operation_tree, resolve_user,
38    unix_timestamp,
39};
40
41/// The key of the global policy among the `access` family's records.
42const KEY: &str = ConfigRecord::SINGLETON_KEY;
43
44/// An answer that is not a plain [`ApiError`]: the reason is the caller's to read.
45pub(crate) enum AdminError {
46    Api(ApiError),
47    /// 400: the change is refused, with the reason.
48    Refused(String),
49    /// 409: the state is in the way, with the reason.
50    Conflict(String),
51    /// 428: the write named no revision.
52    Required,
53}
54
55impl From<ApiError> for AdminError {
56    fn from(error: ApiError) -> Self {
57        Self::Api(error)
58    }
59}
60
61impl IntoResponse for AdminError {
62    fn into_response(self) -> Response {
63        let (status, reason) = match self {
64            Self::Api(error) => {
65                // The same `{"error": TEXT}` as every other refusal here, so a client reads
66                // the reason of a 401, 403 or 404 as it reads a 400.
67                let retry = error.retry_after_seconds;
68                let mut response = (
69                    error.status,
70                    Json(Refusal {
71                        error: Some(error.message.into_owned()),
72                    }),
73                )
74                    .into_response();
75                if let Some(seconds) = retry {
76                    response.headers_mut().insert(
77                        axum::http::header::RETRY_AFTER,
78                        axum::http::HeaderValue::from(seconds),
79                    );
80                }
81                return response;
82            }
83            Self::Refused(reason) => (StatusCode::BAD_REQUEST, reason),
84            Self::Conflict(reason) => (StatusCode::CONFLICT, reason),
85            Self::Required => (
86                StatusCode::PRECONDITION_REQUIRED,
87                "send the revision you read in If-Match".to_owned(),
88            ),
89        };
90        (
91            status,
92            Json(Refusal {
93                error: Some(reason),
94            }),
95        )
96            .into_response()
97    }
98}
99
100fn internal() -> AdminError {
101    AdminError::Api(ApiError::internal())
102}
103
104/// What the gateway holds of the policy.
105struct Held {
106    lineage: Lineage,
107    policy: AccessPolicy,
108    operations: BTreeMap<String, OperationAccess>,
109    effective: Arc<EffectiveAccess>,
110    invalid: Option<String>,
111    /// The revision whose refusal was last logged.
112    logged: Option<ai6::ConfigRevision>,
113}
114
115/// The policy in force, and the way back to the provider that stores it.
116pub struct LiveAccess {
117    provider: Arc<dyn ConfigProvider>,
118    host_chiefs: Vec<String>,
119    managed_by: Option<String>,
120    state: RwLock<Held>,
121    write: tokio::sync::Mutex<()>,
122}
123
124impl std::fmt::Debug for LiveAccess {
125    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        formatter.debug_struct("LiveAccess").finish_non_exhaustive()
127    }
128}
129
130impl LiveAccess {
131    /// Policy over `provider`'s records, with `host_chiefs` (`[unex.access] chief`) always
132    /// chief. With `managed_by` an authorizer plugin decides and only the chief tier is the
133    /// gateway's own: the routes that change the policy answer 409.
134    pub fn new(
135        provider: Arc<dyn ConfigProvider>,
136        host_chiefs: Vec<String>,
137        managed_by: Option<String>,
138    ) -> Result<Self, String> {
139        let policy = AccessPolicy::default();
140        let effective = ai6::compile(&policy, &host_chiefs).map_err(|error| error.to_string())?;
141        Ok(Self {
142            provider,
143            host_chiefs,
144            managed_by,
145            state: RwLock::new(Held {
146                lineage: Lineage::default(),
147                policy,
148                operations: BTreeMap::new(),
149                effective: Arc::new(effective),
150                invalid: None,
151                logged: None,
152            }),
153            write: tokio::sync::Mutex::new(()),
154        })
155    }
156
157    fn read(&self) -> std::sync::RwLockReadGuard<'_, Held> {
158        self.state.read().unwrap_or_else(PoisonError::into_inner)
159    }
160
161    /// The policy now in force.
162    pub fn effective(&self) -> Arc<EffectiveAccess> {
163        self.read().effective.clone()
164    }
165
166    /// Whether the policy has no chief anywhere: nobody could change access.
167    pub fn has_no_chief(&self) -> bool {
168        self.managed_by.is_none()
169            && self.host_chiefs.is_empty()
170            && self.read().policy.chief.is_empty()
171    }
172
173    /// Takes the records of `snapshot`. A policy that does not compile is kept out, once per
174    /// revision logged, and shown by [`LiveAccess::invalid`]; with none stored the built-in
175    /// roles stand in memory.
176    pub fn apply(&self, snapshot: &ConfigSnapshot) {
177        let stored = if self.managed_by.is_some() {
178            Ok(None)
179        } else {
180            snapshot.settings.access_policy()
181        };
182        let operations = if self.managed_by.is_some() {
183            BTreeMap::new()
184        } else {
185            snapshot.settings.operation_access.clone()
186        };
187        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
188        let compiled = stored.and_then(|policy| {
189            let policy = policy.unwrap_or_else(|| {
190                if self.managed_by.is_some() {
191                    AccessPolicy::default()
192                } else {
193                    seeded_policy()
194                }
195            });
196            compile_with_operations(&policy, &self.host_chiefs, &operations, &state.lineage)
197                .map(|effective| (policy, effective))
198                .map_err(|error| error.to_string())
199        });
200        match compiled {
201            Ok((policy, effective)) => {
202                for (operation, orphans) in effective.orphaned() {
203                    for Orphan { item, reason } in orphans {
204                        if state.logged != Some(snapshot.revision) {
205                            eprintln!(
206                                "universal-exports: access: {operation}: {item} is not applied: {reason}"
207                            );
208                        }
209                    }
210                }
211                state.policy = policy;
212                state.operations = operations;
213                state.effective = Arc::new(effective);
214                state.invalid = None;
215            }
216            Err(reason) => {
217                if state.logged != Some(snapshot.revision) {
218                    eprintln!(
219                        "universal-exports: access: revision {} is invalid, keeping the policy in force: {reason}",
220                        snapshot.revision.get()
221                    );
222                }
223                state.invalid = Some(reason);
224            }
225        }
226        state.logged = Some(snapshot.revision);
227    }
228
229    /// Reads the provider and takes what it holds.
230    ///
231    /// # Errors
232    ///
233    /// The provider's error, as text.
234    pub fn reload(&self) -> Result<(), String> {
235        let snapshot = self.provider.load("").map_err(|error| error.to_string())?;
236        self.apply(&snapshot);
237        Ok(())
238    }
239
240    /// Notes that the provider refused its configuration, so the policy in force is not the
241    /// stored one.
242    pub fn mark_invalid(&self, reason: &str) {
243        self.state
244            .write()
245            .unwrap_or_else(PoisonError::into_inner)
246            .invalid = Some(reason.to_owned());
247    }
248
249    /// Why the stored policy is not in force, when it is not.
250    pub fn invalid(&self) -> Option<String> {
251        self.read().invalid.clone()
252    }
253
254    /// Takes the tree of Operations the Stations last published; the Operation policies are
255    /// recompiled against it when it changed.
256    pub fn observe_lineage(&self, lineage: Lineage) {
257        if self.read().lineage == lineage {
258            return;
259        }
260        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
261        state.lineage = lineage;
262        if let Ok(effective) = compile_with_operations(
263            &state.policy,
264            &self.host_chiefs,
265            &state.operations,
266            &state.lineage,
267        ) {
268            state.effective = Arc::new(effective);
269        }
270    }
271
272    /// Writes the built-in roles as the `access` record when there is none, and says whether
273    /// it did. A record another gateway wrote meanwhile wins and is read.
274    ///
275    /// # Errors
276    ///
277    /// The provider's error, as text, other than "read-only" (the roles stay in memory) and a
278    /// record that appeared meanwhile.
279    pub fn seed(
280        &self,
281        snapshot: &ConfigSnapshot,
282        registry: &Arc<dyn RegistryBackend>,
283    ) -> Result<bool, String> {
284        if self.managed_by.is_some() || snapshot.settings.access.is_some() {
285            return Ok(false);
286        }
287        match self.provider.put_if(
288            ConfigRecord::Access,
289            &ConfigScope::Global,
290            KEY,
291            None,
292            &seeded_policy().to_record(),
293        ) {
294            Ok(_) => {
295                let at = std::time::SystemTime::now()
296                    .duration_since(std::time::UNIX_EPOCH)
297                    .map_err(|error| error.to_string())?
298                    .as_secs_f64();
299                registry
300                    .record_audit(&AuditRecord {
301                        id: Uuid::new_v4().to_string(),
302                        actor: "gateway".to_owned(),
303                        action: "access.seeded".to_owned(),
304                        operation: String::new(),
305                        resource: Some(CONFIG_ACCESS.to_owned()),
306                        target: "roles controller operator auditor".to_owned(),
307                        at,
308                    })
309                    .map_err(|error| format!("auditing the seeded policy failed: {error}"))?;
310                Ok(true)
311            }
312            Err(error) if error.kind() == RosterErrorKind::ReadOnly => {
313                eprintln!(
314                    "universal-exports: access: no stored policy; seeded roles kept in memory (provider is read-only)"
315                );
316                Ok(false)
317            }
318            Err(error) if error.kind() == RosterErrorKind::Conflict => Ok(false),
319            Err(error) => Err(error.to_string()),
320        }
321    }
322}
323
324impl Authorizer for LiveAccess {
325    fn authorize(
326        &self,
327        request: AuthorizationRequest,
328    ) -> Result<AuthorizationDecision, ai6::guatiao::library::ProviderError> {
329        self.effective().authorize(request)
330    }
331}
332
333/// Allows what either allows: the chief and Operation tiers of the gateway, or an authorizer
334/// plugin.
335pub struct EitherAuthorizer {
336    /// The gateway's own tiers.
337    pub live: Arc<LiveAccess>,
338    /// The plugin.
339    pub plugin: Arc<dyn Authorizer>,
340}
341
342impl std::fmt::Debug for EitherAuthorizer {
343    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        formatter
345            .debug_struct("EitherAuthorizer")
346            .finish_non_exhaustive()
347    }
348}
349
350impl Authorizer for EitherAuthorizer {
351    fn authorize(
352        &self,
353        request: AuthorizationRequest,
354    ) -> Result<AuthorizationDecision, ai6::guatiao::library::ProviderError> {
355        if self.live.authorize(request.clone())?.allowed {
356            return Ok(AuthorizationDecision {
357                allowed: true,
358                ..AuthorizationDecision::default()
359            });
360        }
361        self.plugin.authorize(request)
362    }
363}
364
365/// The revision of one stored record: `0` when there is none, else a digest of it.
366pub(crate) fn token(record: Option<&ai6::StoredRecord>) -> String {
367    let Some(record) = record else {
368        return "0".to_owned();
369    };
370    let mut hex = String::new();
371    for byte in &Sha256::digest(record.to_string().as_bytes())[..12] {
372        let _ = write!(hex, "{byte:02x}");
373    }
374    hex
375}
376
377/// The records as the provider holds them now.
378struct Current {
379    policy: Option<AccessPolicy>,
380    stored: Option<ai6::StoredRecord>,
381    operations: BTreeMap<String, OperationAccess>,
382    operation_stored: BTreeMap<String, ai6::StoredRecord>,
383    writable: bool,
384}
385
386impl Current {
387    /// The policy a write starts from: what is stored, else the built-in roles that stand.
388    fn policy(&self) -> AccessPolicy {
389        self.policy.clone().unwrap_or_else(seeded_policy)
390    }
391}
392
393async fn read_current(live: &Arc<LiveAccess>) -> Result<Current, AdminError> {
394    let live = live.clone();
395    tokio::task::spawn_blocking(move || {
396        let global = live
397            .provider
398            .definitions(ConfigRecord::Access, &ConfigScope::Global);
399        let operations = live
400            .provider
401            .definitions(ConfigRecord::OperationAccess, &ConfigScope::Global);
402        match (global, operations) {
403            (Ok(global), Ok(operations)) => {
404                let stored = global
405                    .records
406                    .into_iter()
407                    .find(|(key, _)| key == KEY)
408                    .map(|(_, definition)| definition);
409                let policy = stored
410                    .as_ref()
411                    .map(AccessPolicy::from_record)
412                    .transpose()
413                    .map_err(|error| AdminError::Conflict(error.to_string()))?;
414                let mut records = BTreeMap::new();
415                let mut raw = BTreeMap::new();
416                for (key, definition) in operations.records {
417                    let record = OperationAccess::from_record(&definition)
418                        .map_err(|error| AdminError::Conflict(error.to_string()))?;
419                    records.insert(key.clone(), record);
420                    raw.insert(key, definition);
421                }
422                Ok(Current {
423                    policy,
424                    stored,
425                    operations: records,
426                    operation_stored: raw,
427                    writable: global.writable && operations.writable,
428                })
429            }
430            _ => {
431                let state = live.read();
432                Ok(Current {
433                    policy: Some(state.policy.clone()),
434                    stored: None,
435                    operations: state.operations.clone(),
436                    operation_stored: BTreeMap::new(),
437                    writable: false,
438                })
439            }
440        }
441    })
442    .await
443    .map_err(|_| internal())?
444}
445
446/// The revision a write names: `If-Match`, else `?revision=` (what a proposal carries).
447pub(crate) fn revision_of(headers: &HeaderMap, query: &WriteQuery) -> Result<String, AdminError> {
448    headers
449        .get("if-match")
450        .and_then(|value| value.to_str().ok())
451        .map(|value| value.trim().trim_matches('"').to_owned())
452        .or_else(|| query.revision.clone())
453        .ok_or(AdminError::Required)
454}
455
456/// `?revision=`.
457#[derive(Debug, Default, Deserialize)]
458pub(crate) struct WriteQuery {
459    revision: Option<String>,
460}
461
462fn checked_name(gateway: &Gateway, name: &str) -> Result<(), AdminError> {
463    if name.trim().is_empty()
464        || !gateway
465            .config
466            .unex()
467            .text
468            .access_name_bytes
469            .allows(name.len())
470        || name.chars().any(|c| c.is_control() || c.is_whitespace())
471    {
472        Err(AdminError::Api(ApiError::bad_request()))
473    } else {
474        Ok(())
475    }
476}
477
478pub(crate) async fn audit(
479    gateway: &Gateway,
480    person: &Person,
481    action: &str,
482    operation: Option<&str>,
483    resource: &str,
484    target: &str,
485) -> Result<(), AdminError> {
486    let registry = gateway
487        .registry
488        .clone()
489        .ok_or_else(|| AdminError::Api(ApiError::unavailable()))?;
490    let record = AuditRecord {
491        id: Uuid::new_v4().to_string(),
492        actor: crate::actor_of(person),
493        action: action.to_owned(),
494        operation: operation.unwrap_or_default().to_owned(),
495        resource: Some(resource.to_owned()),
496        target: crate::roster::bounded(target, gateway.config.unex().text.roster_target_bytes),
497        at: unix_timestamp()?,
498    };
499    tokio::task::spawn_blocking(move || registry.record_audit(&record))
500        .await
501        .map_err(|_| internal())?
502        .map_err(|_| internal())
503}
504
505pub(crate) fn live(gateway: &Gateway) -> Result<Arc<LiveAccess>, AdminError> {
506    gateway
507        .access_admin
508        .clone()
509        .ok_or(AdminError::Api(ApiError::unavailable()))
510}
511
512fn writable(live: &LiveAccess) -> Result<(), AdminError> {
513    match &live.managed_by {
514        Some(id) => Err(AdminError::Conflict(format!(
515            "access is managed by authorizer {id}"
516        ))),
517        None => Ok(()),
518    }
519}
520
521fn role_views(roles: &BTreeMap<String, RoleDef>) -> Vec<RoleView> {
522    let mut views = vec![RoleView {
523        name: ai6::CHIEF_ROLE.to_owned(),
524        built_in: true,
525        editable: false,
526        role: RoleDef {
527            description: Some("Holds every action; named only in the chief list".to_owned()),
528            ..RoleDef::new(ACTIONS.iter().copied())
529        },
530    }];
531    views.extend(roles.iter().map(|(name, role)| RoleView {
532        name: name.clone(),
533        built_in: ai6::RESERVED_ROLES.contains(&name.as_str()),
534        editable: true,
535        role: role.clone(),
536    }));
537    views
538}
539
540fn delegable_view(policy: &AccessPolicy) -> DelegableView {
541    let set = policy.delegable_set();
542    DelegableView {
543        weakenings: NOT_DELEGABLE
544            .iter()
545            .filter(|action| set.contains(**action))
546            .map(|action| (*action).to_owned())
547            .collect(),
548        actions: set.into_iter().collect(),
549        default: policy.delegable.is_none(),
550    }
551}
552
553/// `GET /v1/user/access`: needs `access.read` at `config:access`.
554pub(crate) async fn read_global_policy(
555    State(gateway): State<Gateway>,
556    headers: HeaderMap,
557) -> Result<Json<AccessView>, AdminError> {
558    let person = resolve_user(&gateway, bearer(&headers)?).await?;
559    authorize_resource_action(&gateway, person, CONFIG_ACCESS.to_owned(), "access.read").await?;
560    let live = live(&gateway)?;
561    let current = read_current(&live).await?;
562    let policy = current.policy();
563    let (host, stored) = (live.host_chiefs.clone(), policy.chief.clone());
564    Ok(Json(AccessView {
565        revision: token(current.stored.as_ref()),
566        writable: current.writable && live.managed_by.is_none(),
567        managed_by: live.managed_by.clone(),
568        roles: role_views(&policy.roles),
569        delegable: delegable_view(&policy),
570        rules: policy.rules,
571        chief: ChiefView { stored, host },
572        invalid: live.invalid(),
573    }))
574}
575
576/// The editing schemas for the global access policy.
577pub(crate) async fn global_form(
578    State(gateway): State<Gateway>,
579    headers: HeaderMap,
580    Path(kind): Path<String>,
581) -> Result<Json<ai6::RecordForm>, AdminError> {
582    let person = resolve_user(&gateway, bearer(&headers)?).await?;
583    authorize_resource_action(&gateway, person, CONFIG_ACCESS.to_owned(), "access.manage").await?;
584    access_form(&kind)
585}
586
587/// The same editing schemas for an Operation's own access policy.
588pub(crate) async fn operation_form(
589    State(gateway): State<Gateway>,
590    headers: HeaderMap,
591    Path((operation, kind)): Path<(String, String)>,
592) -> Result<Json<ai6::RecordForm>, AdminError> {
593    let person = resolve_user(&gateway, bearer(&headers)?).await?;
594    known_operation(&gateway, &operation).await?;
595    let resource = crate::tree::operation_resource(&operation);
596    authorize_resource_action(&gateway, person, resource, "access.manage").await?;
597    access_form(&kind)
598}
599
600fn access_form(kind: &str) -> Result<Json<ai6::RecordForm>, AdminError> {
601    let form = match kind {
602        "roles" => EditorForm::AccessRole,
603        "rules" => EditorForm::AccessRule,
604        _ => return Err(ApiError::not_found().into()),
605    };
606    form.form().map(Json).map_err(|_| internal())
607}
608
609/// Marks the rules of `after` that are not in `before` as written now by `person`; one that
610/// stays keeps its editor.
611fn stamp(before: &[RuleDef], after: &mut [RuleDef], person: &Person, now: f64) {
612    for rule in after {
613        let kept = before.iter().find(|old| {
614            old.subject == rule.subject
615                && old.scope == rule.scope
616                && old.role == rule.role
617                && old.propagate == rule.propagate
618        });
619        match kept {
620            Some(old) => {
621                rule.editor.clone_from(&old.editor);
622                rule.changed_unix = old.changed_unix;
623            }
624            None => {
625                rule.editor = Some(person.name.clone());
626                rule.changed_unix = Some(now as u64);
627            }
628        }
629    }
630}
631
632type Mutation = Box<dyn FnOnce(&mut AccessPolicy) -> Result<String, AdminError> + Send>;
633
634/// Changes the global policy: `access.manage` on it, the named revision, the guard, a
635/// compare-and-swap write, the audit record, then the policy in force.
636async fn write_global(
637    gateway: Gateway,
638    headers: HeaderMap,
639    query: WriteQuery,
640    action: &'static str,
641    mutation: Mutation,
642) -> Result<Json<Changed>, AdminError> {
643    let person = resolve_user(&gateway, bearer(&headers)?).await?;
644    let live = live(&gateway)?;
645    writable(&live)?;
646    authorize_resource_action(
647        &gateway,
648        person.clone(),
649        CONFIG_ACCESS.to_owned(),
650        "access.manage",
651    )
652    .await?;
653    let expected = revision_of(&headers, &query)?;
654    let _turn = live.write.lock().await;
655    let current = read_current(&live).await?;
656    if !current.writable {
657        return Err(AdminError::Conflict(
658            "the configuration provider is read-only".to_owned(),
659        ));
660    }
661    if token(current.stored.as_ref()) != expected {
662        return Err(AdminError::Conflict(
663            "the access policy changed since you read it; reload it".to_owned(),
664        ));
665    }
666    let before = current.policy();
667    let mut after = before.clone();
668    let target = mutation(&mut after)?;
669    let now = unix_timestamp()?;
670    stamp(&before.rules, &mut after.rules, &person, now);
671    let effective = live.effective();
672    let lineage = live.read().lineage.clone();
673    let editor = Editor::new(person.clone(), &effective);
674    if let Err(refusal) = check_change(&before, &after, &editor, &effective, &lineage) {
675        audit(
676            &gateway,
677            &person,
678            "access.refused",
679            None,
680            CONFIG_ACCESS,
681            &format!("{target}: {}", refusal.reason),
682        )
683        .await?;
684        return Err(AdminError::Refused(refusal.reason));
685    }
686    let definition = after.to_record();
687    let swapped = {
688        let (live, stored, definition) = (live.clone(), current.stored.clone(), definition.clone());
689        tokio::task::spawn_blocking(move || {
690            live.provider.put_if(
691                ConfigRecord::Access,
692                &ConfigScope::Global,
693                KEY,
694                stored.as_ref(),
695                &definition,
696            )
697        })
698        .await
699        .map_err(|_| internal())?
700    };
701    match swapped {
702        Ok(_) => {}
703        Err(error) => {
704            return Err(match error.kind() {
705                RosterErrorKind::Conflict => AdminError::Conflict(
706                    "the access policy changed since you read it; reload it".to_owned(),
707                ),
708                RosterErrorKind::ReadOnly => {
709                    AdminError::Conflict("the configuration provider is read-only".to_owned())
710                }
711                RosterErrorKind::Invalid => {
712                    audit(
713                        &gateway,
714                        &person,
715                        "access.refused",
716                        None,
717                        CONFIG_ACCESS,
718                        &format!("{target}: {error}"),
719                    )
720                    .await?;
721                    AdminError::Refused(error.to_string())
722                }
723                _ => AdminError::Api(ApiError::unavailable()),
724            });
725        }
726    }
727    audit(&gateway, &person, action, None, CONFIG_ACCESS, &target).await?;
728    let _ = live.reload();
729    Ok(Json(Changed {
730        revision: token(Some(&definition)),
731    }))
732}
733
734/// `PUT /v1/user/access/roles/{role}`: sets one role's actions (and description).
735pub(crate) async fn put_role(
736    State(gateway): State<Gateway>,
737    headers: HeaderMap,
738    Query(query): Query<WriteQuery>,
739    Path(role): Path<String>,
740    Json(body): Json<RoleDef>,
741) -> Result<Json<Changed>, AdminError> {
742    checked_name(&gateway, &role)?;
743    write_global(
744        gateway,
745        headers,
746        query,
747        "access.update",
748        Box::new(move |policy| {
749            policy.roles.insert(role.clone(), body);
750            Ok(format!("role {role}"))
751        }),
752    )
753    .await
754}
755
756/// `DELETE /v1/user/access/roles/{role}`: a role a rule names cannot be deleted (409).
757pub(crate) async fn delete_role(
758    State(gateway): State<Gateway>,
759    headers: HeaderMap,
760    Query(query): Query<WriteQuery>,
761    Path(role): Path<String>,
762) -> Result<Json<Changed>, AdminError> {
763    checked_name(&gateway, &role)?;
764    write_global(
765        gateway,
766        headers,
767        query,
768        "access.remove",
769        Box::new(move |policy| {
770            if policy.roles.remove(&role).is_none() {
771                return Err(AdminError::Api(ApiError::not_found()));
772            }
773            let used: Vec<String> = policy
774                .rules
775                .iter()
776                .enumerate()
777                .filter(|(_, rule)| rule.role == role)
778                .map(|(index, _)| format!("rule {index}"))
779                .collect();
780            if used.is_empty() {
781                Ok(format!("role {role}"))
782            } else {
783                Err(AdminError::Conflict(format!(
784                    "role {role} is named by {}",
785                    used.join(", ")
786                )))
787            }
788        }),
789    )
790    .await
791}
792
793/// `PUT /v1/user/access/rules`: replaces the whole ordered list.
794pub(crate) async fn put_rules(
795    State(gateway): State<Gateway>,
796    headers: HeaderMap,
797    Query(query): Query<WriteQuery>,
798    Json(body): Json<RulesBody>,
799) -> Result<Json<Changed>, AdminError> {
800    write_global(
801        gateway,
802        headers,
803        query,
804        "access.update",
805        Box::new(move |policy| {
806            policy.rules = body
807                .rules
808                .into_iter()
809                .map(|rule| {
810                    let mut def = RuleDef::new(rule.subject, rule.scope, rule.role);
811                    def.propagate = rule.propagate;
812                    def
813                })
814                .collect();
815            Ok("rules".to_owned())
816        }),
817    )
818    .await
819}
820
821/// `PUT /v1/user/access/delegable`: sets the cap (`null` for the default).
822pub(crate) async fn put_delegable(
823    State(gateway): State<Gateway>,
824    headers: HeaderMap,
825    Query(query): Query<WriteQuery>,
826    Json(body): Json<DelegableBody>,
827) -> Result<Json<Changed>, AdminError> {
828    write_global(
829        gateway,
830        headers,
831        query,
832        "access.update",
833        Box::new(move |policy| {
834            policy.delegable = body.actions;
835            Ok("delegable".to_owned())
836        }),
837    )
838    .await
839}
840
841/// `PUT /v1/user/access/chief`: sets the stored chief list.
842pub(crate) async fn put_chief(
843    State(gateway): State<Gateway>,
844    headers: HeaderMap,
845    Query(query): Query<WriteQuery>,
846    Json(body): Json<ChiefBody>,
847) -> Result<Json<Changed>, AdminError> {
848    write_global(
849        gateway,
850        headers,
851        query,
852        "access.update",
853        Box::new(move |policy| {
854            policy.chief = body.chief;
855            Ok("chief".to_owned())
856        }),
857    )
858    .await
859}
860
861// ---- Operation policies -------------------------------------------------------------------
862
863async fn known_operation(gateway: &Gateway, operation: &str) -> Result<OperationTree, AdminError> {
864    checked_name(gateway, operation)?;
865    let tree = operation_tree(gateway).await?;
866    if tree.operations().any(|known| known == operation) {
867        Ok(tree)
868    } else {
869        Err(AdminError::Api(ApiError::not_found()))
870    }
871}
872
873/// `GET /v1/user/operations/{op}/access`: needs `access.read` at the Operation.
874pub(crate) async fn read_operation_policy(
875    State(gateway): State<Gateway>,
876    headers: HeaderMap,
877    Path(operation): Path<String>,
878) -> Result<Json<OperationView>, AdminError> {
879    let person = resolve_user(&gateway, bearer(&headers)?).await?;
880    let tree = known_operation(&gateway, &operation).await?;
881    let resource = crate::tree::operation_resource(&operation);
882    authorize_resource_action(&gateway, person.clone(), resource, "access.read").await?;
883    let live = live(&gateway)?;
884    let current = read_current(&live).await?;
885    let policy = current.policy();
886    let record = current
887        .operations
888        .get(&operation)
889        .cloned()
890        .unwrap_or_default();
891    // An ancestor is named only to someone who may read its Missions.
892    let mut visible = BTreeSet::new();
893    for ancestor in tree.ancestors(&operation) {
894        let allowed = authorize_resource_action(
895            &gateway,
896            person.clone(),
897            crate::tree::operation_resource(ancestor),
898            "mission.read",
899        )
900        .await
901        .is_ok();
902        if allowed {
903            visible.insert(ancestor.clone());
904        }
905    }
906    let mut inherited = Vec::new();
907    let mut bindings = Vec::new();
908    for ancestor in tree.ancestors(&operation) {
909        if let Some(parent) = current.operations.get(ancestor) {
910            let shown = visible.contains(ancestor);
911            for (name, role) in &parent.roles {
912                if shown {
913                    inherited.push(Inherited {
914                        role: name.clone(),
915                        from: ancestor.clone(),
916                        actions: role.actions.clone(),
917                    });
918                }
919            }
920            for rule in &parent.rules {
921                if rule.scope == format!("operation:{operation}")
922                    || (rule.propagate
923                        && tree.in_subtree(&operation, rule.scope.trim_start_matches("operation:")))
924                {
925                    bindings.push(Binding {
926                        subject: rule.subject.clone(),
927                        role: rule.role.clone(),
928                        tier: "ancestor".to_owned(),
929                        scope: shown.then(|| rule.scope.clone()),
930                    });
931                }
932            }
933        }
934    }
935    for rule in &record.rules {
936        if rule.scope == format!("operation:{operation}")
937            || (rule.propagate
938                && tree.in_subtree(&operation, rule.scope.trim_start_matches("operation:")))
939        {
940            bindings.push(Binding {
941                subject: rule.subject.clone(),
942                role: rule.role.clone(),
943                tier: "operation".to_owned(),
944                scope: Some(rule.scope.clone()),
945            });
946        }
947    }
948    for rule in &policy.rules {
949        let at = rule.scope.strip_prefix("operation:");
950        let reaches = rule.scope == "*"
951            || at == Some(operation.as_str())
952            || (rule.propagate
953                && at.is_some_and(|id| tree.ancestors(&operation).iter().any(|a| a == id)));
954        if reaches {
955            let hidden_ancestor = at.is_some_and(|id| id != operation && !visible.contains(id));
956            bindings.push(Binding {
957                subject: rule.subject.clone(),
958                role: rule.role.clone(),
959                tier: "global".to_owned(),
960                scope: (!hidden_ancestor).then(|| rule.scope.clone()),
961            });
962        }
963    }
964    let effective = live.effective();
965    let orphaned = effective
966        .orphaned()
967        .get(&operation)
968        .into_iter()
969        .flatten()
970        .map(|orphan| OrphanView {
971            item: orphan.item.clone(),
972            reason: orphan.reason.clone(),
973        })
974        .collect();
975    Ok(Json(OperationView {
976        operation_id: operation.clone(),
977        revision: token(current.operation_stored.get(&operation)),
978        writable: current.writable && live.managed_by.is_none(),
979        managed_by: live.managed_by.clone(),
980        roles: role_views_operation(&record.roles),
981        rules: record.rules,
982        inherited,
983        orphaned,
984        bindings,
985        delegable: policy.delegable_set().into_iter().collect(),
986    }))
987}
988
989fn role_views_operation(roles: &BTreeMap<String, RoleDef>) -> Vec<RoleView> {
990    roles
991        .iter()
992        .map(|(name, role)| RoleView {
993            name: name.clone(),
994            built_in: false,
995            editable: true,
996            role: role.clone(),
997        })
998        .collect()
999}
1000
1001type OperationMutation = Box<dyn FnOnce(&mut OperationAccess) -> Result<String, AdminError> + Send>;
1002
1003/// Changes one Operation's record: `access.manage` there, the named revision, the delegation
1004/// guard, a compare-and-swap write and the audit record.
1005async fn write_operation(
1006    gateway: Gateway,
1007    headers: HeaderMap,
1008    query: WriteQuery,
1009    operation: String,
1010    action: &'static str,
1011    mutation: OperationMutation,
1012) -> Result<Json<Changed>, AdminError> {
1013    let person = resolve_user(&gateway, bearer(&headers)?).await?;
1014    let live = live(&gateway)?;
1015    writable(&live)?;
1016    let tree = known_operation(&gateway, &operation).await?;
1017    let resource = crate::tree::operation_resource(&operation);
1018    authorize_resource_action(&gateway, person.clone(), resource.clone(), "access.manage").await?;
1019    let expected = revision_of(&headers, &query)?;
1020    let _turn = live.write.lock().await;
1021    let current = read_current(&live).await?;
1022    if !current.writable {
1023        return Err(AdminError::Conflict(
1024            "the configuration provider is read-only".to_owned(),
1025        ));
1026    }
1027    let stored = current.operation_stored.get(&operation).cloned();
1028    if token(stored.as_ref()) != expected {
1029        return Err(AdminError::Conflict(
1030            "the Operation's access changed since you read it; reload it".to_owned(),
1031        ));
1032    }
1033    let before = current
1034        .operations
1035        .get(&operation)
1036        .cloned()
1037        .unwrap_or_default();
1038    let mut after = before.clone();
1039    let target = mutation(&mut after)?;
1040    let now = unix_timestamp()?;
1041    stamp(&before.rules, &mut after.rules, &person, now);
1042    let policy = current.policy();
1043    let lineage = tree_lineage(&tree);
1044    let effective = live.effective();
1045    let editor = Editor::new(person.clone(), &effective);
1046    let set = AccessSet {
1047        global: &policy,
1048        operations: &current.operations,
1049        lineage: &lineage,
1050    };
1051    if let Err(refusal) =
1052        check_operation_change(&operation, &before, &after, &editor, &effective, &set)
1053    {
1054        audit(
1055            &gateway,
1056            &person,
1057            "access.refused",
1058            Some(&operation),
1059            CONFIG_ACCESS,
1060            &format!("{target}: {}", refusal.reason),
1061        )
1062        .await?;
1063        return Err(AdminError::Refused(refusal.reason));
1064    }
1065    let definition = after.to_record();
1066    let swapped = {
1067        let (live, operation, stored, definition) = (
1068            live.clone(),
1069            operation.clone(),
1070            stored.clone(),
1071            definition.clone(),
1072        );
1073        tokio::task::spawn_blocking(move || {
1074            live.provider.put_if(
1075                ConfigRecord::OperationAccess,
1076                &ConfigScope::Global,
1077                &operation,
1078                stored.as_ref(),
1079                &definition,
1080            )
1081        })
1082        .await
1083        .map_err(|_| internal())?
1084    };
1085    if let Err(error) = swapped {
1086        return Err(match error.kind() {
1087            RosterErrorKind::Conflict => AdminError::Conflict(
1088                "the Operation's access changed since you read it; reload it".to_owned(),
1089            ),
1090            RosterErrorKind::ReadOnly => {
1091                AdminError::Conflict("the configuration provider is read-only".to_owned())
1092            }
1093            RosterErrorKind::Invalid => AdminError::Refused(error.to_string()),
1094            _ => AdminError::Api(ApiError::unavailable()),
1095        });
1096    }
1097    audit(
1098        &gateway,
1099        &person,
1100        action,
1101        Some(&operation),
1102        CONFIG_ACCESS,
1103        &target,
1104    )
1105    .await?;
1106    let _ = live.reload();
1107    Ok(Json(Changed {
1108        revision: token(Some(&definition)),
1109    }))
1110}
1111
1112/// The tree as the policy sees it.
1113pub(crate) fn tree_lineage(tree: &OperationTree) -> Lineage {
1114    Lineage::new(
1115        tree.operations()
1116            .map(|operation| (operation.to_owned(), tree.ancestors(operation).to_vec())),
1117    )
1118}
1119
1120/// `PUT /v1/user/operations/{op}/access/roles/{role}`.
1121pub(crate) async fn put_operation_role(
1122    State(gateway): State<Gateway>,
1123    headers: HeaderMap,
1124    Query(query): Query<WriteQuery>,
1125    Path((operation, role)): Path<(String, String)>,
1126    Json(body): Json<RoleDef>,
1127) -> Result<Json<Changed>, AdminError> {
1128    checked_name(&gateway, &role)?;
1129    write_operation(
1130        gateway,
1131        headers,
1132        query,
1133        operation,
1134        "access.update",
1135        Box::new(move |record| {
1136            record.roles.insert(role.clone(), body);
1137            Ok(format!("role {role}"))
1138        }),
1139    )
1140    .await
1141}
1142
1143/// `DELETE /v1/user/operations/{op}/access/roles/{role}`.
1144pub(crate) async fn delete_operation_role(
1145    State(gateway): State<Gateway>,
1146    headers: HeaderMap,
1147    Query(query): Query<WriteQuery>,
1148    Path((operation, role)): Path<(String, String)>,
1149) -> Result<Json<Changed>, AdminError> {
1150    checked_name(&gateway, &role)?;
1151    write_operation(
1152        gateway,
1153        headers,
1154        query,
1155        operation,
1156        "access.remove",
1157        Box::new(move |record| {
1158            if record.roles.remove(&role).is_none() {
1159                return Err(AdminError::Api(ApiError::not_found()));
1160            }
1161            let used: Vec<String> = record
1162                .rules
1163                .iter()
1164                .enumerate()
1165                .filter(|(_, rule)| rule.role == role)
1166                .map(|(index, _)| format!("rule {index}"))
1167                .collect();
1168            if used.is_empty() {
1169                Ok(format!("role {role}"))
1170            } else {
1171                Err(AdminError::Conflict(format!(
1172                    "role {role} is named by {}",
1173                    used.join(", ")
1174                )))
1175            }
1176        }),
1177    )
1178    .await
1179}
1180
1181/// `PUT /v1/user/operations/{op}/access/rules`.
1182pub(crate) async fn put_operation_rules(
1183    State(gateway): State<Gateway>,
1184    headers: HeaderMap,
1185    Query(query): Query<WriteQuery>,
1186    Path(operation): Path<String>,
1187    Json(body): Json<RulesBody>,
1188) -> Result<Json<Changed>, AdminError> {
1189    write_operation(
1190        gateway,
1191        headers,
1192        query,
1193        operation,
1194        "access.update",
1195        Box::new(move |record| {
1196            record.rules = body
1197                .rules
1198                .into_iter()
1199                .map(|rule| {
1200                    let mut def = RuleDef::new(rule.subject, rule.scope, rule.role);
1201                    def.propagate = rule.propagate;
1202                    def
1203                })
1204                .collect();
1205            Ok("rules".to_owned())
1206        }),
1207    )
1208    .await
1209}
1210
1211// ---- The check ----------------------------------------------------------------------------
1212
1213/// The query of the check route.
1214#[derive(Deserialize)]
1215pub(crate) struct CheckQuery {
1216    subject: String,
1217    action: String,
1218    resource: String,
1219}
1220
1221/// `GET /v1/user/access/check?subject=&action=&resource=`: needs `access.read` at the
1222/// resource (`config:access` for one that is not an Operation). The subject is read through
1223/// the Directory (`account:` by name, `person:` by ID); a `group:` is a person in that group.
1224pub(crate) async fn check(
1225    State(gateway): State<Gateway>,
1226    headers: HeaderMap,
1227    Query(query): Query<CheckQuery>,
1228) -> Result<Json<Checked>, AdminError> {
1229    let person = resolve_user(&gateway, bearer(&headers)?).await?;
1230    let scope = if query.resource.starts_with("operation:") {
1231        query.resource.clone()
1232    } else {
1233        CONFIG_ACCESS.to_owned()
1234    };
1235    authorize_resource_action(&gateway, person, scope, "access.read").await?;
1236    let live = live(&gateway)?;
1237    let subject: ai6::Subject = query
1238        .subject
1239        .parse()
1240        .map_err(|_| AdminError::Api(ApiError::bad_request()))?;
1241    let directory = gateway
1242        .access
1243        .as_ref()
1244        .ok_or_else(|| AdminError::Api(ApiError::unavailable()))?
1245        .directory
1246        .clone();
1247    let looked = {
1248        let (by, value) = match subject.kind() {
1249            "account" => ("name", subject.value().to_owned()),
1250            "person" => ("id", subject.value().to_owned()),
1251            _ => ("", String::new()),
1252        };
1253        if by.is_empty() {
1254            None
1255        } else {
1256            let by = by.to_owned();
1257            tokio::task::spawn_blocking(move || {
1258                directory.lookup(Lookup {
1259                    by,
1260                    value,
1261                    ..Default::default()
1262                })
1263            })
1264            .await
1265            .map_err(|_| internal())?
1266            .map_err(|_| internal())?
1267        }
1268    };
1269    let subject_person = looked.unwrap_or_else(|| match subject.kind() {
1270        "account" => Person {
1271            name: subject.value().to_owned(),
1272            ..Person::default()
1273        },
1274        "person" => Person {
1275            id: subject.value().to_owned(),
1276            ..Person::default()
1277        },
1278        _ => Person {
1279            groups: vec![subject.value().to_owned()],
1280            ..Person::default()
1281        },
1282    });
1283    let tree = operation_tree(&gateway).await?;
1284    let request =
1285        crate::tree::resource_request(subject_person, &query.action, query.resource, &tree);
1286    let explained = live.effective().explain(&request).map_err(|_| internal())?;
1287    Ok(Json(Checked {
1288        allowed: explained.allowed,
1289        tier: explained.tier.map(|tier| match tier {
1290            TierKind::Chief => "chief".to_owned(),
1291            TierKind::Global => "global".to_owned(),
1292            TierKind::Operation(id) => format!("operation:{id}"),
1293            _ => "unknown".to_owned(),
1294        }),
1295        rule_index: explained.rule_index,
1296        role: explained.role,
1297    }))
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302    use ai6::{MemoryProvider, Roster, Settings};
1303    use serde_json::json;
1304
1305    use super::*;
1306
1307    #[test]
1308    fn an_invalid_stored_policy_keeps_the_previous_one_in_force() {
1309        let provider = Arc::new(MemoryProvider::new(Roster::default()));
1310        let live = LiveAccess::new(provider.clone(), vec!["account:boss".into()], None).unwrap();
1311        let mut good = Settings::default();
1312        good.access = Some(
1313            AccessPolicy::from_record(
1314                &ai6::StoredRecord::from_serde(
1315                    &json!({"role": {"v": {"actions": ["mission.read"]}},
1316                    "rule": [{"subject": "account:ann", "scope": "operation:G", "role": "v"}]}),
1317                )
1318                .unwrap(),
1319            )
1320            .unwrap(),
1321        );
1322        provider.replace_all(Roster::default(), good);
1323        live.reload().unwrap();
1324        let ann = Person {
1325            name: "ann".into(),
1326            ..Person::default()
1327        };
1328        let allowed = |live: &LiveAccess| {
1329            live.authorize(AuthorizationRequest {
1330                person: ann.clone(),
1331                action: "mission.read".into(),
1332                resource: "operation:G".into(),
1333                ancestors: Vec::new(),
1334            })
1335            .unwrap()
1336            .allowed
1337        };
1338        assert!(allowed(&live) && live.invalid().is_none());
1339
1340        let mut bad = Settings::default();
1341        bad.access = Some(
1342            AccessPolicy::from_record(
1343                &ai6::StoredRecord::from_serde(
1344                    &json!({"rule": [{"subject": "account:ann", "scope": "*", "role": "chief"}]}),
1345                )
1346                .unwrap(),
1347            )
1348            .unwrap(),
1349        );
1350        provider.replace_all(Roster::default(), bad);
1351        live.reload().unwrap();
1352        assert!(allowed(&live), "the last good policy stays in force");
1353        assert!(live.invalid().unwrap().contains("chief"));
1354    }
1355}