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
//! Repository and namespace identifiers (PRD §6.1).
//!
//! Single deployments retain their configured name and `root` namespace.
//! Multi deployments use SPEC-TRANSPORT-CONNECT §7.4 identities.
use mkit_core::repo_identity::{Namespace, RepositoryIdentity};
use crate::error::ServerError;
use crate::policy::NamespacePolicy;
/// Longest accepted repository name, matching the auth v2 `repository`
/// component bound (`mkit_core::write_auth`).
pub(crate) const MAX_REPO_NAME_BYTES: usize = 255;
/// The namespace a single-repository deployment uses: a reserved sentinel.
/// SPEC-TRANSPORT-CONNECT §7.4 namespaces are always `ed25519-<64 hex>` or
/// `0x<40 hex>`, so no request can ever select `root`. It matches the
/// `vcs-worker` `RefStore` instance name, so M0 needs no Durable Object
/// migration (planner default Q13).
const DEPLOYMENT_DEFAULT_NAMESPACE: &str = "root";
/// A repository name: 1..=255 bytes of printable ASCII with no whitespace
/// (bytes `0x21..=0x7e`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RepoName(String);
impl RepoName {
/// Validate `name`.
///
/// # Errors
/// [`crate::Code::InvalidArgument`] if `name` is empty, longer than 255
/// bytes, or holds a byte outside `0x21..=0x7e`.
pub fn new(name: impl Into<String>) -> Result<Self, ServerError> {
let name = name.into();
if name.is_empty()
|| name.len() > MAX_REPO_NAME_BYTES
|| !name.bytes().all(|b| (0x21..=0x7e).contains(&b))
{
return Err(ServerError::invalid_argument(
"repository name must be 1-255 printable ASCII bytes without whitespace",
));
}
Ok(Self(name))
}
/// The name as given.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
/// A namespace key. Under D34 it selects the namespace coordinator and
/// prefixes every shard key. Single deployments use the reserved default;
/// Multi deployments use a parsed self-certifying namespace (§7.4).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NamespaceKey(String);
impl NamespaceKey {
/// The namespace of a single-repository deployment: the reserved
/// sentinel `"root"`, which the SPEC-TRANSPORT-CONNECT §7.4 namespace
/// grammar (`ed25519-…` / `0x…`) can never select.
#[must_use]
pub fn deployment_default() -> Self {
Self(DEPLOYMENT_DEFAULT_NAMESPACE.to_owned())
}
/// The key as a string.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
/// A canonical namespace already validated by the shared grammar.
#[must_use]
pub fn from_namespace(namespace: &Namespace) -> Self {
Self(namespace.to_string())
}
/// A key read back from storage (`Partition::decode`): the store only
/// ever holds keys this server encoded.
pub(crate) fn from_stored(key: String) -> Self {
Self(key)
}
}
/// A repository's full identity.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RepoId {
/// Owning namespace.
pub namespace: NamespaceKey,
/// Name within the namespace.
pub name: RepoName,
}
/// Multi-repository addressing with a deployment namespace policy.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MultiAddressing {
/// Namespaces permitted for writes. Defaults to an empty allowlist.
pub namespace_policy: NamespacePolicy,
}
impl MultiAddressing {
/// Route requests using their namespaced `X-Repository` identity.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Route with the given namespace policy (SPEC-TRANSPORT-CONNECT §7.5).
#[must_use]
pub fn with_namespace_policy(mut self, policy: NamespacePolicy) -> Self {
self.namespace_policy = policy;
self
}
}
/// A resolved request target and its byte-exact wire identity.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResolvedRepo {
/// The storage identity (single deployments retain the M0 layout).
pub repo: RepoId,
/// The identity carried on the wire.
pub identity: String,
}
/// How a deployment maps a request to a repository.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Addressing {
/// One configured repository, with optional addressing on unsigned RPCs.
Single {
/// The configured repository.
repo: RepoId,
},
/// Routes by `X-Repository`. The adapters serve it (WP-1.30);
/// R-111(1)'s no-deployment-before-WP-1.14 rule still applies to the
/// whole branch (ticket expiry).
Multi(MultiAddressing),
}
impl Addressing {
/// Resolve the request target using SPEC-TRANSPORT-CONNECT §7.4.
/// Empty headers count as absent; identities are never normalized.
///
/// # Errors
/// `invalid_argument` for malformed identities or missing Multi headers;
/// `unauthenticated` for missing signed Single headers; `not_found` for
/// another well-formed identity on a Single deployment.
pub fn resolve(
&self,
x_repository: Option<&str>,
signed: bool,
) -> Result<ResolvedRepo, ServerError> {
let header = x_repository.filter(|s| !s.is_empty());
let invalid = || ServerError::invalid_argument("invalid X-Repository");
match self {
Self::Single { repo } => {
// A Single deployment under the reserved `root` namespace
// keeps its bare-name wire identity; a self-certifying
// namespace (`mkit serve --root`, WP-1.15) is part of it.
let identity = if repo.namespace == NamespaceKey::deployment_default() {
repo.name.as_str().to_owned()
} else {
format!("{}/{}", repo.namespace.as_str(), repo.name.as_str())
};
if let Some(header) = header {
RepositoryIdentity::parse_bare_allowed(header).map_err(|_| invalid())?;
if header != identity {
return Err(ServerError::repository_not_found());
}
} else if signed {
return Err(ServerError::unauthenticated(
"missing X-Repository on a signed request",
));
}
Ok(ResolvedRepo {
repo: repo.clone(),
identity,
})
}
Self::Multi(_) => {
let header = header.ok_or_else(invalid)?;
let identity = RepositoryIdentity::parse(header).map_err(|_| invalid())?;
let namespace = identity.namespace().ok_or_else(invalid)?;
Ok(ResolvedRepo {
repo: RepoId {
namespace: NamespaceKey::from_namespace(namespace),
name: RepoName::new(identity.name())?,
},
identity: header.to_owned(),
})
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Code;
#[test]
fn repo_name_rejects_whitespace_newline_empty_and_256_bytes() {
for bad in [
String::new(),
"has space".into(),
"tab\there".into(),
"line\nbreak".into(),
"trailing\r".into(),
"del\u{7f}".into(),
"caf\u{e9}".into(),
"a".repeat(256),
] {
let err = RepoName::new(bad.clone()).expect_err(&bad);
assert_eq!(err.code(), Code::InvalidArgument);
}
for good in [
"a".to_owned(),
"room-a".into(),
"~!@#/x_y.z".into(),
"a".repeat(255),
] {
assert_eq!(RepoName::new(good.clone()).unwrap().as_str(), good);
}
}
#[test]
fn single_addressing_rejects_another_identity() {
let addressing = Addressing::Single {
repo: RepoId {
namespace: NamespaceKey::deployment_default(),
name: RepoName::new("room-a").unwrap(),
},
};
assert_eq!(
addressing
.resolve(Some("room-b"), false)
.unwrap_err()
.code(),
Code::NotFound
);
}
fn single(identity: &str) -> Addressing {
Addressing::Single {
repo: RepoId {
namespace: NamespaceKey::deployment_default(),
name: RepoName::new(identity).unwrap(),
},
}
}
#[test]
fn resolution_table_and_safe_errors() {
let single = single("default");
let multi = Addressing::Multi(MultiAddressing::new());
for signed in [false, true] {
for absent in [None, Some("")] {
let result = single.resolve(absent, signed);
if signed {
let e = result.unwrap_err();
assert_eq!(e.code(), Code::Unauthenticated);
assert_eq!(
e.public_message(),
"missing X-Repository on a signed request"
);
} else {
assert_eq!(
result.unwrap(),
single.resolve(Some("default"), false).unwrap()
);
}
let e = multi.resolve(absent, signed).unwrap_err();
assert_eq!(e.code(), Code::InvalidArgument);
assert_eq!(e.public_message(), "invalid X-Repository");
}
assert_eq!(
single
.resolve(Some("default"), signed)
.unwrap()
.repo
.namespace
.as_str(),
"root"
);
for bad in ["Default", ".x", "has space", "a/b"] {
let e = single.resolve(Some(bad), signed).unwrap_err();
assert_eq!(e.code(), Code::InvalidArgument);
assert_eq!(e.public_message(), "invalid X-Repository");
}
let identity = format!("ed25519-{}/one", "a".repeat(64));
for other in ["other", &identity] {
let e = single.resolve(Some(other), signed).unwrap_err();
assert_eq!(e.code(), Code::NotFound);
assert_eq!(e.public_message(), "repository not found");
}
let resolved = multi.resolve(Some(&identity), signed).unwrap();
assert_eq!(resolved.identity, identity);
assert_eq!(resolved.repo.namespace.as_str(), &identity[..72]);
assert_eq!(resolved.repo.name.as_str(), "one");
assert_eq!(
multi.resolve(Some("default"), signed).unwrap_err().code(),
Code::InvalidArgument
);
let configured = self::single(&identity)
.resolve(Some(&identity), true)
.unwrap();
assert_eq!(configured.repo.namespace.as_str(), "root");
assert_eq!(configured.repo.name.as_str(), identity);
}
}
#[test]
fn golden_repository_grammar_drives_both_modes() {
#[derive(serde::Deserialize)]
struct Case {
identity: String,
single_ok: bool,
multi_ok: bool,
}
let bytes = include_bytes!("../../../tests/golden/transport/repository-grammar.json");
let cases: Vec<Case> = serde_json::from_slice(bytes).unwrap();
let manifest = include_str!("../../../tests/golden/transport/MANIFEST.txt");
let digest = mkit_core::hash::to_hex(&mkit_core::hash::hash(bytes));
assert!(
manifest
.lines()
.any(|line| line == format!("repository-grammar.json {digest}"))
);
let multi = Addressing::Multi(MultiAddressing::new());
for case in cases {
// Valid Single cases configure their byte-exact identity; invalid
// cases use a valid config and must fail grammar, not equality.
for (addressing, valid) in [
(
single(if case.single_ok {
&case.identity
} else {
"default"
}),
case.single_ok,
),
(multi.clone(), case.multi_ok),
] {
let result = addressing.resolve(Some(&case.identity), false);
if valid {
assert_eq!(result.unwrap().identity, case.identity);
} else {
assert_eq!(
result.unwrap_err().code(),
Code::InvalidArgument,
"{}",
case.identity
);
}
}
}
}
#[test]
fn deployment_default_namespace_is_stable() {
assert_eq!(NamespaceKey::deployment_default().as_str(), "root");
}
}