Skip to main content

universal_exports/
sign_in.rs

1//! Which methods a sign-in may use, from where it is made, and what it still needs.
2//!
3//! The decision belongs to a `coqui_sign_in_policy` provider the `unex` record names
4//! (`sign_in_policy`); with none, each configured method alone is enough, from anywhere.
5//! [`LiveSignIn`] holds the policy in force and swaps it when the record changes. Bearer API
6//! keys are outside it: they are scoped and revocable, and never open a page's sign-in.
7//! The routes read the stored record fresh and write it with a compare-and-swap against the
8//! revision the caller read, so two editors never overwrite each other.
9
10use std::net::SocketAddr;
11use std::sync::{Arc, PoisonError, RwLock};
12
13use ai6::directorates::m::access::{
14    Factor, Person, SignInContext, SignInDecision, SignInPolicy, clients, purposes,
15};
16use ai6::wire::access::{
17    SignInPolicyBody as PolicyBody, SignInPolicyChanged as PolicyChanged,
18    SignInPolicyView as PolicyView,
19};
20use ai6::{
21    CONFIG_ACCESS, ConfigProvider, ConfigRecord, ConfigScope, ProviderConfig, RosterErrorKind,
22    SignInFactor, SignInPolicyProvider, StoredRecord, UnexRecord,
23};
24use axum::Json;
25use axum::extract::{Query, State};
26use axum::http::header::ORIGIN;
27use axum::http::{HeaderMap, StatusCode};
28use coqui_access_signin::SignInRules;
29
30use crate::access_admin::{AdminError, WriteQuery, audit, revision_of, token};
31use crate::{
32    AccessProviders, ApiError, Gateway, authorize_resource_action, bearer, resolve_user,
33    unix_timestamp,
34};
35
36/// The key of the `unex` record, which has one.
37const KEY: &str = ConfigRecord::SINGLETON_KEY;
38
39/// The word for what is signed in to, in a [`SignInContext`]: the gateway's own routes.
40pub(crate) const SERVICE: &str = "unex";
41
42/// The word for what is signed in to when a page is asked for.
43pub(crate) const PAGES: &str = "pages";
44
45/// Builds a sign-in policy provider from the `unex` record's `sign_in_policy`: the provider's
46/// configuration checked against the provider's own schema, so a policy that does not build is
47/// refused before it is stored or put in force.
48pub trait SignInLoader: Send + Sync {
49    /// The policy provider `provider` configured with `config`, or why it cannot be built.
50    ///
51    /// # Errors
52    ///
53    /// The reason, as text, the provider is missing, its configuration is refused or it fails to
54    /// build.
55    fn load(
56        &self,
57        provider: &str,
58        config: Option<&ProviderConfig>,
59    ) -> Result<Arc<dyn SignInPolicy>, String>;
60}
61
62struct Held {
63    record: Option<SignInPolicyProvider>,
64    /// The stored record could not be read at all, so `record` says nothing of it.
65    unparsed: bool,
66    policy: Option<Arc<dyn SignInPolicy>>,
67    invalid: Option<String>,
68}
69
70/// The sign-in policy in force, and the way back to the record that stores it.
71pub struct LiveSignIn {
72    known: Option<std::collections::BTreeSet<String>>,
73    store: Option<Arc<dyn ConfigProvider>>,
74    loader: Option<Arc<dyn SignInLoader>>,
75    held: RwLock<Held>,
76    write: tokio::sync::Mutex<()>,
77}
78
79impl std::fmt::Debug for LiveSignIn {
80    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        formatter.debug_struct("LiveSignIn").finish_non_exhaustive()
82    }
83}
84
85impl LiveSignIn {
86    /// A policy kept in the `unex` record of `store` and built by `loader`; none is in force
87    /// until [`apply`](Self::apply) takes the record.
88    pub fn new(store: Arc<dyn ConfigProvider>, loader: Arc<dyn SignInLoader>) -> Self {
89        Self {
90            known: None,
91            store: Some(store),
92            loader: Some(loader),
93            held: RwLock::new(Held {
94                record: None,
95                unparsed: false,
96                policy: None,
97                invalid: None,
98            }),
99            write: tokio::sync::Mutex::new(()),
100        }
101    }
102
103    /// `policy`, which no route changes.
104    pub fn fixed(policy: Arc<dyn SignInPolicy>) -> Self {
105        Self {
106            known: None,
107            store: None,
108            loader: None,
109            held: RwLock::new(Held {
110                record: None,
111                unparsed: false,
112                policy: Some(policy),
113                invalid: None,
114            }),
115            write: tokio::sync::Mutex::new(()),
116        }
117    }
118
119    /// The IDs of the sign-in providers a policy may list; a policy listing any other is refused.
120    /// Without this nothing is checked.
121    #[must_use]
122    pub fn with_providers<I, S>(mut self, ids: I) -> Self
123    where
124        I: IntoIterator<Item = S>,
125        S: Into<String>,
126    {
127        self.known = Some(ids.into_iter().map(Into::into).collect());
128        self
129    }
130
131    /// Takes the record stored now. It reads the store under the lock a route's change holds, so
132    /// a poll that began before a change cannot put an older record over it.
133    ///
134    /// Call it where blocking is allowed.
135    ///
136    /// # Errors
137    ///
138    /// Why the stored record does not stand: the policy offers nothing meanwhile.
139    pub fn refresh(&self) -> Result<bool, String> {
140        let _turn = self.write.blocking_lock();
141        let store = self
142            .store
143            .clone()
144            .ok_or_else(|| "the sign-in policy is not kept in the configuration".to_owned())?;
145        let stored = store
146            .definitions(ConfigRecord::Unex, &ConfigScope::Global)
147            .map_err(|error| error.to_string())?
148            .records
149            .into_iter()
150            .find(|(key, _)| key == KEY)
151            .and_then(|(_, definition)| policy_of(&definition));
152        let record = match stored {
153            None => None,
154            Some(value) => match value.read::<SignInPolicyProvider>() {
155                Ok(record) => Some(record),
156                Err(reason) => {
157                    let reason = format!("sign_in_policy: {reason}");
158                    self.deny(None, reason.clone(), true);
159                    return Err(reason);
160                }
161            },
162        };
163        self.apply(record.as_ref())
164    }
165
166    fn read(&self) -> std::sync::RwLockReadGuard<'_, Held> {
167        self.held.read().unwrap_or_else(PoisonError::into_inner)
168    }
169
170    /// The policy in force; `None` when the record names none.
171    pub fn policy(&self) -> Option<Arc<dyn SignInPolicy>> {
172        self.read().policy.clone()
173    }
174
175    /// Why the stored policy is not in force, when it is not.
176    pub fn invalid(&self) -> Option<String> {
177        self.read().invalid.clone()
178    }
179
180    /// Puts the policy `record` names in force, or none when it names none, and says whether
181    /// that changed what is in force. A policy that does not build, or names a provider that is
182    /// not configured, fails closed: nothing is offered and [`invalid`](Self::invalid) says why,
183    /// never the policy that was in force before.
184    ///
185    /// # Errors
186    ///
187    /// Why the policy does not stand.
188    pub fn apply(&self, record: Option<&SignInPolicyProvider>) -> Result<bool, String> {
189        {
190            let held = self.read();
191            if held.record.as_ref() == record && !held.unparsed {
192                return match &held.invalid {
193                    Some(reason) => Err(reason.clone()),
194                    None => Ok(false),
195                };
196            }
197        }
198        match record {
199            None => self.install(None, None),
200            Some(record) => match self.build(record) {
201                Ok(policy) => self.install(Some(record.clone()), Some(policy)),
202                Err(reason) => {
203                    self.deny(Some(record.clone()), reason.clone(), false);
204                    return Err(reason);
205                }
206            },
207        }
208        Ok(true)
209    }
210
211    /// Offers nothing, and says why.
212    fn deny(&self, record: Option<SignInPolicyProvider>, reason: String, unparsed: bool) {
213        let mut held = self.held.write().unwrap_or_else(PoisonError::into_inner);
214        held.record = record;
215        held.policy = Some(Arc::new(SignInRules::default()));
216        held.invalid = Some(reason);
217        held.unparsed = unparsed;
218    }
219
220    fn build(&self, record: &SignInPolicyProvider) -> Result<Arc<dyn SignInPolicy>, String> {
221        if let Some(known) = &self.known {
222            for id in listed_providers(record) {
223                if !known.contains(&id) {
224                    return Err(format!(
225                        "the policy lists the provider {id}, which no sign-in provider is \
226                         configured under"
227                    ));
228                }
229            }
230        }
231        self.loader
232            .as_ref()
233            .ok_or_else(|| "no sign-in policy provider can be loaded here".to_owned())?
234            .load(&record.provider, record.config.as_ref())
235    }
236
237    fn install(&self, record: Option<SignInPolicyProvider>, policy: Option<Arc<dyn SignInPolicy>>) {
238        let mut held = self.held.write().unwrap_or_else(PoisonError::into_inner);
239        held.record = record;
240        held.policy = policy;
241        held.invalid = None;
242        held.unparsed = false;
243    }
244
245    /// Whether the policy in force offers no sign-in to any client from an unknown address or
246    /// from loopback. A policy that offers only from other networks is not counted: no list of
247    /// addresses is complete.
248    pub fn offers_nothing(&self) -> bool {
249        let Some(policy) = self.policy() else {
250            return false;
251        };
252        [None, Some("127.0.0.1"), Some("::1")]
253            .into_iter()
254            .flat_map(|address| {
255                [clients::BROWSER, clients::APP, clients::API]
256                    .into_iter()
257                    .map(move |client| SignInContext {
258                        purpose: purposes::SIGN_IN.to_owned(),
259                        address: address.map(str::to_owned),
260                        client: Some(client.to_owned()),
261                        service: Some(SERVICE.to_owned()),
262                        ..SignInContext::default()
263                    })
264            })
265            .all(|context| {
266                policy
267                    .decide(context)
268                    .map(|decision| decision.methods.is_empty() && !decision.complete)
269                    .unwrap_or(true)
270            })
271    }
272}
273
274/// The provider IDs a rules policy lists in its conditions.
275fn listed_providers(record: &SignInPolicyProvider) -> Vec<String> {
276    if record.provider != SignInPolicyProvider::RULES {
277        return Vec::new();
278    }
279    let member = |value: &guatiao::Value, key: &str| {
280        guatiao::TryAsRef::<guatiao::Map>::try_as_ref(value)?
281            .get(key)
282            .cloned()
283    };
284    let rules = record
285        .config
286        .as_ref()
287        .and_then(|config| config.get("rule"))
288        .and_then(guatiao::TryAsRef::<guatiao::List>::try_as_ref);
289    rules
290        .into_iter()
291        .flat_map(|rules| rules.iter())
292        .filter_map(|rule| member(rule, "providers"))
293        .flat_map(|providers| {
294            guatiao::TryAsRef::<guatiao::List>::try_as_ref(&providers)
295                .map(|ids| {
296                    ids.iter()
297                        .filter_map(|id| {
298                            guatiao::TryAsRef::<str>::try_as_ref(id).map(str::to_owned)
299                        })
300                        .collect::<Vec<_>>()
301                })
302                .unwrap_or_default()
303        })
304        .collect()
305}
306
307/// The step a Station's token carries: no sign-in made it, and none decides it again.
308pub(crate) const STATION: &str = "station";
309
310/// Whether `factors` say a Station issued the token.
311pub(crate) fn from_station(factors: &[SignInFactor]) -> bool {
312    matches!(factors, [only] if only.method() == STATION)
313}
314
315impl AccessProviders {
316    /// The IDs a sign-in policy may list: each named sign-in provider and the page
317    /// authenticator. The built-in proxy identity has none, so a `providers` condition never
318    /// matches its step.
319    pub fn provider_ids(&self) -> Vec<String> {
320        self.authenticators
321            .iter()
322            .chain(self.second.iter())
323            .filter_map(|signer| signer.id.clone())
324            .chain(self.page_authenticator_id.clone())
325            .collect()
326    }
327
328    /// Whether a key provider is configured, which keeps working whatever the policy offers.
329    pub fn has_keys(&self) -> bool {
330        self.keys.is_some()
331    }
332
333    /// The methods a page's viewer may be named by when no policy says otherwise: those a sign-in
334    /// may have used, and the page authenticator's own, whichever it uses.
335    pub(crate) fn page_methods(&self) -> Vec<&'static str> {
336        let mut methods = self.configured_methods();
337        if self.page_authenticator.is_some() {
338            for method in ["certificate", "proxy"] {
339                if !methods.contains(&method) {
340                    methods.push(method);
341                }
342            }
343        }
344        methods
345    }
346
347    /// The methods each configured sign-in provider and proxy identity offer, as a policy words
348    /// them: what stands when no policy is configured.
349    pub(crate) fn configured_methods(&self) -> Vec<&'static str> {
350        let mut methods = Vec::new();
351        for signer in &self.authenticators {
352            // An authenticator that says nothing, or cannot, is still asked for a name and a
353            // secret by `login`.
354            let takes = signer
355                .authenticator
356                .describe()
357                .ok()
358                .and_then(|description| description.takes);
359            if takes.as_deref() != Some(ai6::directorates::m::access::takes::REQUEST)
360                && !methods.contains(&"password")
361            {
362                methods.push("password");
363            }
364        }
365        if self.proxy_identity.is_some() {
366            methods.push("proxy");
367        }
368        methods
369    }
370}
371
372impl Gateway {
373    /// The context of a request for `purpose`, with what the gateway knows of where it comes
374    /// from. The client is a browser when the request names an origin, which no other client of
375    /// the gateway does, and an API client otherwise: Outer Office's desktop apps arrive as
376    /// the second kind, so a rule for `app` never matches here.
377    pub(crate) fn sign_in_context(
378        &self,
379        purpose: &str,
380        headers: &HeaderMap,
381        connection: Option<SocketAddr>,
382        service: &str,
383    ) -> SignInContext {
384        // Only a hint about what to offer: the caller says all of this. A browser sends no origin
385        // on a same-origin GET, but it does say how it is fetching.
386        let browser = service == PAGES
387            || headers.contains_key(ORIGIN)
388            || headers.contains_key("sec-fetch-mode")
389            || headers.contains_key("sec-fetch-site");
390        let client = if browser {
391            clients::BROWSER
392        } else {
393            clients::API
394        };
395        // The browser is the gateway's own finding when the request is for its own pages, names
396        // the gateway's public origin (the origin its login routes require), or is a fetch the
397        // browser itself marks same-origin. Any other claim of a client kind can only add steps
398        // to a sign-in.
399        let verified = browser
400            && (service == PAGES
401                || headers
402                    .get(ORIGIN)
403                    .and_then(|origin| origin.to_str().ok())
404                    .is_some_and(|origin| origin == self.public_origin())
405                || headers
406                    .get("sec-fetch-site")
407                    .is_some_and(|site| site == "same-origin"));
408        let context = SignInContext {
409            purpose: purpose.to_owned(),
410            address: self
411                .login_guard()
412                .address(headers, connection)
413                .map(|address| address.to_string()),
414            client: Some(client.to_owned()),
415            service: Some(service.to_owned()),
416            time_unix: unix_timestamp().ok().map(|now| now as i64),
417            ..SignInContext::default()
418        };
419        if verified {
420            context.with_verified_client()
421        } else {
422            context
423        }
424    }
425
426    /// What the sign-in policy decides for `context`; `None` when it could not find out, which
427    /// offers nothing and refuses.
428    pub(crate) async fn decide_sign_in(
429        &self,
430        providers: &AccessProviders,
431        context: SignInContext,
432    ) -> Option<SignInDecision> {
433        let providers = providers.clone();
434        let decided = tokio::task::spawn_blocking(move || {
435            let policy: Arc<dyn SignInPolicy> =
436                match providers.sign_in.as_ref().and_then(|live| live.policy()) {
437                    Some(policy) => policy,
438                    None => {
439                        let pages = context.service.as_deref() == Some(PAGES);
440                        let methods = if pages {
441                            providers.page_methods()
442                        } else {
443                            providers.configured_methods()
444                        };
445                        // Nothing configured to sign in with offers nothing.
446                        let rules = if methods.is_empty() {
447                            SignInRules::default()
448                        } else {
449                            SignInRules::single_factor(methods)
450                                .map_err(|error| error.to_string())?
451                        };
452                        Arc::new(rules)
453                    }
454                };
455            policy.decide(context).map_err(|error| error.to_string())
456        })
457        .await
458        .ok()?;
459        match decided {
460            Ok(decision) => Some(decision),
461            Err(reason) => {
462                eprintln!("universal-exports: the sign-in policy could not decide: {reason}");
463                None
464            }
465        }
466    }
467
468    /// The steps `factors` record, as a policy reads them.
469    pub(crate) fn passed(factors: &[SignInFactor]) -> Vec<Factor> {
470        factors
471            .iter()
472            .map(|factor| Factor {
473                method: factor.method().to_owned(),
474                provider: factor.provider().map(str::to_owned),
475                person: factor.person().map(str::to_owned),
476            })
477            .collect()
478    }
479}
480
481/// A step that passed, as the sign-in keeps it.
482pub(crate) fn step(
483    method: &str,
484    provider: Option<&str>,
485    person: &Person,
486) -> Result<SignInFactor, ApiError> {
487    SignInFactor::try_new(method, provider.map(str::to_owned), Some(person.id.clone()))
488        .map_err(|_| ApiError::internal())
489}
490
491/// The refusal of a method the policy does not offer from here: no authenticator is asked and
492/// no try is counted.
493pub(crate) fn not_accepted() -> ApiError {
494    ApiError::refused(
495        StatusCode::FORBIDDEN,
496        "this sign-in method is not accepted from here".to_owned(),
497    )
498}
499
500fn live(gateway: &Gateway) -> Result<Arc<LiveSignIn>, AdminError> {
501    gateway
502        .access
503        .as_ref()
504        .and_then(|access| access.sign_in.clone())
505        .ok_or(AdminError::Api(ApiError::unavailable()))
506}
507
508fn store(live: &LiveSignIn) -> Result<Arc<dyn ConfigProvider>, AdminError> {
509    live.store.clone().ok_or_else(|| {
510        AdminError::Conflict("the sign-in policy is not kept in the configuration".to_owned())
511    })
512}
513
514/// The `unex` record as stored, and the part of it that is the policy.
515struct Stored {
516    unex: Option<StoredRecord>,
517    writable: bool,
518}
519
520/// The `sign_in_policy` table of a `unex` record.
521fn policy_of(unex: &StoredRecord) -> Option<StoredRecord> {
522    unex.get("sign_in_policy")
523        .and_then(|policy| StoredRecord::from_value(policy).ok())
524}
525
526impl Stored {
527    fn policy(&self) -> Option<StoredRecord> {
528        policy_of(self.unex.as_ref()?)
529    }
530
531    /// The policy as it is shown: every credential literal in its configuration is
532    /// `<redacted>`, as the `unex` record shows it.
533    fn shown(&self) -> Option<StoredRecord> {
534        let mut unex = self.unex.clone()?;
535        crate::config_secrets::redact_unex(&mut unex);
536        policy_of(&unex)
537    }
538
539    /// `policy` as it is stored: a `<redacted>` the person got from [`Self::shown`] and sent
540    /// back keeps the literal stored.
541    fn kept(&self, policy: StoredRecord) -> StoredRecord {
542        let mut wrapper = StoredRecord::new().with("sign_in_policy", policy.value().clone());
543        if let Some(stored) = &self.unex {
544            crate::config_secrets::keep_redacted_unex(&mut wrapper, stored);
545        }
546        policy_of(&wrapper).unwrap_or_default()
547    }
548}
549
550async fn read_stored(store: Arc<dyn ConfigProvider>) -> Result<Stored, AdminError> {
551    tokio::task::spawn_blocking(move || {
552        store
553            .definitions(ConfigRecord::Unex, &ConfigScope::Global)
554            .map(|definitions| Stored {
555                writable: definitions.writable,
556                unex: definitions
557                    .records
558                    .into_iter()
559                    .find(|(key, _)| key == KEY)
560                    .map(|(_, definition)| definition),
561            })
562    })
563    .await
564    .map_err(|_| AdminError::Api(ApiError::internal()))?
565    .map_err(|_| AdminError::Api(ApiError::unavailable()))
566}
567
568/// `GET /v1/user/access/sign-in`: needs `access.read` at `config:access`.
569pub(crate) async fn read_policy(
570    State(gateway): State<Gateway>,
571    headers: HeaderMap,
572) -> Result<Json<PolicyView>, AdminError> {
573    let person = resolve_user(&gateway, bearer(&headers)?).await?;
574    authorize_resource_action(&gateway, person, CONFIG_ACCESS.to_owned(), "access.read").await?;
575    let live = live(&gateway)?;
576    let stored = read_stored(store(&live)?).await?;
577    let nothing = offers_nothing(&live).await;
578    Ok(Json(PolicyView {
579        revision: token(stored.policy().as_ref()),
580        writable: stored.writable,
581        policy: stored
582            .shown()
583            .map(|policy| ai6::guatiao_serde::SerdeValue::from(policy.value().clone())),
584        in_force: live.policy().is_some(),
585        offers_nothing: nothing,
586        invalid: live.invalid(),
587        note: restore_note(&gateway, nothing).map(str::to_owned),
588    }))
589}
590
591enum Change {
592    Set(Box<SignInPolicyProvider>, StoredRecord),
593    Remove,
594}
595
596/// `PUT /v1/user/access/sign-in`: stores the policy and puts it in force; needs
597/// `access.manage` at `config:access` and the revision read in `If-Match`. A policy that does
598/// not build is refused (400). One that offers no sign-in is accepted: API keys still work.
599pub(crate) async fn put_policy(
600    State(gateway): State<Gateway>,
601    headers: HeaderMap,
602    Query(query): Query<WriteQuery>,
603    Json(body): Json<PolicyBody>,
604) -> Result<Json<PolicyChanged>, AdminError> {
605    let mut value = StoredRecord::new();
606    if let Some(provider) = body.provider {
607        value.insert("provider", provider.as_str());
608    }
609    if let Some(config) = body.config {
610        let config = StoredRecord::from_serde(&config)
611            .map_err(|reason| AdminError::Refused(format!("sign_in_policy: {reason}")))?;
612        value.insert("config", config.value().clone());
613    }
614    let record: SignInPolicyProvider = value
615        .read()
616        .map_err(|reason| AdminError::Refused(format!("sign_in_policy: {reason}")))?;
617    write(
618        gateway,
619        headers,
620        query,
621        "access.sign_in.update",
622        Change::Set(Box::new(record), value),
623    )
624    .await
625}
626
627/// `DELETE /v1/user/access/sign-in`: back to each configured method alone being enough.
628pub(crate) async fn remove_policy(
629    State(gateway): State<Gateway>,
630    headers: HeaderMap,
631    Query(query): Query<WriteQuery>,
632) -> Result<Json<PolicyChanged>, AdminError> {
633    write(
634        gateway,
635        headers,
636        query,
637        "access.sign_in.remove",
638        Change::Remove,
639    )
640    .await
641}
642
643async fn write(
644    gateway: Gateway,
645    headers: HeaderMap,
646    query: WriteQuery,
647    action: &'static str,
648    change: Change,
649) -> Result<Json<PolicyChanged>, AdminError> {
650    let person = resolve_user(&gateway, bearer(&headers)?).await?;
651    let live = live(&gateway)?;
652    authorize_resource_action(
653        &gateway,
654        person.clone(),
655        CONFIG_ACCESS.to_owned(),
656        "access.manage",
657    )
658    .await?;
659    let expected = revision_of(&headers, &query)?;
660    let _turn = live.write.lock().await;
661    let provider = store(&live)?;
662    let stored = read_stored(provider.clone()).await?;
663    if !stored.writable {
664        return Err(AdminError::Conflict(
665            "the configuration provider is read-only".to_owned(),
666        ));
667    }
668    if token(stored.policy().as_ref()) != expected {
669        return Err(AdminError::Conflict(
670            "the sign-in policy changed since you read it; reload it".to_owned(),
671        ));
672    }
673    // What the read showed as `<redacted>` keeps the credential stored.
674    let change = match change {
675        Change::Set(_, value) => {
676            let value = stored.kept(value);
677            let record: SignInPolicyProvider = value
678                .read()
679                .map_err(|reason| AdminError::Refused(format!("sign_in_policy: {reason}")))?;
680            Change::Set(Box::new(record), value)
681        }
682        remove => remove,
683    };
684    let target = match &change {
685        Change::Set(record, _) => format!("sign_in_policy {}", record.provider),
686        Change::Remove => "sign_in_policy".to_owned(),
687    };
688    // Built before it is stored, so a policy that cannot stand is never written.
689    let built = match &change {
690        Change::Set(record, _) => {
691            let (building, record) = (live.clone(), (**record).clone());
692            let result = tokio::task::spawn_blocking(move || building.build(&record))
693                .await
694                .map_err(|_| AdminError::Api(ApiError::internal()))?;
695            match result {
696                Ok(policy) => Some(policy),
697                Err(reason) => {
698                    audit(
699                        &gateway,
700                        &person,
701                        "access.sign_in.refused",
702                        None,
703                        CONFIG_ACCESS,
704                        &format!("{target}: {reason}"),
705                    )
706                    .await?;
707                    return Err(AdminError::Refused(reason));
708                }
709            }
710        }
711        Change::Remove => {
712            if stored.policy().is_none() {
713                return Err(AdminError::Api(ApiError::not_found()));
714            }
715            None
716        }
717    };
718    let mut definition = stored
719        .unex
720        .clone()
721        .filter(StoredRecord::is_object)
722        .unwrap_or_default();
723    match &change {
724        Change::Set(_, value) => definition.insert("sign_in_policy", value.value().clone()),
725        Change::Remove => {
726            definition.remove("sign_in_policy");
727        }
728    }
729    definition
730        .read::<UnexRecord>()
731        .map_err(|reason| AdminError::Refused(format!("unex: {reason}")))?;
732    // The audit record comes first: a change that cannot be recorded is not stored.
733    audit(&gateway, &person, action, None, CONFIG_ACCESS, &target).await?;
734    let swapped = {
735        let (provider, expected, definition) =
736            (provider.clone(), stored.unex.clone(), definition.clone());
737        tokio::task::spawn_blocking(move || {
738            provider.put_if(
739                ConfigRecord::Unex,
740                &ConfigScope::Global,
741                KEY,
742                expected.as_ref(),
743                &definition,
744            )
745        })
746        .await
747        .map_err(|_| AdminError::Api(ApiError::internal()))?
748    };
749    if let Err(error) = swapped {
750        return Err(match error.kind() {
751            RosterErrorKind::Conflict => AdminError::Conflict(
752                "the sign-in policy changed since you read it; reload it".to_owned(),
753            ),
754            RosterErrorKind::ReadOnly => {
755                AdminError::Conflict("the configuration provider is read-only".to_owned())
756            }
757            RosterErrorKind::Invalid => AdminError::Refused(error.to_string()),
758            _ => AdminError::Api(ApiError::unavailable()),
759        });
760    }
761    match change {
762        Change::Set(record, _) => live.install(Some(*record), built),
763        Change::Remove => live.install(None, None),
764    }
765    let nothing = offers_nothing(&live).await;
766    let keys = gateway
767        .access
768        .as_ref()
769        .is_some_and(AccessProviders::has_keys);
770    if nothing {
771        eprintln!("{}", nothing_offered(keys));
772    }
773    Ok(Json(PolicyChanged {
774        revision: token(policy_of(&definition).as_ref()),
775        offers_nothing: nothing,
776        note: restore_note(&gateway, nothing).map(str::to_owned),
777    }))
778}
779
780/// What the gateway says when the policy in force offers no sign-in; with no key provider
781/// configured, there is nothing left that works but an edit to the database.
782pub fn nothing_offered(keys: bool) -> &'static str {
783    if keys {
784        "universal-exports: sign-in policy: no sign-in is offered; API keys still work (ai6ctl \
785         with a key holding access.manage changes the policy)"
786    } else {
787        "universal-exports: sign-in policy: no sign-in is offered and no key provider is \
788         configured; only an edit to the database's unex record restores sign-in"
789    }
790}
791
792fn restore_note(gateway: &Gateway, offers_nothing: bool) -> Option<&'static str> {
793    let keys = gateway
794        .access
795        .as_ref()
796        .is_some_and(AccessProviders::has_keys);
797    (offers_nothing && !keys).then(|| nothing_offered(false))
798}
799
800/// [`LiveSignIn::offers_nothing`], where blocking is allowed: the policy may be a plugin.
801async fn offers_nothing(live: &Arc<LiveSignIn>) -> bool {
802    let live = live.clone();
803    tokio::task::spawn_blocking(move || live.offers_nothing())
804        .await
805        .unwrap_or(true)
806}