Repository navigation
Expand file tree
/
Copy pathconfig.rs
More file actions
2874 lines (2621 loc) · 120 KB
/
Copy pathconfig.rs
File metadata and controls
2874 lines (2621 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Relay configuration from environment variables.
use std::time::Duration;
use std::{collections::HashMap, net::SocketAddr};
use sha2::{Digest, Sha256};
use thiserror::Error;
use tracing::{error, warn};
/// Default maximum inbound WebSocket frame size in bytes.
///
/// Must comfortably exceed accepted event content sizes after Nostr JSON and
/// NIP-44 encryption overhead.
pub const DEFAULT_MAX_FRAME_BYTES: usize = 512 * 1024;
/// Errors that can occur while loading relay configuration.
#[derive(Debug, Error)]
pub enum ConfigError {
/// The `BUZZ_BIND_ADDR` environment variable could not be parsed as a socket address.
#[error("invalid BUZZ_BIND_ADDR: {0}")]
InvalidBindAddr(String),
/// A configuration value failed validation.
#[error("invalid config: {0}")]
InvalidValue(String),
}
/// Authentication mode for the deployment-admin API.
///
/// Configured by `BUZZ_ADMIN_AUTH`: unset/empty/`nip98` → `Nip98` (fail-secure
/// default), `disabled` → `Disabled`, anything else is a startup error.
///
/// # Role resolution (nip98 mode only)
///
/// In `nip98` mode the authenticated pubkey is resolved to an
/// `AdminPrincipal` at request time via [`crate::api::admin::auth::resolve_admin_principal`]:
/// - `Operator/Config` if pubkey ∈ `RELAY_OPERATOR_PUBKEYS`
/// - `Operator/OwnerFallback` if pubkey == `RELAY_OWNER_PUBKEY` **and**
/// `RELAY_OPERATOR_PUBKEYS` is empty (evaluated from config, never runtime rows)
/// - `Moderator/Db` from the `relay_operators` table otherwise
/// - `None` → 403 (no fall-through role, ever)
///
/// Disabled mode serves every moderation read and refuses writes and staffing.
/// NIP-98 mode is read-write per resolved principal.
#[derive(Debug, Clone)]
pub enum AdminAuth {
/// Authentication disabled. The operator has explicitly asserted
/// that the admin API is protected at the network layer (reverse proxy,
/// VPN, firewall). `Host`/`Origin` checks remain active as defense-in-depth.
/// Selected by `BUZZ_ADMIN_AUTH=disabled`.
/// Every moderation read is served to anyone who can reach the relay;
/// `authorize()` returns `NetworkTrusted` with no identity, so write and
/// staffing routes always 403.
Disabled,
/// NIP-98 HTTP Auth. Every request must carry an `Authorization: Nostr`
/// header containing a signed kind-27235 event. The authenticated pubkey
/// is resolved to an [`crate::api::admin::auth::AdminPrincipal`] at request
/// time from config + DB. Selected by `BUZZ_ADMIN_AUTH=nip98` or by leaving
/// `BUZZ_ADMIN_AUTH` unset (fail-secure default). Read-write per resolved
/// principal; attributes mutations to a distinct human operator.
Nip98,
}
/// Deny-by-default deployment-admin configuration. Mutation and staffing routes
/// require a resolved principal (NIP-98 only); disabled mode serves reads only.
#[derive(Debug, Clone)]
pub struct AdminConfig {
/// Exact admin HTTP authority.
pub host: String,
/// Authentication mode selected at startup.
pub auth: AdminAuth,
/// Optional admin SPA bundle directory.
pub web_dir: Option<std::path::PathBuf>,
}
/// Relay-hosted policy content presented on join surfaces.
#[derive(Debug, Clone)]
pub struct JoinPolicyConfig {
/// Operator-provided Terms of Service document in Markdown.
pub terms_markdown: Option<String>,
/// Operator-provided Privacy Policy document in Markdown.
pub privacy_markdown: Option<String>,
/// Whether join surfaces must collect an 18+ attestation.
pub age_attestation_required: bool,
/// Content-derived identifier binding receipts to the exact policy revision.
pub version: String,
}
/// Optional KLIPY GIF-search integration owned by the relay operator.
///
/// The API key deliberately stays private and its [`Debug`] implementation is
/// redacted so dumping [`Config`] cannot disclose it.
#[derive(Clone)]
pub struct KlipyConfig {
api_key: String,
}
impl KlipyConfig {
/// Return the key only to the outbound KLIPY client.
pub(crate) fn api_key(&self) -> &str {
&self.api_key
}
}
impl std::fmt::Debug for KlipyConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KlipyConfig")
.field("api_key", &"[REDACTED]")
.finish()
}
}
/// Maximum configured jitter, leaving ten seconds of the hard-drain budget for
/// WebSocket close-frame delivery after the final delayed cancellation.
pub const MAX_DRAIN_JITTER_MS: u64 = 20_000;
/// Relay runtime configuration, loaded from environment variables.
#[derive(Debug, Clone)]
pub struct Config {
/// Address the relay HTTP/WebSocket server binds to.
pub bind_addr: SocketAddr,
/// Postgres database connection URL.
pub database_url: String,
/// Optional read-replica connection URL (e.g. an Aurora `cluster-ro-`
/// endpoint). Unset means all reads stay on the writer.
pub read_database_url: Option<String>,
/// Replica read budget `B` in milliseconds (`BUZZ_REPLICA_READ_MAX_AGE_MS`).
/// `0` (the default) disables bounded-staleness replica routing; see
/// [`buzz_db::DbConfig::replica_read_max_age_ms`].
pub replica_read_max_age_ms: u64,
/// Replica freshness budget for fleet usage telemetry
/// (`BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS`). Independent of serving-read
/// routing; defaults to 30 seconds and `0` disables telemetry DB queries.
pub usage_metrics_replica_max_age_ms: u64,
/// Upper bound, in milliseconds, of the per-connection random delay applied
/// when sending the `1012 Service Restart` close frame during graceful
/// shutdown (`BUZZ_DRAIN_JITTER_MS`). Each live connection is closed after
/// an independent delay drawn uniformly from `[1, drain_jitter_ms]` when
/// jitter is enabled, which
/// spreads client reconnects across the window instead of releasing the
/// whole pod's sockets in one instant (the reconnect thundering herd that
/// drives DB pool-timeout bursts on rolling deploys).
///
/// Default `0` reproduces the previous all-at-once close. Values above
/// [`MAX_DRAIN_JITTER_MS`] are capped, leaving headroom under the relay's
/// 30-second hard-drain timeout for close-frame delivery.
pub drain_jitter_ms: u64,
/// Redis connection URL used by the pub/sub manager.
pub redis_url: String,
/// Maximum connections in the shared Redis pool. Defaults to 16.
///
/// deadpool's own default is `CPU_COUNT * 2`, which on a 2-vCPU relay
/// pod is only 4 — small enough that rate-limit checks, presence, and
/// pub/sub publishes queue behind each other under load.
pub redis_pool_size: usize,
/// Maximum connections in the Postgres writer/reader pools. Defaults to 50.
///
/// The `buzz-db` default of 20 was sized for a handful of pods against
/// `max_connections=100`. Against Aurora (~5,000 connections) that cap
/// is the binding constraint: a burst of concurrent handlers exhausts
/// the per-pod pool and requests fail on acquire timeout while the
/// database sits idle.
pub db_pool_size: u32,
/// Maximum connections in the Postgres read-replica pool
/// (`BUZZ_DB_READ_POOL_SIZE`). Defaults to `db_pool_size`. Sized
/// independently so reader capacity can be tuned against the replica's
/// headroom without touching the writer pool.
pub db_read_pool_size: Option<u32>,
/// Public WebSocket URL of this relay, advertised in NIP-11.
pub relay_url: String,
/// Public WebSocket URL of the dedicated device-pairing relay, when configured.
pub pairing_relay_url: Option<String>,
/// Maximum number of concurrent WebSocket connections.
pub max_connections: usize,
/// Maximum number of concurrently executing message handlers.
pub max_concurrent_handlers: usize,
/// Per-connection outbound message buffer size (number of messages).
pub send_buffer_size: usize,
/// Maximum inbound WebSocket frame size in bytes.
pub max_frame_bytes: usize,
/// Number of consecutive buffer-full events tolerated before cancelling a slow client.
pub slow_client_grace_limit: u8,
/// Authentication provider configuration.
pub auth: buzz_auth::AuthConfig,
/// Whether REST API requests must present a valid token. Independent of
/// WebSocket protocol auth, which is *always* required by REQ/EVENT/COUNT.
pub require_auth_token: bool,
/// Opt-in private accessory API; disabled until explicitly deployed.
pub buzz_v1_enabled: bool,
/// How long an automatic thread follow stays live without the actor's
/// involvement; independent of NIP-RS retention.
pub buzz_v1_retention_seconds: u32,
/// Comma-separated list of allowed CORS origins.
/// If empty, permissive CORS is used (dev mode).
/// Example: "tauri://localhost,http://localhost:3000"
pub cors_origins: Vec<String>,
/// Optional hex-encoded private key for the relay's signing keypair.
/// If absent, a fresh keypair is generated at startup.
pub relay_private_key: Option<String>,
/// Optional Unix Domain Socket path. When set, the relay also listens on this
/// UDS for traffic (e.g. service mesh sidecar). Health probes still use TCP.
pub uds_path: Option<String>,
/// TCP port for the health-only router (`/_liveness`, `/_readiness`, `/_status`).
/// Separate from the app router so K8s probes bypass Istio and auth middleware.
pub health_port: u16,
/// TCP port for the Prometheus metrics exporter (`GET /metrics`).
pub metrics_port: u16,
/// Interval between read-only partition catalog audits.
pub partition_audit_interval: Duration,
/// Whether the partition manager may issue any partition DDL. Off also
/// disables catch-all advancement.
pub partition_manager_create_enabled: bool,
/// Whether the partition manager may replace an empty right-edge catch-all
/// with dedicated monthlies. Also enables periodic (not only startup) DDL.
/// Requires `partition_manager_create_enabled`.
pub partition_manager_advance_enabled: bool,
/// When true, NIP-42 pubkey-only authentication (no API token) is
/// restricted to pubkeys in the `pubkey_allowlist` table. Users with valid
/// API tokens bypass the allowlist entirely.
/// Applies to all NIP-42 pubkey-only connections, regardless of `require_auth_token`.
pub pubkey_allowlist_enabled: bool,
/// When true, every authenticated request must also pass a relay-level
/// membership check against the `relay_members` table.
/// When false (default), the check is a no-op and all authenticated callers
/// are permitted regardless of auth method (API token, NIP-42).
pub require_relay_membership: bool,
/// Whether this deployment can serve huddle (voice) audio.
///
/// Huddle audio frames are relayed peer-to-peer *within a single pod*
/// (`AudioRoomManager` is an in-process map; only huddle lifecycle events
/// cross pods via Redis). Under horizontal scaling (any-pod-any-connection,
/// plan §4 fork B) two peers in the same huddle can land on different pods
/// and never hear each other. Rather than sticky-route huddles or ship a
/// silent split-room (plan §5b, decided by Tyler), a horizontally-scaled
/// deployment sets this `false` and the relay surfaces a clear, client-
/// handleable "huddle audio unavailable" signal on join.
///
/// Defaults to `true` so single-pod deployments (the N=1 case) keep today's
/// behavior unchanged. Operators running multiple relay pods MUST set
/// `BUZZ_HUDDLE_AUDIO_AVAILABLE=false` until the out-of-relay media/SFU
/// service lands.
pub huddle_audio_available: bool,
/// Inter-relay mesh configuration (`BUZZ_MESH`, `BUZZ_MESH_BIND_ADDR`).
/// Opt-in: mesh forms only when `BUZZ_MESH=on` is explicit. The default
/// (absent/off) is exact single-instance behavior — no bind, no Redis
/// registry write — so an image upgrade with untouched env is a strict
/// no-regression rollout.
pub mesh: buzz_relay_mesh::MeshConfig,
/// Testbed-only reliable-stream echo consumer (`BUZZ_MESH_DEMO_ECHO`).
/// When `on`, the owner side of an inbound reliable mesh stream echoes
/// every validated `Data` frame back to the sender — a transport/
/// session-routing smoke for cross-pod evidence runs, NOT a product flow.
/// Same strict opt-in as `BUZZ_MESH`; default off means inbound reliable
/// streams are accepted, logged, and closed (no session consumer yet).
pub mesh_demo_echo: bool,
/// Optional hex-encoded pubkey of the relay owner.
/// When set, this pubkey is automatically bootstrapped into `relay_members`
/// with the `owner` role on first startup.
pub relay_owner_pubkey: Option<String>,
/// Canonical HTTP origin of the deployment-global operator API.
///
/// Every operator NIP-98 `u` tag is verified against this origin, independent
/// of the inbound HTTP `Host` header and tenant registry. Required only to
/// *use* the community-provisioning endpoints: when it is unset, those
/// endpoints fail closed at request time (see
/// `api::operator::authorize_operator_request`). It is NOT required at boot
/// even when `RELAY_OPERATOR_PUBKEYS` is set, because that allowlist is
/// shared with the NIP-98 admin console, which needs no origin. Set via
/// `RELAY_OPERATOR_API_ORIGIN` as an `http://` or `https://` origin with no
/// path, query, or fragment.
pub relay_operator_api_origin: Option<String>,
/// Deployment-level relay operator pubkeys allowed to use the
/// `/operator/communities` management endpoints.
///
/// Unlike `relay_owner_pubkey` (a role *within* the deployment community),
/// operators span tenants: they may create new communities and bootstrap
/// initial owners, but hold no implicit tenant membership row.
/// Empty (the default) disables community provisioning entirely — fail closed.
///
/// Set via `RELAY_OPERATOR_PUBKEYS` as a comma-separated list of 64-char
/// hex pubkeys. Invalid entries are rejected at startup (config error), not
/// skipped — a typo must not silently disable an operator.
pub relay_operator_pubkeys: Vec<String>,
/// Configured operator-listener identities and their HTTPS delivery URLs.
pub operator_listener_delivery_urls: HashMap<String, url::Url>,
/// Allow NIP-OA owner attestation for relay membership.
///
/// When `true` and `require_relay_membership` is also `true`, agents
/// bearing a valid NIP-OA `auth` tag can authenticate by proving their
/// owner is a relay member. The agent gets session-scoped access.
///
/// On open relays (`require_relay_membership = false`), NIP-OA owner
/// extraction for agent→owner backfill happens unconditionally (the
/// signature is cryptographically self-proving). This flag only controls
/// whether NIP-OA can grant membership access on closed relays.
///
/// Default: `false`. Set via `BUZZ_ALLOW_NIP_OA_AUTH=true`.
pub allow_nip_oa_auth: bool,
/// Relay-owned KLIPY integration. Unset means GIF search is not advertised
/// and its proxy routes return 404.
pub klipy: Option<KlipyConfig>,
/// Media storage configuration (S3/MinIO).
pub media: buzz_media::MediaConfig,
/// Maximum concurrent media uploads handled by one relay process.
pub media_max_concurrent_uploads: usize,
/// Maximum concurrent media uploads accepted from one pubkey.
pub media_max_concurrent_uploads_per_pubkey: u32,
/// Maximum media upload starts accepted from one pubkey per minute.
pub media_uploads_per_minute: u32,
/// Whether tamper-evident event/media audit logging is enabled. Defaults to true.
/// This does not control the separate `moderation_actions` audit trail.
/// Set `BUZZ_AUDIT_ENABLED=false` for deployments that do not require it.
pub audit_enabled: bool,
/// Optional override for ephemeral channel TTL (in seconds).
/// When set, any channel created with a TTL tag will use this value instead
/// of the client-provided one. Useful for testing ephemeral expiry quickly.
/// Example: `BUZZ_EPHEMERAL_TTL_OVERRIDE=60` → all ephemeral channels expire
/// 60 seconds after the last message.
pub ephemeral_ttl_override: Option<i32>,
/// Root directory for the relay's local git scratch. No authoritative
/// repository state lives here — runtime reads/writes hydrate ephemeral
/// repos from object storage per request. Temporary workspaces, buffered
/// subprocess output, and the disposable immutable pack cache live below
/// this path.
/// Repo-name uniqueness lives in Postgres (`git_repo_names`), not on disk,
/// so this directory need not be persistent or shared across replicas.
pub git_repo_path: std::path::PathBuf,
/// Parent directory for process-isolated immutable pack cache sessions.
pub git_pack_cache_path: std::path::PathBuf,
/// Maximum pack file size for git push (bytes). Default: 500 MB.
pub git_max_pack_bytes: u64,
/// Maximum total bytes materialized for one git repo request. Default: 1 GB.
///
/// This bounds clone/fetch hydration work across a repo's historical pack
/// set rather than only bounding one incoming push body.
pub git_max_repo_bytes: u64,
/// Maximum bytes retained in the process-local immutable pack/index cache.
/// Zero disables retention while preserving request-local hydration.
pub git_pack_cache_max_bytes: u64,
/// Maximum pack digests populated concurrently in one relay process.
pub git_pack_cache_max_concurrent_populations: usize,
/// Maximum number of repos per pubkey. Default: 100.
pub git_max_repos_per_pubkey: u32,
/// Maximum concurrent git subprocess operations. Default: 20.
pub git_max_concurrent_ops: usize,
/// HMAC secret for git pre-receive hook callbacks.
/// Used to authenticate internal policy endpoint requests.
pub git_hook_hmac_secret: String,
/// Whether NIP-PL push discovery, lease acceptance, enqueueing, matching, and delivery
/// are enabled for this deployment. Defaults to false.
pub push_enabled: bool,
/// Descriptor key identifier accepted in kind:30350 `exec` tags.
pub push_executor_key_id: String,
/// Exact HTTP(S) gateway endpoint used to sign and submit APNs delivery capabilities.
/// Required while push is enabled. An explicitly empty setting is allowed
/// only while push is disabled.
pub push_gateway_delivery_url: Option<url::Url>,
/// Hard timeout for one push gateway delivery request.
pub push_gateway_timeout: Duration,
/// Hard timeout for one operator-listener delivery request.
pub operator_listener_timeout: Duration,
/// Optional relay-hosted policy shown on join surfaces. Disabled when no
/// documents or age attestation are configured.
pub join_policy: Option<JoinPolicyConfig>,
/// Deployment-admin API and SPA configuration. Absent means the surface is disabled.
pub admin: Option<AdminConfig>,
/// Optional path to the web UI `dist/` directory.
/// When set, the relay serves the invite landing page and its static assets.
/// When unset, no static file serving happens (relay behaves as before).
pub web_dir: Option<std::path::PathBuf>,
/// Whether the configured web bundle serves Git browser routes in addition
/// to the public invite landing page. Defaults to false.
pub serve_git_web_gui: bool,
/// NIP-FI federated-identity enforcement configuration.
///
/// Selected by `BUZZ_NIP_FI_MODE`: `enforce` validates assertions at HTTP
/// ingress and (via S3) at WebSocket upgrade; `deny_protected` denies
/// protected requests without evaluating; `shadow` evaluates and records
/// the enforce verdict but admits exactly as `off`. `Off` (the default)
/// leaves all identity enforcement to NIP-42 alone.
pub nip_fi: crate::nip_fi_config::NipFiRelayConfig,
}
fn parse_bind_addr(raw: &str) -> Result<SocketAddr, ConfigError> {
raw.parse::<SocketAddr>()
.map_err(|e| ConfigError::InvalidBindAddr(e.to_string()))
}
fn positive_u64_from_env(name: &str, default: u64) -> Result<u64, ConfigError> {
match std::env::var(name) {
Ok(raw) => raw
.parse::<u64>()
.ok()
.filter(|value| *value > 0)
.ok_or_else(|| ConfigError::InvalidValue(format!("{name} must be a positive integer"))),
Err(std::env::VarError::NotPresent) => Ok(default),
Err(std::env::VarError::NotUnicode(_)) => Err(ConfigError::InvalidValue(format!(
"{name} must be valid Unicode"
))),
}
}
fn rate_limit_config_from_env() -> Result<buzz_auth::RateLimitConfig, ConfigError> {
let defaults = buzz_auth::RateLimitConfig::default();
Ok(buzz_auth::RateLimitConfig {
human_messages_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_HUMAN_MESSAGES_PER_MIN",
defaults.human_messages_per_min,
)?,
gif_searches_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_GIF_SEARCHES_PER_MIN",
defaults.gif_searches_per_min,
)?,
human_api_calls_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_HUMAN_API_CALLS_PER_MIN",
defaults.human_api_calls_per_min,
)?,
human_ws_events_per_sec: positive_u64_from_env(
"BUZZ_RATE_LIMIT_HUMAN_WS_EVENTS_PER_SEC",
defaults.human_ws_events_per_sec,
)?,
agent_standard_messages_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_AGENT_STANDARD_MESSAGES_PER_MIN",
defaults.agent_standard_messages_per_min,
)?,
agent_standard_api_calls_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_AGENT_STANDARD_API_CALLS_PER_MIN",
defaults.agent_standard_api_calls_per_min,
)?,
agent_elevated_messages_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_AGENT_ELEVATED_MESSAGES_PER_MIN",
defaults.agent_elevated_messages_per_min,
)?,
agent_platform_messages_per_min: positive_u64_from_env(
"BUZZ_RATE_LIMIT_AGENT_PLATFORM_MESSAGES_PER_MIN",
defaults.agent_platform_messages_per_min,
)?,
})
}
fn parse_operator_api_origin(raw: &str) -> Result<String, ConfigError> {
let raw = raw.trim();
let url = url::Url::parse(raw).map_err(|e| {
ConfigError::InvalidValue(format!("RELAY_OPERATOR_API_ORIGIN is not a valid URL: {e}"))
})?;
if !matches!(url.scheme(), "http" | "https")
|| url.host().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.path() != "/"
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(ConfigError::InvalidValue(
"RELAY_OPERATOR_API_ORIGIN must be an http(s) origin with no credentials, path, query, or fragment"
.to_string(),
));
}
Ok(raw.trim_end_matches('/').to_string())
}
fn parse_push_gateway_delivery_url(raw: &str) -> Result<url::Url, ConfigError> {
let url = url::Url::parse(raw.trim()).map_err(|e| {
ConfigError::InvalidValue(format!(
"BUZZ_PUSH_GATEWAY_DELIVERY_URL is not a valid URL: {e}"
))
})?;
if !matches!(url.scheme(), "http" | "https")
|| url.host().is_none()
|| (url.scheme() == "https" && url.port().is_some())
|| !url.username().is_empty()
|| url.password().is_some()
|| url.path() != "/v1/deliveries/apns"
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(ConfigError::InvalidValue(
"BUZZ_PUSH_GATEWAY_DELIVERY_URL must be an exact HTTP(S) /v1/deliveries/apns URL without credentials, query, or fragment; explicit ports are supported only for HTTP"
.to_string(),
));
}
Ok(url)
}
fn parse_operator_listener_delivery_urls(
raw: &str,
) -> Result<HashMap<String, url::Url>, ConfigError> {
let mut endpoints = HashMap::new();
let entries: Vec<&str> = raw
.split(';')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.collect();
if !raw.trim().is_empty() && entries.is_empty() {
return Err(ConfigError::InvalidValue(
"BUZZ_OPERATOR_LISTENERS must contain pubkey:delivery_url pairs".to_string(),
));
}
for entry in entries {
let (pubkey, delivery_url) = entry.split_once(':').ok_or_else(|| {
ConfigError::InvalidValue(
"BUZZ_OPERATOR_LISTENERS entries must be pubkey:delivery_url pairs".to_string(),
)
})?;
let pubkey = pubkey.trim().to_ascii_lowercase();
if pubkey.len() != 64 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(ConfigError::InvalidValue(format!(
"BUZZ_OPERATOR_LISTENERS entry has an invalid pubkey: {pubkey:?}"
)));
}
let url = url::Url::parse(delivery_url.trim()).map_err(|e| {
ConfigError::InvalidValue(format!(
"BUZZ_OPERATOR_LISTENERS endpoint is not a valid URL: {e}"
))
})?;
if url.scheme() != "https"
|| url.host().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(ConfigError::InvalidValue(
"BUZZ_OPERATOR_LISTENERS endpoints must be HTTPS URLs without credentials, query, or fragment"
.to_string(),
));
}
if endpoints.insert(pubkey.clone(), url).is_some() {
return Err(ConfigError::InvalidValue(format!(
"BUZZ_OPERATOR_LISTENERS contains duplicate pubkey: {pubkey}"
)));
}
}
Ok(endpoints)
}
fn parse_bool(name: &str, default: bool) -> Result<bool, ConfigError> {
match std::env::var(name) {
Err(std::env::VarError::NotPresent) => Ok(default),
Err(error) => Err(ConfigError::InvalidValue(format!(
"{name} must be valid UTF-8: {error}"
))),
Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "on" => Ok(true),
"false" | "0" | "off" | "" => Ok(false),
_ => Err(ConfigError::InvalidValue(format!(
"{name} must be true or false"
))),
},
}
}
fn parse_optional_bool(name: &str) -> Result<bool, ConfigError> {
parse_bool(name, false)
}
fn ensure_git_repo_path(
raw: impl Into<std::path::PathBuf>,
) -> Result<std::path::PathBuf, ConfigError> {
ensure_git_path("BUZZ_GIT_REPO_PATH", raw)
}
fn ensure_git_path(
setting: &str,
raw: impl Into<std::path::PathBuf>,
) -> Result<std::path::PathBuf, ConfigError> {
let git_repo_path = raw.into();
if let Err(e) = std::fs::create_dir_all(&git_repo_path) {
return Err(ConfigError::InvalidValue(format!(
"{setting}={} could not be created: {e}",
git_repo_path.display()
)));
}
Ok(git_repo_path)
}
/// Env vars that once gated authenticated media reads.
///
/// `BUZZ_REQUIRE_MEDIA_GET_AUTH` was the real flag; `BUZZ_REQUIRE_MEDIA_READ_AUTH`
/// was documented in `.env.example` as an accepted alias but was never read by
/// the relay. Media reads are now unconditionally authenticated, so both are
/// inert and an operator still setting either — especially to `false` — holds a
/// belief about their deployment that is no longer true.
const INERT_MEDIA_READ_AUTH_VARS: [&str; 2] = [
"BUZZ_REQUIRE_MEDIA_GET_AUTH",
"BUZZ_REQUIRE_MEDIA_READ_AUTH",
];
/// Which of `names` are present, so startup can warn that they do nothing.
///
/// `lookup` is injected rather than calling `std::env::var` directly: process
/// env is global mutable state, so a test that set real vars would race every
/// other test in the binary.
fn inert_env_vars<'a>(names: &[&'a str], lookup: impl Fn(&str) -> Option<String>) -> Vec<&'a str> {
names
.iter()
.copied()
.filter(|name| lookup(name).is_some())
.collect()
}
impl Config {
/// Loads configuration from environment variables, falling back to development defaults.
pub fn from_env() -> Result<Self, ConfigError> {
let bind_addr_raw =
std::env::var("BUZZ_BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:3000".to_string());
let bind_addr = parse_bind_addr(&bind_addr_raw)?;
let database_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); // sadscan:disable np.postgres.1
let read_database_url = std::env::var("READ_DATABASE_URL")
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty());
// The old seconds-denominated name is a hard startup error, not an
// alias: silently honouring it would mean 1000x the intended budget.
if std::env::var("BUZZ_REPLICA_HEAD_MAX_AGE_SECS").is_ok() {
return Err(ConfigError::InvalidValue(
"BUZZ_REPLICA_HEAD_MAX_AGE_SECS was renamed to BUZZ_REPLICA_READ_MAX_AGE_MS \
(note: milliseconds, not seconds); refusing to start"
.to_string(),
));
}
// Replica read budget: 0 = off (the rollout default), so this is a
// non-negative parse, unlike `positive_u64_from_env`.
let replica_read_max_age_ms = match std::env::var("BUZZ_REPLICA_READ_MAX_AGE_MS") {
Ok(raw) => raw.trim().parse::<u64>().map_err(|_| {
ConfigError::InvalidValue(
"BUZZ_REPLICA_READ_MAX_AGE_MS must be a non-negative integer".to_string(),
)
})?,
Err(_) => 0,
};
let usage_metrics_replica_max_age_ms =
match std::env::var("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS") {
Ok(raw) => raw.trim().parse::<u64>().map_err(|_| {
ConfigError::InvalidValue(
"BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS must be a non-negative integer"
.to_string(),
)
})?,
Err(_) => 30_000,
};
// Drain jitter: 0 = off (default). Clamp oversized values so every
// delayed close is initiated with ten seconds left in the relay's
// hard-drain budget. An empty/whitespace-only value is treated as unset
// (jitter off), matching the sibling vars in this file — so setting the
// var to "" is a valid kill switch, not a crashloop.
let drain_jitter_ms = match std::env::var("BUZZ_DRAIN_JITTER_MS") {
Ok(raw) if raw.trim().is_empty() => 0,
Ok(raw) => raw
.trim()
.parse::<u64>()
.map_err(|_| {
ConfigError::InvalidValue(
"BUZZ_DRAIN_JITTER_MS must be a non-negative integer".to_string(),
)
})?
.min(MAX_DRAIN_JITTER_MS),
Err(_) => 0,
};
let redis_url =
std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6379".to_string());
let redis_pool_size = std::env::var("BUZZ_REDIS_POOL_SIZE")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|&v| v > 0)
.unwrap_or(16);
let db_pool_size = std::env::var("BUZZ_DB_POOL_SIZE")
.ok()
.and_then(|v| v.parse::<u32>().ok())
.filter(|&v| v > 0)
.unwrap_or(50);
let db_read_pool_size = std::env::var("BUZZ_DB_READ_POOL_SIZE")
.ok()
.and_then(|v| v.parse::<u32>().ok())
.filter(|&v| v > 0);
let relay_url =
std::env::var("RELAY_URL").unwrap_or_else(|_| "ws://localhost:3000".to_string());
let pairing_relay_url = std::env::var("BUZZ_PAIRING_RELAY_URL")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.map(|value| {
let parsed = url::Url::parse(&value).map_err(|e| {
ConfigError::InvalidValue(format!(
"BUZZ_PAIRING_RELAY_URL must be a valid ws:// or wss:// URL: {e}"
))
})?;
if !matches!(parsed.scheme(), "ws" | "wss") || parsed.host_str().is_none() {
return Err(ConfigError::InvalidValue(
"BUZZ_PAIRING_RELAY_URL must be a valid ws:// or wss:// URL".to_string(),
));
}
Ok(value)
})
.transpose()?;
let max_connections = std::env::var("BUZZ_MAX_CONNECTIONS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10_000);
let max_concurrent_handlers = std::env::var("BUZZ_MAX_CONCURRENT_HANDLERS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(1024);
let send_buffer_size = std::env::var("BUZZ_SEND_BUFFER")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(1_000);
let max_frame_bytes = std::env::var("BUZZ_MAX_FRAME_BYTES")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|&v| v > 0)
.unwrap_or(DEFAULT_MAX_FRAME_BYTES);
let slow_client_grace_limit = std::env::var("BUZZ_SLOW_CLIENT_GRACE_LIMIT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(15);
let require_auth_token = std::env::var("BUZZ_REQUIRE_AUTH_TOKEN")
.map(|v| v == "true" || v == "1")
.unwrap_or(false);
let pubkey_allowlist_enabled = std::env::var("BUZZ_PUBKEY_ALLOWLIST")
.map(|v| v == "true" || v == "1")
.unwrap_or(false);
let require_relay_membership = std::env::var("BUZZ_REQUIRE_RELAY_MEMBERSHIP")
.map(|v| v == "true" || v == "1")
.unwrap_or(false);
// Defaults true → single-pod (N=1) keeps today's huddle behavior. A
// horizontally-scaled deployment sets this false; see the field doc.
let huddle_audio_available = std::env::var("BUZZ_HUDDLE_AUDIO_AVAILABLE")
.map(|v| !(v == "false" || v == "0"))
.unwrap_or(true);
// Mesh opt-in: default OFF. Strict rollout no-regression — an image
// upgrade with untouched env must not bind a new UDP port or write a
// new Redis key. Horizontally-scaled deployments explicitly set
// `BUZZ_MESH=on`; anything else (absent, `off`, other values) keeps
// exact single-instance behavior.
let mesh_enabled = std::env::var("BUZZ_MESH")
.map(|v| v.eq_ignore_ascii_case("on") || v == "true" || v == "1")
.unwrap_or(false);
let mesh_bind_addr = std::env::var("BUZZ_MESH_BIND_ADDR")
.map(|raw| {
raw.parse::<SocketAddr>().map_err(|e| {
ConfigError::InvalidValue(format!("invalid BUZZ_MESH_BIND_ADDR: {e}"))
})
})
.unwrap_or_else(|_| Ok("0.0.0.0:3478".parse().expect("static default parses")))?;
let mesh = buzz_relay_mesh::MeshConfig {
enabled: mesh_enabled,
bind_addr: mesh_bind_addr,
registry_refresh: std::time::Duration::from_secs(15),
};
// Demo echo opt-in: same strict pattern as BUZZ_MESH — explicit
// `on`/`true`/`1` only, anything else (absent, `off`, typos) is off.
let mesh_demo_echo = std::env::var("BUZZ_MESH_DEMO_ECHO")
.map(|v| v.eq_ignore_ascii_case("on") || v == "true" || v == "1")
.unwrap_or(false);
let allow_nip_oa_auth = std::env::var("BUZZ_ALLOW_NIP_OA_AUTH")
.map(|v| v == "true" || v == "1")
.unwrap_or(false);
let klipy = std::env::var("BUZZ_KLIPY_API_KEY")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.map(|api_key| KlipyConfig { api_key });
// Note: intentionally not prefixed with BUZZ_ — this is a relay-identity
// config that may be shared across multiple services (e.g., ACP agent).
let relay_owner_pubkey = std::env::var("RELAY_OWNER_PUBKEY")
.ok()
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty())
.map(|s| {
// Must be exactly 64 lowercase hex characters (32-byte pubkey).
// Fail closed — once RELAY_OWNER_PUBKEY can be the break-glass
// operator root (owner-fallback B), silently discarding a malformed
// value would be a lockout, not a graceful degradation.
let valid = s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit());
if valid {
Ok(s)
} else {
Err(ConfigError::InvalidValue(format!(
"RELAY_OWNER_PUBKEY is not a valid 64-char hex pubkey — \
got: {s:?}. Fix or unset it; a malformed value is a startup error \
because this key can serve as the break-glass operator root when \
RELAY_OPERATOR_PUBKEYS is empty."
)))
}
})
.transpose()?;
// Note: intentionally not prefixed with BUZZ_ — same relay-identity
// config family as RELAY_OWNER_PUBKEY. Comma-separated 64-char hex
// pubkeys. Unlike RELAY_OWNER_PUBKEY (warn-and-ignore), an invalid
// entry here is a hard config error: silently dropping an operator
// pubkey would silently disable provisioning for that operator.
let relay_operator_api_origin = std::env::var("RELAY_OPERATOR_API_ORIGIN")
.ok()
.filter(|raw| !raw.trim().is_empty())
.map(|raw| parse_operator_api_origin(&raw))
.transpose()?;
let relay_operator_pubkeys = match std::env::var("RELAY_OPERATOR_PUBKEYS") {
Ok(raw) => {
let mut pubkeys = Vec::new();
for entry in raw.split(',') {
let entry = entry.trim().to_lowercase();
if entry.is_empty() {
continue;
}
let valid = entry.len() == 64 && entry.chars().all(|c| c.is_ascii_hexdigit());
if !valid {
return Err(ConfigError::InvalidValue(format!(
"RELAY_OPERATOR_PUBKEYS entry is not a valid 64-char hex pubkey: {entry:?}"
)));
}
if !pubkeys.contains(&entry) {
pubkeys.push(entry);
}
}
pubkeys
}
Err(_) => Vec::new(),
};
if !relay_operator_pubkeys.is_empty() && relay_operator_api_origin.is_none() {
// Do NOT fail closed at boot: RELAY_OPERATOR_PUBKEYS is the shared
// allowlist for BOTH the community-provisioning endpoints and the
// NIP-98 admin console. Only provisioning needs the canonical
// origin, so requiring it at boot would force admin-console
// operators to configure a provisioning surface they never use.
// The provisioning endpoints stay fail-closed at request time
// (see `api::operator::authorize_operator_request`, which rejects
// when the origin is unconfigured); this warning names that so an
// operator who *did* want provisioning knows why it 500s.
warn!(
"RELAY_OPERATOR_PUBKEYS is set but RELAY_OPERATOR_API_ORIGIN is not — \
the community-provisioning endpoints (POST /operator/communities) will \
reject every request until RELAY_OPERATOR_API_ORIGIN is set. The NIP-98 \
admin console does not require it and is unaffected."
);
}
let operator_listener_delivery_urls = match std::env::var("BUZZ_OPERATOR_LISTENERS") {
Ok(raw) => parse_operator_listener_delivery_urls(&raw)?,
Err(std::env::VarError::NotPresent) => HashMap::new(),
Err(error) => {
return Err(ConfigError::InvalidValue(format!(
"BUZZ_OPERATOR_LISTENERS must be valid UTF-8: {error}"
)));
}
};
if !operator_listener_delivery_urls.is_empty() && relay_operator_api_origin.is_none() {
error!(
"BUZZ_OPERATOR_LISTENERS is set but RELAY_OPERATOR_API_ORIGIN is not — operator-listener registration requests will reject every request until RELAY_OPERATOR_API_ORIGIN is set"
);
}
let auth = buzz_auth::AuthConfig {
rate_limits: rate_limit_config_from_env()?,
};
if !require_auth_token {
warn!(
"BUZZ_REQUIRE_AUTH_TOKEN is false — REST API requests bypass token auth. \
WebSocket protocol auth is unaffected. Set to true for production."
);
}
let cors_origins = std::env::var("BUZZ_CORS_ORIGINS")
.unwrap_or_default()
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
let relay_private_key = std::env::var("BUZZ_RELAY_PRIVATE_KEY").ok();
let uds_path = std::env::var("BUZZ_UDS_PATH")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let health_port = std::env::var("BUZZ_HEALTH_PORT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(8080);
let metrics_port = std::env::var("BUZZ_METRICS_PORT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(9102);
// Catalog-only and cheap, but clamp operator mistakes away from a hot
// loop or a multi-day observability gap.
let partition_audit_interval = Duration::from_secs(
std::env::var("BUZZ_PARTITION_AUDIT_INTERVAL_SECS")
.ok()
.and_then(|value| value.parse::<u64>().ok())
.unwrap_or(15 * 60)
.clamp(60, 24 * 60 * 60),
);
let partition_manager_create_enabled =
parse_bool("BUZZ_PARTITION_MANAGER_CREATE_ENABLED", true)?;
// Off by default: each environment opts in after its canary.
let partition_manager_advance_enabled =
parse_bool("BUZZ_PARTITION_MANAGER_ADVANCE_ENABLED", false)?;
let s3_addressing_style = match std::env::var("BUZZ_S3_ADDRESSING_STYLE") {
Ok(value) => value.parse().map_err(ConfigError::InvalidValue)?,
Err(std::env::VarError::NotPresent) => buzz_media::config::S3AddressingStyle::default(),
Err(std::env::VarError::NotUnicode(_)) => {
return Err(ConfigError::InvalidValue(
"BUZZ_S3_ADDRESSING_STYLE must be valid Unicode and one of 'path' or 'virtual'"
.to_string(),
));
}
};
let media = buzz_media::MediaConfig {
s3_endpoint: std::env::var("BUZZ_S3_ENDPOINT")
.unwrap_or_else(|_| "http://localhost:9000".to_string()),
s3_access_key: std::env::var("BUZZ_S3_ACCESS_KEY")
.unwrap_or_else(|_| "buzz_dev".to_string()),
s3_secret_key: std::env::var("BUZZ_S3_SECRET_KEY")
.unwrap_or_else(|_| "buzz_dev_secret".to_string()),
s3_bucket: std::env::var("BUZZ_S3_BUCKET").unwrap_or_else(|_| "buzz-media".to_string()),
s3_region: std::env::var("BUZZ_S3_REGION")
.or_else(|_| std::env::var("AWS_REGION"))
.unwrap_or_else(|_| "us-east-1".to_string()),
s3_addressing_style,
max_image_bytes: std::env::var("BUZZ_MAX_IMAGE_BYTES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(50 * 1024 * 1024),
max_gif_bytes: std::env::var("BUZZ_MAX_GIF_BYTES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10 * 1024 * 1024),
max_video_bytes: std::env::var("BUZZ_MAX_VIDEO_BYTES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(500 * 1024 * 1024),
max_file_bytes: std::env::var("BUZZ_MAX_FILE_BYTES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(100 * 1024 * 1024),
public_base_url: std::env::var("BUZZ_MEDIA_BASE_URL")
.unwrap_or_else(|_| "http://localhost:3000/media".to_string()),
// Per-upload-event records (`_uploads/` moderation side channel).
// Off by default; coherence between the three knobs is enforced in
// MediaConfig::validate at startup.
upload_records_enabled: std::env::var("BUZZ_MEDIA_UPLOAD_RECORDS")
.map(|v| v == "true" || v == "1")
.unwrap_or(false),
upload_ip_header: std::env::var("BUZZ_MEDIA_UPLOAD_IP_HEADER")
.ok()
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty()),