Skip to main content

apiplant_core/
config.rs

1//! `main.toml` — the top-level server configuration.
2//!
3//! Every field is optional: a missing file, or a file missing any given key,
4//! falls back to a safe default. The only piece of configuration that is
5//! *inferred* rather than declared is TLS: if the app directory contains an
6//! `https/` folder with a cert + key, the server serves HTTPS.
7//!
8//! ## Environment variables
9//!
10//! Any string value here — like any string in any of the app's TOML files — may
11//! reference the environment: `url = "$DATABASE_URL"`,
12//! `port = "${PORT:-8080}"`. See [`crate::env`] for the syntax.
13
14use serde::Deserialize;
15use std::path::Path;
16
17/// Fully-resolved server configuration.
18#[derive(Debug, Clone, Default, Deserialize)]
19#[serde(default)]
20pub struct Config {
21    pub app: AppConfig,
22    pub server: ServerConfig,
23    pub database: DatabaseConfig,
24    pub auth: AuthConfig,
25    pub docs: DocsConfig,
26    pub admin: AdminConfig,
27    pub public: PublicConfig,
28    pub email: EmailConfig,
29    pub cache: CacheConfig,
30    pub payments: PaymentsConfig,
31    pub ai: AiConfig,
32}
33
34/// What the app calls itself.
35///
36/// The directory an app lives in is a developer's filing decision —
37/// `07-functions`, `api-v2`, `backend` — and the dashboard header is read by
38/// people who never see it. This is where an app says the name they should
39/// read instead.
40#[derive(Debug, Clone, Default, Deserialize)]
41#[serde(default)]
42pub struct AppConfig {
43    /// Display name, used wherever the app is named to a person — the admin
44    /// dashboard's header and title. Unset falls back to the directory name.
45    pub name: Option<String>,
46}
47
48/// Accepts either a bare string or a list of them, so a config that names one
49/// domain doesn't have to be written as a one-element list.
50fn one_or_many<'de, D: serde::Deserializer<'de>>(de: D) -> Result<Vec<String>, D::Error> {
51    #[derive(Deserialize)]
52    #[serde(untagged)]
53    enum OneOrMany {
54        One(String),
55        Many(Vec<String>),
56    }
57    Ok(match OneOrMany::deserialize(de)? {
58        OneOrMany::One(s) => vec![s],
59        OneOrMany::Many(v) => v,
60    })
61}
62
63#[derive(Debug, Clone, Deserialize)]
64#[serde(default)]
65pub struct ServerConfig {
66    /// Interface to bind, e.g. `0.0.0.0`. Empty or `*` means every interface
67    /// and is normalised to `0.0.0.0` on load.
68    pub host: String,
69    /// TCP port.
70    pub port: u16,
71    /// Only answer requests whose `Host:` header is one of these. Written as a
72    /// single string (`domain = "api.example.com"`) or a list
73    /// (`domain = ["api.example.com", "www.example.com"]`). Unset — or the
74    /// catch-all spellings `""`, `*` and `_` (nginx's `server_name _`) —
75    /// answers any host, and all of them normalise to an empty list on load.
76    #[serde(deserialize_with = "one_or_many")]
77    pub domain: Vec<String>,
78    /// Sub-path the API is mounted under, e.g. `/api`. Always starts with `/`
79    /// and never ends with one (normalised on load).
80    pub base_path: String,
81    /// Number of worker threads. `None` = one per CPU.
82    pub workers: Option<usize>,
83    /// The origin this server is reached at from outside — `https://api.example.com`.
84    ///
85    /// Only links that leave the process need it: an invitation email has to
86    /// name a URL, and a request's own `Host:` header is the wrong source for
87    /// one (a message is composed once and read anywhere, possibly behind a
88    /// proxy that rewrote it). Unset falls back to the first configured
89    /// `domain`, then to `http://<host>:<port>`, which is right for local
90    /// development and wrong in front of a load balancer — so set it there.
91    pub public_url: String,
92}
93
94impl Default for ServerConfig {
95    fn default() -> Self {
96        ServerConfig {
97            host: "0.0.0.0".to_string(),
98            port: 8080,
99            domain: Vec::new(),
100            base_path: "/".to_string(),
101            workers: None,
102            public_url: String::new(),
103        }
104    }
105}
106
107impl ServerConfig {
108    /// The origin to put in a link that will be read outside this process.
109    ///
110    /// Prefers what the app declared, then the first domain it answers for,
111    /// and only then the socket it happens to be bound to.
112    pub fn public_origin(&self) -> String {
113        if !self.public_url.is_empty() {
114            return self.public_url.trim_end_matches('/').to_string();
115        }
116        if let Some(domain) = self.domain.first() {
117            // A bare domain is a hostname, not a URL; assume the scheme every
118            // deployment that has a domain name is using.
119            return if domain.contains("://") {
120                domain.trim_end_matches('/').to_string()
121            } else {
122                format!("https://{domain}")
123            };
124        }
125        let host = match self.host.as_str() {
126            "0.0.0.0" | "" | "*" | "::" => "localhost",
127            host => host,
128        };
129        format!("http://{host}:{}", self.port)
130    }
131}
132
133#[derive(Debug, Clone, Deserialize)]
134#[serde(default)]
135pub struct DatabaseConfig {
136    /// Full connection URL. When empty it is assembled from the parts below.
137    pub url: String,
138    pub host: String,
139    pub port: u16,
140    pub name: String,
141    pub user: String,
142    pub password: String,
143    /// Max pool connections.
144    pub max_connections: u32,
145    /// Run pending migrations on boot.
146    pub auto_migrate: bool,
147}
148
149impl Default for DatabaseConfig {
150    fn default() -> Self {
151        DatabaseConfig {
152            url: String::new(),
153            host: "localhost".to_string(),
154            port: 5432,
155            name: "apiplant".to_string(),
156            user: "postgres".to_string(),
157            password: "postgres".to_string(),
158            max_connections: 16,
159            auto_migrate: true,
160        }
161    }
162}
163
164impl DatabaseConfig {
165    /// The connection URL, assembled from parts when `url` was left empty.
166    pub fn resolved_url(&self) -> String {
167        if !self.url.is_empty() {
168            return self.url.clone();
169        }
170        format!(
171            "postgres://{}:{}@{}:{}/{}",
172            self.user, self.password, self.host, self.port, self.name
173        )
174    }
175}
176
177#[derive(Debug, Clone, Deserialize)]
178#[serde(default)]
179pub struct AuthConfig {
180    /// Secret used to sign session JWTs. Auto-generated (and warned about) when
181    /// left empty — set it in production so tokens survive restarts.
182    pub jwt_secret: String,
183    /// Session token lifetime in seconds.
184    pub session_ttl_secs: u64,
185    /// Allow self-service signup on `POST /auth/register`.
186    pub allow_registration: bool,
187
188    // --- the three features that need a mailbox to reach ------------------
189    //
190    // Each is `Option<bool>` rather than `bool` because their honest default is
191    // not a constant: it is "yes, if this app can send email". Leaving one unset
192    // means it follows `[email]`, so configuring a provider turns all three on
193    // and configuring none leaves them off — and neither one asks the developer
194    // to keep two sections in step. Setting one explicitly always wins, which is
195    // how an app that sends mail can still refuse, say, open registration.
196    /// Require a new account to confirm its address before it can sign in.
197    /// Unset follows `[email]`.
198    pub require_email_verification: Option<bool>,
199    /// Offer `POST /auth/invitations`, so an admin can add someone who has no
200    /// account yet. Unset follows `[email]`.
201    pub allow_invitations: Option<bool>,
202    /// Offer `POST /auth/password/forgot` and `/auth/password/reset`. Unset
203    /// follows `[email]`.
204    pub allow_password_reset: Option<bool>,
205
206    /// How long an organisation invitation stays valid (default 7 days).
207    pub invite_ttl_secs: u64,
208    /// How long an address-confirmation link stays valid (default 24 hours).
209    pub verification_ttl_secs: u64,
210    /// How long a password-reset link stays valid (default 1 hour). Short on
211    /// purpose: it is a live credential sitting in a mailbox.
212    pub password_reset_ttl_secs: u64,
213}
214
215impl Default for AuthConfig {
216    fn default() -> Self {
217        AuthConfig {
218            jwt_secret: String::new(),
219            session_ttl_secs: 60 * 60 * 24 * 7,
220            allow_registration: true,
221            require_email_verification: None,
222            allow_invitations: None,
223            allow_password_reset: None,
224            invite_ttl_secs: 60 * 60 * 24 * 7,
225            verification_ttl_secs: 60 * 60 * 24,
226            password_reset_ttl_secs: 60 * 60,
227        }
228    }
229}
230
231impl AuthConfig {
232    /// Whether new accounts must confirm their address, given whether the app
233    /// can send mail at all. An unset flag follows the mailer: asking for a
234    /// confirmation nobody can deliver would lock every new account out.
235    pub fn requires_email_verification(&self, email_enabled: bool) -> bool {
236        self.require_email_verification.unwrap_or(email_enabled) && email_enabled
237    }
238
239    /// Whether invitations are offered. See
240    /// [`requires_email_verification`](Self::requires_email_verification) for
241    /// why an explicit `true` still needs a mailer.
242    pub fn invitations_enabled(&self, email_enabled: bool) -> bool {
243        self.allow_invitations.unwrap_or(email_enabled) && email_enabled
244    }
245
246    /// Whether password reset is offered.
247    pub fn password_reset_enabled(&self, email_enabled: bool) -> bool {
248        self.allow_password_reset.unwrap_or(email_enabled) && email_enabled
249    }
250}
251
252/// Interactive API documentation (OpenAPI spec + Swagger UI).
253#[derive(Debug, Clone, Deserialize)]
254#[serde(default)]
255pub struct DocsConfig {
256    /// Serve the OpenAPI spec and Swagger UI (default true).
257    pub enabled: bool,
258    /// Path (under `base_path`) the Swagger UI is served at.
259    pub path: String,
260    /// Title shown in the UI and the spec's `info.title`. Unset falls back to
261    /// the app's name — see [`App::docs_title`](crate::App::docs_title) — so an
262    /// app that renames itself renames its docs too.
263    pub title: Option<String>,
264}
265
266impl Default for DocsConfig {
267    fn default() -> Self {
268        DocsConfig {
269            enabled: true,
270            path: "/docs".to_string(),
271            title: None,
272        }
273    }
274}
275
276/// The built-in admin dashboard, served from the binary itself.
277///
278/// Every app gets one, and there is only one: the interface is embedded in
279/// `apiplant` and its manifest is derived from the app on boot. Turn it off for
280/// a deployment that shouldn't expose an operator console at all — an app that
281/// wants its own can serve one from `public/` like any other page.
282#[derive(Debug, Clone, Deserialize)]
283#[serde(default)]
284pub struct AdminConfig {
285    /// Serve the admin dashboard (default true).
286    pub enabled: bool,
287    /// Path the dashboard is served at, outside `base_path`.
288    pub path: String,
289    /// Image shown in place of the apiplant mark, as a URL the browser can
290    /// fetch — usually a file in `public/`. Unset keeps the apiplant mark.
291    pub logo: Option<String>,
292    /// Optional AI help for writing text in the admin dashboard.
293    pub ai_assistance: AdminAiAssistanceConfig,
294}
295
296/// Extra browser-side prompting that fills text fields through the app's
297/// configured AI provider.
298#[derive(Debug, Clone, Deserialize)]
299#[serde(default)]
300pub struct AdminAiAssistanceConfig {
301    /// Show the "fill with AI" control in the dashboard.
302    pub enabled: bool,
303    /// Optional system prompt sent only by the dashboard's own field helper.
304    pub system: String,
305    /// Placeholder shown in the helper's prompt box.
306    pub prompt_placeholder: String,
307}
308
309impl Default for AdminAiAssistanceConfig {
310    fn default() -> Self {
311        AdminAiAssistanceConfig {
312            enabled: false,
313            system: String::new(),
314            prompt_placeholder: "Describe what you want AI to write for this field."
315                .to_string(),
316        }
317    }
318}
319
320impl Default for AdminConfig {
321    fn default() -> Self {
322        AdminConfig {
323            enabled: true,
324            path: "/admin".to_string(),
325            logo: None,
326            ai_assistance: AdminAiAssistanceConfig::default(),
327        }
328    }
329}
330
331/// Static files served from the app's `public/` directory.
332///
333/// When the directory exists its contents are served at the site root, so
334/// `public/index.html` answers `/` and `public/style.css` answers `/style.css`.
335#[derive(Debug, Clone, Deserialize)]
336#[serde(default)]
337pub struct PublicConfig {
338    /// Serve `dir` at the root when it exists (default true).
339    pub enabled: bool,
340    /// Directory (relative to the app root) holding the static site.
341    pub dir: String,
342    /// Page returned for requests that match nothing, relative to `dir`.
343    /// Defaults to `404.html` when that file exists.
344    pub not_found: Option<String>,
345}
346
347impl Default for PublicConfig {
348    fn default() -> Self {
349        PublicConfig {
350            enabled: true,
351            dir: "public".to_string(),
352            not_found: None,
353        }
354    }
355}
356
357/// Outbound email: which provider sends it, and the credentials to do so.
358///
359/// Off by default (`provider = "none"`): an app that never sends mail carries
360/// no configuration and no client. Turning it on is one line plus a key, and
361/// every provider is reached through the same [`send_email`] call from a
362/// function — swapping SendGrid for SES is a config change, not a code change.
363///
364/// [`send_email`]: https://docs.rs/apiplant-function
365#[derive(Debug, Clone, Deserialize)]
366#[serde(default)]
367pub struct EmailConfig {
368    /// `none` (default), `smtp`, `ses`, `sendgrid`, `brevo` (aka `sendinblue`),
369    /// `mailjet`, `mailgun`, `postmark` or `resend`.
370    pub provider: String,
371    /// Envelope sender, e.g. `no-reply@example.com`. Required once enabled; a
372    /// message may override it per-send.
373    pub from: String,
374    /// Display name shown beside `from`.
375    pub from_name: String,
376    /// Default `Reply-To`. Empty = none.
377    pub reply_to: String,
378    /// The provider's API key. For `ses` this is the AWS access key id; for
379    /// `mailjet` the public key; for `smtp` it is unused (see [`SmtpConfig`]).
380    pub api_key: String,
381    /// The second half of a two-part credential: the AWS secret access key for
382    /// `ses`, the private key for `mailjet`. Unused elsewhere.
383    pub api_secret: String,
384    /// AWS region for `ses`, e.g. `eu-west-1`.
385    pub region: String,
386    /// Sending domain for `mailgun`, e.g. `mg.example.com`.
387    pub domain: String,
388    /// How long one send may take before it is abandoned.
389    pub timeout_secs: u64,
390    /// Connection details for `provider = "smtp"`.
391    pub smtp: SmtpConfig,
392}
393
394impl Default for EmailConfig {
395    fn default() -> Self {
396        EmailConfig {
397            provider: "none".to_string(),
398            from: String::new(),
399            from_name: String::new(),
400            reply_to: String::new(),
401            api_key: String::new(),
402            api_secret: String::new(),
403            region: String::new(),
404            domain: String::new(),
405            timeout_secs: 15,
406            smtp: SmtpConfig::default(),
407        }
408    }
409}
410
411impl EmailConfig {
412    /// Whether a provider is configured at all. `none` and the empty string
413    /// both mean "this app doesn't send mail".
414    pub fn enabled(&self) -> bool {
415        !matches!(
416            self.provider.trim().to_ascii_lowercase().as_str(),
417            "" | "none"
418        )
419    }
420}
421
422/// SMTP transport settings, used only when `provider = "smtp"`.
423///
424/// Every provider here also speaks SMTP, so this is the escape hatch for one
425/// that has no first-class entry above — or for a company relay that has no API
426/// at all.
427#[derive(Debug, Clone, Deserialize)]
428#[serde(default)]
429pub struct SmtpConfig {
430    pub host: String,
431    /// `0` (the default) picks the port that matches `encryption`: 465 for
432    /// `tls`, 587 for `starttls`, 25 for `none`.
433    pub port: u16,
434    pub username: String,
435    pub password: String,
436    /// `starttls` (default), `tls` (implicit TLS, usually port 465) or `none`.
437    pub encryption: String,
438}
439
440impl Default for SmtpConfig {
441    fn default() -> Self {
442        SmtpConfig {
443            host: String::new(),
444            port: 0,
445            username: String::new(),
446            password: String::new(),
447            encryption: "starttls".to_string(),
448        }
449    }
450}
451
452/// An optional Redis cache.
453///
454/// Nothing in the framework caches through it: resources, permissions and the
455/// admin manifest all behave exactly the same whether it is configured or not.
456/// It exists so a *function* has somewhere to put a rate-limit counter, a
457/// memoised third-party response or a short-lived token — see the `cache_*`
458/// helpers on a function's `Context`.
459///
460/// Off unless `url` is set, so an app that doesn't want one pays nothing.
461#[derive(Debug, Clone, Deserialize)]
462#[serde(default)]
463pub struct CacheConfig {
464    /// Turn the configured cache off without deleting its settings.
465    pub enabled: bool,
466    /// Connection URL, e.g. `redis://127.0.0.1:6379` or `rediss://…/0`. Empty
467    /// (the default) means no cache.
468    pub url: String,
469    /// Prepended to every key a function uses, so several apps can share one
470    /// Redis without colliding.
471    pub prefix: String,
472    /// Expiry applied to a `set` that doesn't ask for one. `0` = keys persist.
473    pub default_ttl_secs: u64,
474    /// How long one cache operation may take before it is abandoned.
475    pub timeout_secs: u64,
476}
477
478impl Default for CacheConfig {
479    fn default() -> Self {
480        CacheConfig {
481            enabled: true,
482            url: String::new(),
483            prefix: String::new(),
484            default_ttl_secs: 0,
485            timeout_secs: 5,
486        }
487    }
488}
489
490impl CacheConfig {
491    /// Whether a cache should be connected: switched on *and* pointed at a
492    /// server.
493    pub fn is_active(&self) -> bool {
494        self.enabled && !self.url.trim().is_empty()
495    }
496}
497
498/// Payments: who takes the money, and how the checkout is set up.
499///
500/// Off by default (`provider = "none"`). Turning it on does three things an
501/// app would otherwise build by hand: it connects a Stripe client, it adds the
502/// `billing_*` [resources](crate::defaults) — catalogue, customers,
503/// subscriptions, payments — so billing state is queryable through the same
504/// permissions and roles as everything else, and it mounts the `/billing`
505/// endpoints that start a checkout and receive Stripe's webhooks.
506///
507/// Nothing here is a price. Prices live in `billing_price` rows, because a
508/// price is data an operator changes on a Tuesday, not configuration that
509/// wants a deployment.
510#[derive(Debug, Clone, Deserialize)]
511#[serde(default)]
512pub struct PaymentsConfig {
513    /// `none` (default) or `stripe`.
514    pub provider: String,
515    /// Stripe secret key (`sk_live_…` / `sk_test_…`). Required once enabled.
516    pub secret_key: String,
517    /// Stripe publishable key (`pk_live_…`). Not a secret: it is handed to the
518    /// browser by `GET <base>/billing/config`, which is how a front end
519    /// mounts Stripe's own elements without hardcoding a key per environment.
520    pub publishable_key: String,
521    /// Signing secret for the webhook endpoint (`whsec_…`).
522    ///
523    /// Without it `POST <base>/billing/webhook` refuses every delivery — an
524    /// unverified webhook is an unauthenticated request that edits
525    /// subscriptions, and accepting one because it is inconvenient not to is
526    /// how somebody else grants themselves a plan.
527    pub webhook_secret: String,
528    /// ISO 4217 currency for prices that don't name one, e.g. `eur`.
529    pub currency: String,
530    /// Let Stripe Tax work out and apply the right tax for the customer's
531    /// location (default true).
532    ///
533    /// On means the amounts here are what you charge *before* tax and Stripe
534    /// adds what the buyer owes. It needs an origin address and active
535    /// registrations in the Stripe dashboard; with none, Stripe adds nothing
536    /// and the charge is the price.
537    pub automatic_tax: bool,
538    /// Ask the buyer for a VAT/GST number at checkout (default true when
539    /// `automatic_tax` is on — a business buyer's number is what makes the
540    /// reverse charge apply).
541    pub tax_id_collection: Option<bool>,
542    /// Collect a full billing address at checkout rather than only what the
543    /// card requires. `auto` (default) or `required`; automatic tax needs an
544    /// address, so `auto` still collects enough to place the customer.
545    pub billing_address: String,
546    /// Where Stripe returns the buyer after a completed checkout. Empty falls
547    /// back to the dashboard's billing screen — see
548    /// [`ServerConfig::public_origin`].
549    pub success_url: String,
550    /// Where Stripe returns a buyer who backed out. Empty falls back to the
551    /// dashboard's billing screen.
552    pub cancel_url: String,
553    /// Where the Stripe customer portal returns to. Empty falls back to the
554    /// dashboard's billing screen.
555    pub portal_return_url: String,
556    /// How long one Stripe API call may take before it is abandoned.
557    pub timeout_secs: u64,
558}
559
560impl Default for PaymentsConfig {
561    fn default() -> Self {
562        PaymentsConfig {
563            provider: "none".to_string(),
564            secret_key: String::new(),
565            publishable_key: String::new(),
566            webhook_secret: String::new(),
567            currency: "usd".to_string(),
568            automatic_tax: true,
569            tax_id_collection: None,
570            billing_address: "auto".to_string(),
571            success_url: String::new(),
572            cancel_url: String::new(),
573            portal_return_url: String::new(),
574            timeout_secs: 20,
575        }
576    }
577}
578
579impl PaymentsConfig {
580    /// Whether a provider is configured at all. `none` and the empty string
581    /// both mean "this app doesn't take money".
582    pub fn enabled(&self) -> bool {
583        !matches!(
584            self.provider.trim().to_ascii_lowercase().as_str(),
585            "" | "none"
586        )
587    }
588
589    /// The currency to use for an amount that didn't name one, lowercased the
590    /// way Stripe wants it.
591    pub fn default_currency(&self) -> String {
592        let currency = self.currency.trim().to_ascii_lowercase();
593        if currency.is_empty() {
594            "usd".to_string()
595        } else {
596            currency
597        }
598    }
599
600    /// Whether checkout asks for a tax number. Unset follows `automatic_tax`:
601    /// collecting a VAT number is only useful to somebody computing tax with
602    /// it, and asking for one you ignore is a field that does nothing.
603    pub fn collects_tax_ids(&self) -> bool {
604        self.tax_id_collection.unwrap_or(self.automatic_tax)
605    }
606
607    /// Whether the webhook endpoint can verify a delivery. Payments still work
608    /// without it — the checkout completes and Stripe has the money — but
609    /// nothing of ours would ever hear about it.
610    pub fn webhooks_enabled(&self) -> bool {
611        self.enabled() && !self.webhook_secret.trim().is_empty()
612    }
613}
614
615/// An AI chat assistant: which service answers, and what to say to it.
616///
617/// Off by default (`provider = "none"`). Turning it on connects one client and
618/// mounts `<base>/ai/chat`, which takes a list of messages and streams the
619/// reply back token by token — and gives every function a `chat` call over the
620/// same provider.
621///
622/// The three providers differ only in wire format. `custom` is the one that
623/// matters most in practice: anything speaking the OpenAI chat-completions
624/// shape — llama.cpp, vLLM, Ollama, LM Studio, a gateway of your own — is
625/// reached by pointing [`endpoint`](Self::endpoint) at it, with no key at all
626/// if it wants none.
627#[derive(Debug, Clone, Deserialize)]
628#[serde(default)]
629pub struct AiConfig {
630    /// `none` (default), `openai`, `anthropic` or `custom`.
631    pub provider: String,
632    /// Where to send the request.
633    ///
634    /// Empty uses the provider's own API (`https://api.openai.com`,
635    /// `https://api.anthropic.com`) and is required for `custom`. A bare origin
636    /// or a base path (`http://localhost:8080`, `.../v1`) gets the provider's
637    /// standard path appended; a URL that already names the full path
638    /// (`…/v1/chat/completions`, `…/v1/messages`) is used exactly as written,
639    /// for a gateway that mounts it somewhere of its own.
640    pub endpoint: String,
641    /// Model to ask for when a request doesn't name one, e.g. `gpt-4o-mini`.
642    /// Some local servers serve a single model and ignore this.
643    pub model: String,
644    /// The provider's API key. **Optional**: a local model behind
645    /// `provider = "custom"` usually wants no credential, and sending an empty
646    /// one is different from sending none — so an empty key means the request
647    /// carries no authorization header at all.
648    pub api_key: String,
649    /// Prepended to every conversation as the system prompt, unless the request
650    /// carries its own. Empty = none.
651    pub system: String,
652    /// Cap on the tokens generated per reply. Anthropic requires one, so this
653    /// is sent to every provider rather than being special-cased.
654    pub max_tokens: u32,
655    /// Sampling temperature sent when a request doesn't name one. Negative
656    /// (the default) sends nothing and lets the provider choose.
657    pub temperature: f32,
658    /// Who may call `<base>/ai/chat`, in the grammar a resource's
659    /// `[permissions]` uses: `public`, `authenticated` (the default), `member`,
660    /// `role:<name>`.
661    ///
662    /// Defaulting to `authenticated` is deliberate. The endpoint spends money
663    /// (or a GPU) on behalf of whoever calls it, and a public one is an open
664    /// proxy to your provider account — which is a decision an app should have
665    /// to write down.
666    pub access: String,
667    /// How long one completion may take before it is abandoned. Generous by
668    /// default: a long answer from a local model is slow, not broken.
669    pub timeout_secs: u64,
670}
671
672impl Default for AiConfig {
673    fn default() -> Self {
674        AiConfig {
675            provider: "none".to_string(),
676            endpoint: String::new(),
677            model: String::new(),
678            api_key: String::new(),
679            system: String::new(),
680            max_tokens: 2048,
681            temperature: -1.0,
682            access: "authenticated".to_string(),
683            timeout_secs: 300,
684        }
685    }
686}
687
688impl AiConfig {
689    /// Whether a provider is configured at all. `none` and the empty string
690    /// both mean "this app has no assistant".
691    pub fn enabled(&self) -> bool {
692        !matches!(
693            self.provider.trim().to_ascii_lowercase().as_str(),
694            "" | "none"
695        )
696    }
697
698    /// The sampling temperature to send, or `None` to let the provider decide.
699    pub fn default_temperature(&self) -> Option<f32> {
700        (self.temperature >= 0.0).then_some(self.temperature)
701    }
702}
703
704impl Config {
705    /// Load `main.toml` from an app directory, applying defaults for anything
706    /// absent. A missing file is not an error.
707    pub fn load(app_dir: &Path) -> crate::Result<Self> {
708        let path = app_dir.join("main.toml");
709        let mut config = if path.exists() {
710            let text = std::fs::read_to_string(&path).map_err(|e| crate::Error::Io {
711                path: path.clone(),
712                source: e,
713            })?;
714            // `$VAR` in any string value is read from the environment here,
715            // which is what keeps credentials out of a committed main.toml.
716            crate::env::parse_toml::<Config>(&text, "main.toml")
717                .map_err(|e| crate::Error::Toml { path, source: e })?
718        } else {
719            tracing::info!("no main.toml found, using defaults");
720            Config::default()
721        };
722        config.normalise();
723        Ok(config)
724    }
725
726    fn normalise(&mut self) {
727        // "bind everywhere" has three spellings people arrive with: leaving it
728        // out, the wildcard, and the address itself. They all mean 0.0.0.0.
729        let host = self.server.host.trim();
730        if host.is_empty() || host == "*" {
731            self.server.host = "0.0.0.0".to_string();
732        } else {
733            self.server.host = host.to_string();
734        }
735
736        // Same idea for the vhost filter: an empty or wildcard `domain` is a
737        // request for no filter at all, not a filter for the empty host. `_` is
738        // there because nginx spells its catch-all `server_name _`. A wildcard
739        // anywhere in the list wins — it already answers every host, so the
740        // named entries beside it can't narrow anything.
741        let domains = std::mem::take(&mut self.server.domain);
742        let mut wildcard = false;
743        for d in domains {
744            match d.trim() {
745                "" | "*" | "_" | "0.0.0.0" => wildcard = true,
746                d => self.server.domain.push(d.to_string()),
747            }
748        }
749        if wildcard {
750            self.server.domain.clear();
751        }
752
753        let bp = self.server.base_path.trim_end_matches('/');
754        self.server.base_path = if bp.is_empty() {
755            String::new()
756        } else if bp.starts_with('/') {
757            bp.to_string()
758        } else {
759            format!("/{bp}")
760        };
761
762        if !self.docs.path.starts_with('/') {
763            self.docs.path = format!("/{}", self.docs.path);
764        }
765
766        let admin = self.admin.path.trim_matches('/');
767        self.admin.path = if admin.is_empty() {
768            AdminConfig::default().path
769        } else {
770            format!("/{admin}")
771        };
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use super::*;
778    use std::fs;
779    use std::time::{SystemTime, UNIX_EPOCH};
780
781    fn temp_dir(label: &str) -> std::path::PathBuf {
782        let mut dir = std::env::temp_dir();
783        let stamp = SystemTime::now()
784            .duration_since(UNIX_EPOCH)
785            .unwrap()
786            .as_nanos();
787        dir.push(format!(
788            "apiplant-config-{label}-{}-{stamp}",
789            std::process::id()
790        ));
791        fs::create_dir_all(&dir).unwrap();
792        dir
793    }
794
795    #[test]
796    fn missing_main_toml_uses_defaults() {
797        let dir = temp_dir("defaults");
798        let config = Config::load(&dir).unwrap();
799
800        assert_eq!(config.server.host, "0.0.0.0");
801        assert_eq!(config.server.port, 8080);
802        assert_eq!(config.server.base_path, "");
803        assert_eq!(
804            config.database.resolved_url(),
805            "postgres://postgres:postgres@localhost:5432/apiplant"
806        );
807        assert!(config.auth.allow_registration);
808        assert!(config.docs.enabled);
809        assert_eq!(config.docs.path, "/docs");
810        // The dashboard and the public site are on by default; an app opts out.
811        assert!(config.admin.enabled);
812        assert_eq!(config.admin.path, "/admin");
813        assert!(!config.admin.ai_assistance.enabled);
814        assert_eq!(
815            config.admin.ai_assistance.prompt_placeholder,
816            "Describe what you want AI to write for this field."
817        );
818        assert!(config.public.enabled);
819        assert_eq!(config.public.dir, "public");
820        assert_eq!(config.public.not_found, None);
821        // Email, cache and payments are opt-in: an app that says nothing gets
822        // none of them.
823        assert!(!config.email.enabled());
824        assert!(!config.cache.is_active());
825        assert!(!config.payments.enabled());
826
827        fs::remove_dir_all(dir).unwrap();
828    }
829
830    #[test]
831    fn email_and_cache_load_from_their_sections() {
832        let dir = temp_dir("email-cache");
833        fs::write(
834            dir.join("main.toml"),
835            r#"
836[email]
837provider = "sendgrid"
838from = "no-reply@example.com"
839from_name = "Example"
840api_key = "SG.literal"
841
842[cache]
843url = "redis://127.0.0.1:6379"
844prefix = "example:"
845default_ttl_secs = 300
846"#,
847        )
848        .unwrap();
849
850        let config = Config::load(&dir).unwrap();
851
852        assert!(config.email.enabled());
853        assert_eq!(config.email.provider, "sendgrid");
854        assert_eq!(config.email.from, "no-reply@example.com");
855        assert_eq!(config.email.api_key, "SG.literal");
856        // Untouched defaults still apply inside a section that was given.
857        assert_eq!(config.email.timeout_secs, 15);
858        assert_eq!(config.email.smtp.encryption, "starttls");
859
860        assert!(config.cache.is_active());
861        assert_eq!(config.cache.prefix, "example:");
862        assert_eq!(config.cache.default_ttl_secs, 300);
863
864        fs::remove_dir_all(dir).unwrap();
865    }
866
867    #[test]
868    fn payments_load_from_their_section() {
869        let dir = temp_dir("payments");
870        fs::write(
871            dir.join("main.toml"),
872            r#"
873[payments]
874provider = "stripe"
875secret_key = "sk_test_literal"
876webhook_secret = "whsec_literal"
877currency = "EUR"
878"#,
879        )
880        .unwrap();
881
882        let config = Config::load(&dir).unwrap();
883
884        assert!(config.payments.enabled());
885        assert!(config.payments.webhooks_enabled());
886        // Stripe wants a lowercase currency, and nobody writes one.
887        assert_eq!(config.payments.default_currency(), "eur");
888        // Untouched defaults still apply inside a section that was given.
889        assert!(config.payments.automatic_tax);
890        assert_eq!(config.payments.timeout_secs, 20);
891
892        fs::remove_dir_all(dir).unwrap();
893    }
894
895    /// A configured provider with no signing secret still takes money — the
896    /// checkout is Stripe's page — but nothing of ours would hear that it
897    /// worked, so the two questions are answered separately.
898    #[test]
899    fn webhooks_need_their_own_secret() {
900        let payments = PaymentsConfig {
901            provider: "stripe".into(),
902            secret_key: "sk_test".into(),
903            ..PaymentsConfig::default()
904        };
905        assert!(payments.enabled());
906        assert!(!payments.webhooks_enabled());
907    }
908
909    /// Asking for a VAT number is only useful to somebody computing tax with
910    /// it, so the default follows automatic tax — and an app can still say
911    /// otherwise in either direction.
912    #[test]
913    fn tax_id_collection_follows_automatic_tax_unless_told_otherwise() {
914        let with_tax = PaymentsConfig::default();
915        assert!(with_tax.automatic_tax && with_tax.collects_tax_ids());
916
917        let no_tax = PaymentsConfig {
918            automatic_tax: false,
919            ..PaymentsConfig::default()
920        };
921        assert!(!no_tax.collects_tax_ids());
922
923        let explicit = PaymentsConfig {
924            automatic_tax: false,
925            tax_id_collection: Some(true),
926            ..PaymentsConfig::default()
927        };
928        assert!(explicit.collects_tax_ids());
929    }
930
931    /// `enabled = false` has to beat a perfectly good URL, or switching the
932    /// cache off would mean deleting the settings needed to switch it back on.
933    #[test]
934    fn a_disabled_cache_stays_off_even_with_a_url() {
935        let config = CacheConfig {
936            enabled: false,
937            url: "redis://127.0.0.1:6379".into(),
938            ..CacheConfig::default()
939        };
940        assert!(!config.is_active());
941    }
942
943    /// `Config::load` reads its file through the same expansion every other
944    /// app-directory TOML gets — including a URL assembled from several
945    /// variables, which is the case a whole-value substitution can't do.
946    #[test]
947    fn load_expands_environment_references_anywhere_in_the_file() {
948        std::env::set_var("APIPLANT_TEST_JWT", "from-env-jwt");
949        std::env::set_var("APIPLANT_TEST_MAIL", "from-env-key");
950        std::env::set_var("APIPLANT_TEST_DB_USER", "alice");
951        std::env::set_var("APIPLANT_TEST_DB_PASS", "s3cret");
952        let dir = temp_dir("env");
953        fs::write(
954            dir.join("main.toml"),
955            r#"
956[server]
957domain = "${APIPLANT_TEST_DOMAIN:-api.example.com}"
958
959[database]
960url = "postgres://$APIPLANT_TEST_DB_USER:$APIPLANT_TEST_DB_PASS@db:5432/app"
961
962[auth]
963jwt_secret = "$APIPLANT_TEST_JWT"
964
965[email]
966provider = "brevo"
967api_key = "${APIPLANT_TEST_MAIL}"
968from = "no-reply@example.com"
969"#,
970        )
971        .unwrap();
972
973        let config = Config::load(&dir).unwrap();
974        assert_eq!(
975            config.database.resolved_url(),
976            "postgres://alice:s3cret@db:5432/app"
977        );
978        assert_eq!(config.auth.jwt_secret, "from-env-jwt");
979        assert_eq!(config.email.api_key, "from-env-key");
980        // An unset variable falls back to the default written beside it.
981        assert_eq!(config.server.domain, ["api.example.com"]);
982
983        for name in [
984            "APIPLANT_TEST_JWT",
985            "APIPLANT_TEST_MAIL",
986            "APIPLANT_TEST_DB_USER",
987            "APIPLANT_TEST_DB_PASS",
988        ] {
989            std::env::remove_var(name);
990        }
991        fs::remove_dir_all(dir).unwrap();
992    }
993
994    #[test]
995    fn load_treats_wildcard_host_and_domain_as_everything() {
996        for (host, domain) in [
997            ("", "\"\""),
998            ("*", "\"*\""),
999            (" 0.0.0.0 ", "\"_\""),
1000            ("*", "[]"),
1001            // A wildcard beside named hosts still means "answer any host".
1002            ("*", "[\"api.example.com\", \"*\"]"),
1003        ] {
1004            let dir = temp_dir("wildcards");
1005            fs::write(
1006                dir.join("main.toml"),
1007                format!("[server]\nhost = \"{host}\"\ndomain = {domain}\n"),
1008            )
1009            .unwrap();
1010
1011            let config = Config::load(&dir).unwrap();
1012
1013            assert_eq!(config.server.host, "0.0.0.0", "host {host:?}");
1014            assert!(config.server.domain.is_empty(), "domain {domain}");
1015            fs::remove_dir_all(&dir).unwrap();
1016        }
1017    }
1018
1019    /// `domain` takes a list as readily as a single string, and each entry is
1020    /// trimmed the same way.
1021    #[test]
1022    fn load_accepts_a_list_of_domains() {
1023        let dir = temp_dir("domains");
1024        fs::write(
1025            dir.join("main.toml"),
1026            "[server]\ndomain = [\"api.example.com\", \" www.example.com \"]\n",
1027        )
1028        .unwrap();
1029
1030        let config = Config::load(&dir).unwrap();
1031
1032        assert_eq!(config.server.domain, ["api.example.com", "www.example.com"]);
1033        fs::remove_dir_all(dir).unwrap();
1034    }
1035
1036    #[test]
1037    fn load_normalises_paths_and_prefers_explicit_database_url() {
1038        let dir = temp_dir("normalise");
1039        fs::write(
1040            dir.join("main.toml"),
1041            r#"
1042[server]
1043base_path = "api/"
1044workers = 8
1045
1046[database]
1047url = "postgres://db.example/custom"
1048host = "ignored"
1049port = 9999
1050name = "ignored"
1051user = "ignored"
1052password = "ignored"
1053
1054[docs]
1055path = "swagger"
1056
1057[admin]
1058path = "console/"
1059
1060[admin.ai_assistance]
1061enabled = true
1062system = "Return only the field content."
1063prompt_placeholder = "Tell AI what to draft"
1064
1065[public]
1066dir = "site"
1067not_found = "oops.html"
1068"#,
1069        )
1070        .unwrap();
1071
1072        let config = Config::load(&dir).unwrap();
1073
1074        assert_eq!(config.server.base_path, "/api");
1075        assert_eq!(config.server.workers, Some(8));
1076        assert_eq!(config.docs.path, "/swagger");
1077        assert_eq!(config.admin.path, "/console");
1078        assert!(config.admin.ai_assistance.enabled);
1079        assert_eq!(
1080            config.admin.ai_assistance.system,
1081            "Return only the field content."
1082        );
1083        assert_eq!(
1084            config.admin.ai_assistance.prompt_placeholder,
1085            "Tell AI what to draft"
1086        );
1087        assert_eq!(config.public.dir, "site");
1088        assert_eq!(config.public.not_found.as_deref(), Some("oops.html"));
1089        assert_eq!(
1090            config.database.resolved_url(),
1091            "postgres://db.example/custom"
1092        );
1093
1094        fs::remove_dir_all(dir).unwrap();
1095    }
1096
1097    #[test]
1098    fn resolved_url_is_assembled_from_parts_when_url_is_empty() {
1099        let config = DatabaseConfig {
1100            url: String::new(),
1101            host: "db".into(),
1102            port: 5433,
1103            name: "plants".into(),
1104            user: "alice".into(),
1105            password: "secret".into(),
1106            max_connections: 16,
1107            auto_migrate: true,
1108        };
1109
1110        assert_eq!(
1111            config.resolved_url(),
1112            "postgres://alice:secret@db:5433/plants"
1113        );
1114    }
1115}