aboutsummaryrefslogtreecommitdiffstats
path: root/src/api/access.rs
blob: ade6542cad56b645c91a9d661dc864a40c7e5477 (plain)
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
//! What the user of a request may do, from the user registry (`access`), checked on
//! every request ([`access.md`](../../docs/access.md)): the endpoints by `authorize`,
//! the store's paths by its handlers, through the `Access` it leaves on the request.

use axum::{
    body::Body,
    extract::State,
    http::{Method, Request, StatusCode},
    response::Response,
};
use serde_json::Value as JsonValue;
use tracing::{debug, warn};

use super::auth::AuthenticatedUser;
use super::error_response;
use crate::access::{Caps, Right, registry};
use crate::document::meta;
use crate::state::AppState;

/// What the user of a request may do (a request extension, set by `authorize`).
#[derive(Clone, Debug)]
pub(crate) enum Access {
    /// The swarm has no registry (one from before it, `access.md`): every user the
    /// node lets in may do what all could before; protocol data only those in
    /// `--protocol-writers` (`store::parse_write_path`).
    Everything,
    /// What its registry entry gives.
    Caps(Caps),
}

/// How much of a place a user may read (`Access::visible`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Visible {
    /// It and all below it.
    All,
    /// Only what lies below it on the way to what it may read (a map's keys leading
    /// there, as a directory one may pass through but not list): `prune`.
    Partly,
    Nothing,
}

impl Access {
    pub(crate) fn allows(&self, right: Right, path: &[String]) -> bool {
        match self {
            Self::Everything => true,
            Self::Caps(caps) => caps.allows(right, path),
        }
    }

    pub(crate) fn visible(&self, path: &[String]) -> Visible {
        match self {
            Self::Everything => Visible::All,
            // The root holds protocol data too, which a capability on `[]` doesn't give.
            Self::Caps(caps)
                if caps.allows(Right::Read, path)
                    && (!path.is_empty() || caps.allows(Right::Read, &meta::path(&[]))) =>
            {
                Visible::All
            }
            Self::Caps(caps) if caps.reaches(Right::Read, path) => Visible::Partly,
            Self::Caps(_) => Visible::Nothing,
        }
    }
}

/// `value`, read at `path`, as much of it as `access` lets its user read: of a map it
/// may only partly read, the keys on the way to what it may (recursively); a list, a
/// text or a scalar it may only partly read is left out, as a list's items have no path
/// of their own to give rights to. `typed`: `value` is typed JSON
/// (`typed::JsonForm::typed`), whose maps may be tagged (`{"$map": {…}}`) and whose
/// tagged values (`{"$uint": 5}`) are scalars. None if nothing of it is readable.
pub(crate) fn prune(
    value: JsonValue,
    path: &mut Vec<String>,
    access: &Access,
    typed: bool,
) -> Option<JsonValue> {
    match access.visible(path) {
        Visible::All => return Some(value),
        Visible::Nothing => return None,
        Visible::Partly => {}
    }
    let JsonValue::Object(map) = value else {
        return None;
    };
    let tag = |map: &serde_json::Map<String, JsonValue>| {
        (typed && map.len() == 1)
            .then(|| {
                map.keys()
                    .next()
                    .filter(|key| key.starts_with('$'))
                    .cloned()
            })
            .flatten()
    };
    let map = match tag(&map) {
        None => map,
        Some(tag) if tag == "$map" => match map.into_iter().next() {
            Some((_, JsonValue::Object(inner))) => inner,
            _ => return None,
        },
        // A tagged scalar or text.
        Some(_) => return None,
    };
    let mut out = serde_json::Map::new();
    for (key, child) in map {
        path.push(key.clone());
        let child = prune(child, path, access, typed);
        path.pop();
        if let Some(child) = child {
            out.insert(key, child);
        }
    }
    // A map whose only key looks like a tag is tagged itself.
    Some(match tag(&out) {
        Some(_) => serde_json::json!({ "$map": out }),
        None => JsonValue::Object(out),
    })
}

/// A shallow read of `path` (`store::read_shallow`), its `entries` only those `access`
/// lets its user read at least partly.
pub(crate) fn prune_shallow(mut value: JsonValue, path: &[String], access: &Access) -> JsonValue {
    if access.visible(path) == Visible::All {
        return value;
    }
    if let Some(entries) = value.get_mut("entries").and_then(JsonValue::as_object_mut) {
        let mut child = path.to_vec();
        entries.retain(|key, _| {
            child.push(key.clone());
            let visible = access.visible(&child) != Visible::Nothing;
            child.pop();
            visible
        });
        let size = entries.len();
        value["size"] = size.into();
    }
    value
}

/// What an endpoint needs (`needed`).
#[derive(Debug, PartialEq, Eq)]
enum Need {
    /// The store and its streams: their handlers check each path.
    Store,
    /// Looking at this node (its figures, peers, dashboard): any capability.
    Observe,
    /// A right on protocol data.
    Protocol(Right, Vec<String>),
}

/// What a request to `path` by `method` needs. Remakes' records and forget records
/// are protocol data of their own: proposing or aborting a remake needs `write` on
/// `_continuum/remakes`, forgetting a peer on `_continuum/forgotten`; everything else
/// this node's operators do (its log filter, exports, quarantine, the changes) needs
/// protocol data itself, reading it to look, writing it to act.
fn needed(method: &Method, path: &str) -> Need {
    let looking = method == Method::GET || method == Method::HEAD;
    let protocol = |right, parts: &[&str]| Need::Protocol(right, meta::path(parts));
    let under = |prefix: &str| path == prefix || path.starts_with(&format!("{prefix}/"));
    if under("/store") || under("/stream") {
        Need::Store
    } else if (path == "/peers" && looking) || path == "/admin/stats" || under("/admin/dashboard") {
        Need::Observe
    } else if under("/peers") {
        protocol(Right::Write, &[meta::FORGOTTEN])
    } else if under("/admin/remakes") {
        if looking {
            protocol(Right::Read, &[meta::REMAKES])
        } else {
            protocol(Right::Write, &[meta::REMAKES])
        }
    } else if looking && !under("/debug") {
        protocol(Right::Read, &[])
    } else {
        protocol(Right::Write, &[])
    }
}

/// Finds what the request's user may do, refuses the request if its endpoint needs
/// more (`needed`), and leaves `Access` on it for the store's handlers. Inside
/// `auth::basic_auth`, which found the user. A user the registry doesn't have may do
/// nothing: `403`.
pub(crate) async fn authorize(
    State(state): State<AppState>,
    mut request: Request<Body>,
    next: axum::middleware::Next,
) -> Response {
    let Some(AuthenticatedUser(user)) = request.extensions().get::<AuthenticatedUser>().cloned()
    else {
        return error_response(StatusCode::UNAUTHORIZED, "not authenticated", None);
    };
    let access = {
        let replica = state.doc.read().await;
        if !registry::exists(&replica.doc) {
            Access::Everything
        } else if state.protocol_writers.contains(&user)
            && registry::managers(&replica.doc).is_empty()
        {
            // Nobody may manage users any more (two removals at once, merged; or an
            // entry damaged): this node's protocol writers may set it right.
            warn!(user = %user, "The user registry has nobody who may manage users; a protocol writer may do everything until it has");
            Access::Everything
        } else {
            match registry::user(&replica.doc, &user) {
                Some(entry) => Access::Caps(entry.caps()),
                None => {
                    debug!(user = %user, "Refused a user the registry doesn't have");
                    return error_response(
                        StatusCode::FORBIDDEN,
                        format!("{user} is not a registered user (docs/access.md)"),
                        None,
                    );
                }
            }
        }
    };
    let allowed = match needed(request.method(), request.uri().path()) {
        Need::Store => true,
        Need::Observe => match &access {
            Access::Everything => true,
            Access::Caps(caps) => !caps.is_empty(),
        },
        Need::Protocol(right, path) => access.allows(right, &path),
    };
    if !allowed {
        debug!(user = %user, method = %request.method(), path = %request.uri().path(), "Refused a request the user's capabilities don't cover");
        return error_response(
            StatusCode::FORBIDDEN,
            format!("{user} may not do that here (docs/access.md)"),
            None,
        );
    }
    request.extensions_mut().insert(access);
    next.run(request).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::access::Capability;
    use serde_json::json;

    fn path(text: &str) -> Vec<String> {
        text.split('/')
            .filter(|segment| !segment.is_empty())
            .map(str::to_owned)
            .collect()
    }

    fn caps(list: &[(&str, &[&str])]) -> Access {
        Access::Caps(Caps::new(
            list.iter()
                .map(|(at, rights)| Capability {
                    path: path(at),
                    rights: rights.iter().map(|right| (*right).to_owned()).collect(),
                    by: String::new(),
                    since: 0,
                })
                .collect(),
        ))
    }

    #[test]
    fn endpoints_and_what_they_need() {
        let read = |parts: &[&str]| Need::Protocol(Right::Read, meta::path(parts));
        let write = |parts: &[&str]| Need::Protocol(Right::Write, meta::path(parts));
        assert_eq!(needed(&Method::GET, "/store"), Need::Store);
        assert_eq!(needed(&Method::PUT, "/store/a/b"), Need::Store);
        assert_eq!(needed(&Method::GET, "/stream/a"), Need::Store);
        assert_eq!(needed(&Method::GET, "/storehouse"), read(&[]));
        assert_eq!(needed(&Method::GET, "/peers"), Need::Observe);
        assert_eq!(needed(&Method::GET, "/admin/stats"), Need::Observe);
        assert_eq!(
            needed(&Method::GET, "/admin/dashboard/state"),
            Need::Observe
        );
        assert_eq!(
            needed(&Method::POST, "/admin/dashboard/refresh"),
            Need::Observe
        );
        assert_eq!(
            needed(&Method::DELETE, "/peers/continuum:00"),
            write(&[meta::FORGOTTEN])
        );
        assert_eq!(
            needed(&Method::GET, "/admin/remakes/r1"),
            read(&[meta::REMAKES])
        );
        assert_eq!(
            needed(&Method::POST, "/admin/remakes"),
            write(&[meta::REMAKES])
        );
        assert_eq!(
            needed(&Method::DELETE, "/admin/remakes/r1"),
            write(&[meta::REMAKES])
        );
        assert_eq!(needed(&Method::GET, "/admin/config"), read(&[]));
        assert_eq!(needed(&Method::GET, "/admin/quarantine/q"), read(&[]));
        assert_eq!(
            needed(&Method::POST, "/admin/quarantine/q/replay"),
            write(&[])
        );
        assert_eq!(needed(&Method::PUT, "/admin/log"), write(&[]));
        assert_eq!(needed(&Method::GET, "/debug/firewall"), write(&[]));
    }

    #[test]
    fn what_a_user_sees_of_a_tree() {
        let tree = json!({
            "servers": { "eu": { "a": 1 }, "us": { "b": 2 } },
            "list": [1, 2],
            "_continuum": { "users": {} }
        });
        let reader = caps(&[("servers/eu", &["read"]), ("list/0", &["read"])]);
        assert_eq!(
            prune(tree.clone(), &mut Vec::new(), &reader, false),
            Some(json!({ "servers": { "eu": { "a": 1 } } }))
        );
        let data = caps(&[("", &["read", "write"])]);
        assert_eq!(
            prune(tree.clone(), &mut Vec::new(), &data, false),
            Some(json!({ "servers": { "eu": { "a": 1 }, "us": { "b": 2 } }, "list": [1, 2] }))
        );
        assert_eq!(
            prune(tree.clone(), &mut Vec::new(), &Access::Everything, false),
            Some(tree.clone())
        );
        assert_eq!(
            prune(tree, &mut Vec::new(), &caps(&[("x", &["read"])]), false),
            Some(json!({}))
        );
        assert_eq!(
            prune(json!(1), &mut path("y"), &caps(&[("x", &["read"])]), false),
            None
        );
    }

    #[test]
    fn typed_json_keeps_its_tags() {
        let reader = caps(&[("m/$x", &["read"]), ("n/k", &["read"])]);
        let tree = json!({
            "m": { "$map": { "$x": 1, "$y": 2 } },
            "n": { "k": { "$uint": 5 }, "$z": 1 }
        });
        assert_eq!(
            prune(tree, &mut Vec::new(), &reader, true),
            Some(json!({ "m": { "$map": { "$x": 1 } }, "n": { "k": { "$uint": 5 } } }))
        );
        // A tagged scalar on the way is no map.
        let tagged = json!({ "t": { "$text": "hello" } });
        assert_eq!(
            prune(tagged, &mut Vec::new(), &caps(&[("t/x", &["read"])]), true),
            Some(json!({}))
        );
    }

    #[test]
    fn a_shallow_read_lists_the_way() {
        let read = json!({ "type": "map", "size": 3,
                           "entries": { "a": {}, "b": {}, "_continuum": {} } });
        let reader = caps(&[("a/x", &["read"])]);
        assert_eq!(
            prune_shallow(read.clone(), &[], &reader),
            json!({ "type": "map", "size": 1, "entries": { "a": {} } })
        );
        assert_eq!(prune_shallow(read.clone(), &[], &Access::Everything), read);
    }
}