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
//! Protocol selection: which API protocols (REST, GraphQL, RPC) a service
//! exposes, how they are deployed, and which one a request is served with.
//!
//! [`ProtocolConfig::from_env`] reads the `KRAB_PROTOCOL_*` variables and
//! [`ProtocolConfig::validate`] checks them at startup; the request-time
//! resolution lives in the `rest` HTTP stack. `grpc` is deliberately not a
//! protocol here — see ADR 0007.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Versioned RPC envelope for additive schema evolution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcEnvelope<T> {
/// The payload.
pub data: T,
/// Optional request id for correlation; omitted from the JSON when `None`.
#[serde(skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
/// Version of the payload schema, chosen by the producer.
pub schema_version: u32,
/// Free-form feature names agreed between producer and consumer; Krab
/// attaches no meaning to them. Omitted from the JSON when empty and
/// defaulted to empty when absent.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub feature_flags: Vec<String>,
/// A producer-set compatibility marker; Krab attaches no behaviour to it.
/// Always serialised, and defaulted to `false` when absent.
#[serde(default)]
pub compatibility_mode: bool,
}
impl<T> RpcEnvelope<T> {
/// Wraps `data` at schema `version`, with no request id, no feature flags
/// and compatibility mode off.
pub fn new(data: T, version: u32) -> Self {
Self {
data,
request_id: None,
schema_version: version,
feature_flags: vec![],
compatibility_mode: false,
}
}
/// Sets the request id.
pub fn with_request_id(mut self, id: String) -> Self {
self.request_id = Some(id);
self
}
/// Sets `compatibility_mode` to `true`.
pub fn with_compatibility_mode(mut self) -> Self {
self.compatibility_mode = true;
self
}
}
/// Supported API transport protocols.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProtocolKind {
/// JSON REST endpoints (`rest`).
Rest,
/// GraphQL (`graphql`).
Graphql,
/// Krab's JSON-over-HTTP RPC (`rpc`). Not gRPC.
Rpc,
}
impl ProtocolKind {
/// Parse from a case-insensitive string.
///
/// `"grpc"` is **not** accepted. It used to map to [`Self::Rpc`], so a
/// service configured with `KRAB_PROTOCOL_ENABLED=grpc` came up exposing
/// Krab's JSON-over-HTTP RPC and reported itself as satisfying a gRPC
/// requirement. Krab has no gRPC transport — `tonic` and `prost` appear
/// nowhere in the workspace — so failing configuration validation is the
/// honest outcome. See ADR 0007.
pub fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"rest" => Some(Self::Rest),
"graphql" => Some(Self::Graphql),
"rpc" => Some(Self::Rpc),
_ => None,
}
}
/// The lowercase wire name (`rest`, `graphql`, `rpc`), as used in
/// configuration, the `x-krab-protocol` header and metric labels.
pub fn as_str(&self) -> &'static str {
match self {
Self::Rest => "rest",
Self::Graphql => "graphql",
Self::Rpc => "rpc",
}
}
}
/// How many protocol adapters the service exposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExposureMode {
/// Exactly one protocol adapter.
Single,
/// Two or more protocol adapters.
Multi,
}
impl ExposureMode {
/// Parses `single` or `multi`, case-insensitively; `None` otherwise.
pub fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"single" => Some(Self::Single),
"multi" => Some(Self::Multi),
_ => None,
}
}
}
/// Deployment shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeploymentTopology {
/// One process serves all adapters.
SingleService,
/// Each protocol gets its own microservice binary.
SplitServices,
}
impl DeploymentTopology {
/// Parses `single_service` or `split_services`, case-insensitively;
/// `None` otherwise.
pub fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"single_service" => Some(Self::SingleService),
"split_services" => Some(Self::SplitServices),
_ => None,
}
}
}
/// Advertised protocol capabilities for a service.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceCapabilities {
/// Name of the service advertising these capabilities.
pub service: String,
/// Protocol used when a request does not select one.
pub default_protocol: ProtocolKind,
/// Every protocol the service exposes.
pub supported_protocols: Vec<ProtocolKind>,
/// Maps protocol → base route, e.g. Rest → "/api/v1/users".
pub protocol_routes: HashMap<ProtocolKind, String>,
}
/// Policy constraints on protocol exposure.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProtocolPolicy {
/// Operation name → allowed protocols.
/// If an operation is listed here, only those protocols are valid.
pub restricted_operations: HashMap<String, Vec<ProtocolKind>>,
/// Tenant ID → allowed protocols override.
///
/// If a tenant is listed here, allowed protocols are additionally constrained
/// to this list.
pub tenant_overrides: HashMap<String, Vec<ProtocolKind>>,
}
/// Full runtime protocol config loaded from env at startup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolConfig {
/// `KRAB_PROTOCOL_EXPOSURE_MODE` (default `single`). `single` requires
/// exactly one enabled protocol.
pub exposure_mode: ExposureMode,
/// `KRAB_PROTOCOL_ENABLED_<SERVICE>` or `KRAB_PROTOCOL_ENABLED` (default
/// `[rest]`). The default protocol is always added if missing.
pub enabled_protocols: Vec<ProtocolKind>,
/// `KRAB_PROTOCOL_DEFAULT` (default `rest`): served when neither the
/// route family nor an allowed client preference picks one.
pub default_protocol: ProtocolKind,
/// `KRAB_PROTOCOL_TOPOLOGY` (default `single_service`).
/// `split_services` also requires `KRAB_PROTOCOL_SPLIT_TARGETS_JSON`.
pub topology: DeploymentTopology,
/// Per-operation and per-tenant restrictions.
pub policy: ProtocolPolicy,
/// Disabled by default. When false, `x-krab-protocol` must not be used for switching.
pub allow_runtime_switch_header: bool,
}
impl Default for ProtocolConfig {
fn default() -> Self {
Self {
exposure_mode: ExposureMode::Single,
enabled_protocols: vec![ProtocolKind::Rest],
default_protocol: ProtocolKind::Rest,
topology: DeploymentTopology::SingleService,
policy: ProtocolPolicy::default(),
allow_runtime_switch_header: false,
}
}
}
impl ProtocolConfig {
/// Build from environment variables.
///
/// Env vars consumed:
/// - `KRAB_PROTOCOL_EXPOSURE_MODE`=single|multi
/// - `KRAB_PROTOCOL_ENABLED`=rest,graphql,rpc
/// - `KRAB_PROTOCOL_ENABLED_<SERVICE>`=rest,graphql,rpc (service-local override)
/// - `KRAB_PROTOCOL_DEFAULT`=rest|graphql|rpc
/// - `KRAB_PROTOCOL_TOPOLOGY`=single_service|split_services
/// - `KRAB_PROTOCOL_RESTRICTED_OPS_JSON`={"operation":["rest"]}
/// - `KRAB_PROTOCOL_TENANT_OVERRIDES_JSON`={"tenant-a":["graphql"]}
/// - `KRAB_PROTOCOL_ALLOW_RUNTIME_SWITCH_HEADER`=true|false
pub fn from_env() -> Self {
let mut config = Self::default();
if let Ok(raw) = std::env::var("KRAB_PROTOCOL_EXPOSURE_MODE") {
if let Some(mode) = ExposureMode::parse(&raw) {
config.exposure_mode = mode;
}
}
if let Ok(raw) = std::env::var("KRAB_PROTOCOL_DEFAULT") {
if let Some(protocol) = ProtocolKind::parse(&raw) {
config.default_protocol = protocol;
}
}
let service_name = std::env::var("KRAB_SERVICE_NAME")
.or_else(|_| std::env::var("KRAB_SERVICE"))
.unwrap_or_else(|_| "service".to_string());
if let Some(service_local) = parse_service_local_enabled(&service_name) {
config.enabled_protocols = service_local;
} else if let Ok(raw) = std::env::var("KRAB_PROTOCOL_ENABLED") {
let parsed = parse_protocol_csv(&raw);
if !parsed.is_empty() {
config.enabled_protocols = parsed;
}
}
if !config.enabled_protocols.contains(&config.default_protocol) {
config.enabled_protocols.push(config.default_protocol);
}
if let Ok(raw) = std::env::var("KRAB_PROTOCOL_TOPOLOGY") {
if let Some(topology) = DeploymentTopology::parse(&raw) {
config.topology = topology;
}
}
if let Ok(raw) = std::env::var("KRAB_PROTOCOL_ALLOW_RUNTIME_SWITCH_HEADER") {
if let Some(value) = parse_bool(&raw) {
config.allow_runtime_switch_header = value;
}
}
let mut policy = ProtocolPolicy::default();
// Malformed policy JSON must not silently drop every restriction:
// log loudly here, and `validate()` reports it as a startup error.
if let Ok(raw) = std::env::var("KRAB_PROTOCOL_RESTRICTED_OPS_JSON") {
match parse_protocol_map_json(&raw) {
Some(restricted_operations) => policy.restricted_operations = restricted_operations,
None => tracing::error!("protocol_restricted_ops_json_malformed"),
}
}
if let Ok(raw) = std::env::var("KRAB_PROTOCOL_TENANT_OVERRIDES_JSON") {
match parse_protocol_map_json(&raw) {
Some(tenant_overrides) => policy.tenant_overrides = tenant_overrides,
None => tracing::error!("protocol_tenant_overrides_json_malformed"),
}
}
config.policy = policy;
config
}
/// Validate startup invariants.
pub fn validate(&self) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
if self.enabled_protocols.is_empty() {
errors.push("enabled_protocols must not be empty".to_string());
}
if !self.enabled_protocols.contains(&self.default_protocol) {
errors.push(format!(
"default protocol '{}' is not present in enabled_protocols",
self.default_protocol.as_str()
));
}
if self.exposure_mode == ExposureMode::Single && self.enabled_protocols.len() != 1 {
errors.push(format!(
"single exposure mode requires exactly one enabled protocol (found {})",
self.enabled_protocols.len()
));
}
for (operation, protocols) in &self.policy.restricted_operations {
for protocol in protocols {
if !self.enabled_protocols.contains(protocol) {
errors.push(format!(
"restricted operation '{}' contains unsupported protocol '{}'",
operation,
protocol.as_str()
));
}
}
}
for (tenant_id, protocols) in &self.policy.tenant_overrides {
for protocol in protocols {
if !self.enabled_protocols.contains(protocol) {
errors.push(format!(
"tenant override '{}' contains unsupported protocol '{}'",
tenant_id,
protocol.as_str()
));
}
}
}
// Policy env vars that failed to parse never made it into
// `self.policy`, so the loops above cannot see them. Re-check the raw
// sources: bad JSON silently dropping every restriction (fail-open)
// and an unknown protocol name silently becoming deny-all are both
// config mistakes that must fail startup, not pass validation.
for env_key in [
"KRAB_PROTOCOL_RESTRICTED_OPS_JSON",
"KRAB_PROTOCOL_TENANT_OVERRIDES_JSON",
] {
let Ok(raw) = std::env::var(env_key) else {
continue;
};
match serde_json::from_str::<HashMap<String, Vec<String>>>(&raw) {
Ok(map) => {
for (entry, protocols) in map {
for name in protocols {
if ProtocolKind::parse(&name).is_none() {
errors.push(format!(
"{env_key}: entry '{entry}' names unknown protocol '{name}'"
));
}
}
}
}
Err(error) => errors.push(format!("{env_key} is not valid JSON: {error}")),
}
}
if self.topology == DeploymentTopology::SplitServices {
let split_targets = std::env::var("KRAB_PROTOCOL_SPLIT_TARGETS_JSON")
.ok()
.map(|v| v.trim().to_string())
.unwrap_or_default();
if split_targets.is_empty() {
errors.push(
"split_services topology requires KRAB_PROTOCOL_SPLIT_TARGETS_JSON".to_string(),
);
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
/// Axum handler that answers with the [`ServiceCapabilities`] held in router
/// state, as JSON.
#[cfg(feature = "rest")]
pub async fn capabilities_handler(
axum::extract::State(caps): axum::extract::State<ServiceCapabilities>,
) -> axum::Json<ServiceCapabilities> {
axum::Json(caps)
}
fn parse_bool(value: &str) -> Option<bool> {
let normalized = value.trim();
if normalized.eq_ignore_ascii_case("true") || normalized == "1" {
return Some(true);
}
if normalized.eq_ignore_ascii_case("false") || normalized == "0" {
return Some(false);
}
None
}
fn parse_protocol_csv(value: &str) -> Vec<ProtocolKind> {
let mut out = Vec::new();
for token in value.split(',').map(str::trim).filter(|s| !s.is_empty()) {
if let Some(protocol) = ProtocolKind::parse(token) {
if !out.contains(&protocol) {
out.push(protocol);
}
}
}
out
}
fn parse_protocol_map_json(value: &str) -> Option<HashMap<String, Vec<ProtocolKind>>> {
let raw: HashMap<String, Vec<String>> = serde_json::from_str(value).ok()?;
let mut parsed = HashMap::new();
for (key, protocols) in raw {
let mut out = Vec::new();
for protocol in protocols {
if let Some(kind) = ProtocolKind::parse(&protocol) {
if !out.contains(&kind) {
out.push(kind);
}
}
}
parsed.insert(key, out);
}
Some(parsed)
}
fn parse_service_local_enabled(service_name: &str) -> Option<Vec<ProtocolKind>> {
let suffix = service_name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_uppercase()
} else {
'_'
}
})
.collect::<String>();
let key = format!("KRAB_PROTOCOL_ENABLED_{suffix}");
let raw = std::env::var(key).ok()?;
let parsed = parse_protocol_csv(&raw);
if parsed.is_empty() {
None
} else {
Some(parsed)
}
}