-
Notifications
You must be signed in to change notification settings - Fork 70
/
lib.rs
372 lines (327 loc) · 10.6 KB
/
lib.rs
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
//! Access control.
//!
//! Access control in Attic is simple and stateless [0] - The server validates
//! the JWT against a HS256 key and allows access based on the `https://jwt.attic.rs/v1`
//! claim.
//!
//! One primary goal of the Attic Server is easy scalability. It's designed
//! to be deployed to serverless platforms like fly.io and have fast
//! cold-start times. Instances are created and destoyed rapidly in response
//! to requests.
//!
//! [0] We may revisit this later :)
//!
//! ## Opaqueness
//!
//! The token format is unstable and claims beyond the standard ones defined
//! in RFC 7519 should never be interpreted by the client. The token might not
//! even be a valid JWT, in which case the client must not throw an error.
//!
//! ## Cache discovery
//!
//! If the JWT grants any permission at all to the requested cache name,
//! then the bearer is able to discover the presence of the cache, meaning
//! that NoSuchCache or Forbidden can be returned depending on the scenario.
//! Otherwise, the user will get a generic 401 response (Unauthorized)
//! regardless of the request (or whether the cache exists or not).
//!
//! ## Supplying the token
//!
//! The JWT can be supplied to the server in one of two ways:
//!
//! - As a normal Bearer token.
//! - As the password in Basic Auth (used by Nix). The username is ignored.
//!
//! To add the token to Nix, use the following format in `~/.config/nix/netrc`:
//!
//! ```text
//! machine attic.server.tld password eyJhb...
//! ```
//!
//! ## Example token
//!
//! ```json
//! {
//! "sub": "meow",
//! "exp": 4102324986,
//! "https://jwt.attic.rs/v1": {
//! "caches": {
//! "cache-rw": {
//! "w": 1,
//! "r": 1
//! },
//! "cache-ro": {
//! "r": 1
//! },
//! "team-*": {
//! "w": 1,
//! "r": 1,
//! "cc": 1
//! }
//! }
//! }
//! }
//! ```
#![deny(
asm_sub_register,
deprecated,
missing_abi,
unsafe_code,
unused_macros,
unused_must_use,
unused_unsafe
)]
#![deny(clippy::from_over_into, clippy::needless_question_mark)]
#![cfg_attr(
not(debug_assertions),
deny(unused_imports, unused_mut, unused_variables)
)]
pub mod util;
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::error::Error as StdError;
use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine};
use chrono::{DateTime, Utc};
use displaydoc::Display;
pub use jwt_simple::{
algorithms::{HS256Key, MACLike},
claims::{Claims, JWTClaims},
prelude::UnixTimeStamp,
};
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, BoolFromInt};
use attic::cache::{CacheName, CacheNamePattern};
/// Custom claim namespace for the AtticAccess information.
///
/// Custom claim namespaces are required by platforms like Auth0, and
/// custom claims without one will be silently dropped.
///
/// <https://auth0.com/docs/security/tokens/json-web-tokens/create-namespaced-custom-claims>
///
/// Also change the `#[serde(rename)]` below if you change this.
pub const CLAIM_NAMESPACE: &str = "https://jwt.attic.rs/v1";
macro_rules! require_permission_function {
($name:ident, $descr:literal, $member:ident) => {
pub fn $name(&self) -> Result<()> {
if !self.$member {
tracing::debug!("Client has no {} permission", $descr);
if self.can_discover() {
Err(Error::PermissionDenied)
} else {
Err(Error::NoDiscoveryPermission)
}
} else {
Ok(())
}
}
};
}
/// A validated JSON Web Token.
#[derive(Debug)]
pub struct Token(JWTClaims<TokenClaims>);
/// Claims of a JSON Web Token.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TokenClaims {
/// Attic namespace.
#[serde(rename = "https://jwt.attic.rs/v1")]
attic_ns: AtticAccess,
}
/// Permissions granted to a client.
///
/// This is the content of the `attic-access` claim in JWTs.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AtticAccess {
/// Cache permissions.
///
/// Keys here may include wildcards.
caches: HashMap<CacheNamePattern, CachePermission>,
}
/// Permission to a single cache.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CachePermission {
/// Can pull objects from the cache.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "r")]
#[serde_as(as = "BoolFromInt")]
pub pull: bool,
/// Can push objects to the cache.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "w")]
#[serde_as(as = "BoolFromInt")]
pub push: bool,
/// Can delete objects from the cache.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "d")]
#[serde_as(as = "BoolFromInt")]
pub delete: bool,
/// Can create the cache itself.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "cc")]
#[serde_as(as = "BoolFromInt")]
pub create_cache: bool,
/// Can reconfigure the cache.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "cr")]
#[serde_as(as = "BoolFromInt")]
pub configure_cache: bool,
/// Can configure retention/quota settings.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "cq")]
#[serde_as(as = "BoolFromInt")]
pub configure_cache_retention: bool,
/// Can destroy the cache itself.
#[serde(default = "CachePermission::permission_default")]
#[serde(skip_serializing_if = "is_false")]
#[serde(rename = "cd")]
#[serde_as(as = "BoolFromInt")]
pub destroy_cache: bool,
}
pub type Result<T> = std::result::Result<T, Error>;
/// An access error.
#[derive(Debug, Display)]
#[ignore_extra_doc_attributes]
pub enum Error {
/// User has no permission to this cache.
NoDiscoveryPermission,
/// User does not have permission to complete this action.
///
/// This implies that there is some permission granted to the
/// user, so the user is authorized to discover the cache.
PermissionDenied,
/// JWT error: {0}
TokenError(jwt_simple::Error),
/// Base64 decode error: {0}
Base64Error(base64::DecodeError),
}
impl Token {
/// Verifies and decodes a token.
pub fn from_jwt(token: &str, key: &HS256Key) -> Result<Self> {
key.verify_token(token, None)
.map_err(Error::TokenError)
.map(Token)
}
/// Creates a new token with an expiration timestamp.
pub fn new(sub: String, exp: &DateTime<Utc>) -> Self {
let claims = TokenClaims {
attic_ns: Default::default(),
};
Self(JWTClaims {
issued_at: None,
expires_at: Some(UnixTimeStamp::from_secs(
exp.timestamp().try_into().unwrap(),
)),
invalid_before: None,
issuer: None,
subject: Some(sub),
audiences: None,
jwt_id: None,
nonce: None,
custom: claims,
})
}
/// Encodes the token.
pub fn encode(&self, key: &HS256Key) -> Result<String> {
key.authenticate(self.0.clone()).map_err(Error::TokenError)
}
/// Returns the subject of the token.
pub fn sub(&self) -> Option<&str> {
self.0.subject.as_deref()
}
/// Returns the claims as a serializable value.
pub fn opaque_claims(&self) -> &impl Serialize {
&self.0
}
/// Returns a mutable reference to a permission entry.
pub fn get_or_insert_permission_mut(
&mut self,
pattern: CacheNamePattern,
) -> &mut CachePermission {
use std::collections::hash_map::Entry;
let access = self.attic_access_mut();
match access.caches.entry(pattern) {
Entry::Occupied(v) => v.into_mut(),
Entry::Vacant(v) => v.insert(CachePermission::default()),
}
}
/// Returns explicit permission granted for a cache.
pub fn get_permission_for_cache(&self, cache: &CacheName) -> CachePermission {
let access = self.attic_access();
let pattern_key = cache.to_pattern();
if let Some(direct_match) = access.caches.get(&pattern_key) {
return direct_match.clone();
}
for (pattern, permission) in access.caches.iter() {
if pattern.matches(cache) {
return permission.clone();
}
}
CachePermission::default()
}
fn attic_access(&self) -> &AtticAccess {
&self.0.custom.attic_ns
}
fn attic_access_mut(&mut self) -> &mut AtticAccess {
&mut self.0.custom.attic_ns
}
}
impl CachePermission {
/// Adds implicit grants for public caches.
pub fn add_public_permissions(&mut self) {
self.pull = true;
}
/// Returns whether the user is allowed to discover this cache.
///
/// This permission is implied when any permission is explicitly
/// granted.
pub const fn can_discover(&self) -> bool {
self.push
|| self.pull
|| self.delete
|| self.create_cache
|| self.configure_cache
|| self.destroy_cache
|| self.configure_cache_retention
}
pub fn require_discover(&self) -> Result<()> {
if !self.can_discover() {
Err(Error::NoDiscoveryPermission)
} else {
Ok(())
}
}
require_permission_function!(require_pull, "pull", pull);
require_permission_function!(require_push, "push", push);
require_permission_function!(require_delete, "delete", delete);
require_permission_function!(require_create_cache, "create cache", create_cache);
require_permission_function!(
require_configure_cache,
"reconfigure cache",
configure_cache
);
require_permission_function!(
require_configure_cache_retention,
"configure cache retention",
configure_cache_retention
);
require_permission_function!(require_destroy_cache, "destroy cache", destroy_cache);
fn permission_default() -> bool {
false
}
}
impl StdError for Error {}
pub fn decode_token_hs256_secret_base64(s: &str) -> Result<HS256Key> {
let secret = BASE64_STANDARD.decode(s).map_err(Error::Base64Error)?;
Ok(HS256Key::from_bytes(&secret))
}
// bruh
fn is_false(b: &bool) -> bool {
!b
}