Repository navigation
Expand file tree
/
Copy pathwebauthn_controller.rs
More file actions
331 lines (304 loc) · 8.46 KB
/
Copy pathwebauthn_controller.rs
File metadata and controls
331 lines (304 loc) · 8.46 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
use chrono::{DateTime, Local};
use rocket::form::Form;
use rocket::http::{CookieJar, Status};
use rocket::response::content::RawHtml;
use rocket::response::status::Custom;
use rocket::response::{Redirect, Responder};
use rocket::{State, serde::json::Json};
use webauthn_rs::prelude::*;
use webauthn_rs_proto::{
AuthenticatorSelectionCriteria, ResidentKeyRequirement,
UserVerificationPolicy,
};
use crate::DbConn;
use crate::config::Config;
use crate::controllers::pages_controller::rocket_uri_macro_home_page;
use crate::ephemeral::session::{
SessionCookie, UserSession, stored_redirect_or,
};
use crate::errors::{
AuthenticationError, Either, LoginError, Result, ZauthError,
};
use crate::models::passkey::{NewPassKey, PassKey};
use crate::models::session::Session;
use crate::models::user::User;
use crate::views::accepter::Accepter;
use crate::webauthn::WebAuthnStore;
#[post("/webauthn/start_register", format = "json", data = "<residential>")]
pub async fn start_register(
// from body
residential: Json<bool>,
// from headers
session: UserSession,
// injected
webauthn_store: &State<WebAuthnStore>,
db: DbConn,
) -> Result<Json<CreationChallengeResponse>> {
let authenticator_criteria = AuthenticatorSelectionCriteria {
authenticator_attachment: None,
resident_key: if *residential {
Some(ResidentKeyRequirement::Required)
} else {
Some(ResidentKeyRequirement::Discouraged)
},
require_resident_key: *residential,
user_verification: UserVerificationPolicy::Required,
};
let exclude = PassKey::find_credentials(session.user.id, &db)
.await?
.iter()
.map(|cred| cred.cred_id().clone())
.collect();
match webauthn_store.webauthn.start_passkey_registration(
Uuid::from_u128(session.user.id as u128),
&session.user.username,
&session.user.username,
Some(exclude),
) {
Ok((mut ccr, reg_state)) => {
webauthn_store
.add_registration(session.user.id, reg_state)
.await;
ccr.public_key.authenticator_selection =
Some(authenticator_criteria);
Ok(Json(ccr))
},
Err(e) => Err(e.into()),
}
}
#[derive(Deserialize)]
pub struct PassKeyRegistration {
credential: RegisterPublicKeyCredential,
name: String,
}
#[post("/webauthn/finish_register", format = "json", data = "<reg>")]
pub async fn finish_register<'r>(
// from body
reg: Json<PassKeyRegistration>,
// from headers
session: UserSession,
// injected
webauthn_store: &State<WebAuthnStore>,
db: DbConn,
) -> Result<Either<Redirect, impl Responder<'r, 'static> + use<'r>>> {
let reg_state =
match webauthn_store.fetch_registration(session.user.id).await {
Some(registration) => registration,
None => {
return Err(ZauthError::WebauthnError(
WebauthnError::ChallengeNotFound,
));
},
};
match webauthn_store
.webauthn
.finish_passkey_registration(®.credential, ®_state)
{
Ok(pk) => {
let passkey = NewPassKey {
user_id: session.user.id,
name: reg.name.clone(),
cred: pk,
};
PassKey::create(passkey, &db).await?;
Ok(Either::Left(Redirect::to(uri!(list_passkeys))))
},
Err(e) => Ok(Either::Right(RawHtml(
template!("passkeys/new_passkey.html", {
current_user: User = session.user,
errors: Option<String> = Some(e.to_string()),
}),
))),
}
}
#[post("/webauthn/start_auth", format = "json", data = "<username>")]
pub async fn start_authentication(
// from body
username: Json<Option<String>>,
// injected
webauthn_store: &State<WebAuthnStore>,
db: DbConn,
) -> Result<Json<(DateTime<Local>, RequestChallengeResponse)>> {
let now = Local::now();
let user_opt = if let Some(name) = username.into_inner() {
User::find_by_username(name, &db).await.ok()
} else {
None
};
match user_opt {
Some(user) => {
let creds: Vec<Passkey> =
PassKey::find_credentials(user.id, &db).await?;
match webauthn_store
.webauthn
.start_passkey_authentication(creds.as_slice())
{
Ok((rcr, auth_state)) => {
webauthn_store
.add_authentication(
now,
Either::Right((auth_state, user.id)),
)
.await;
Ok(Json((now, rcr)))
},
Err(e) => Err(e.into()),
}
},
None => {
match webauthn_store.webauthn.start_discoverable_authentication() {
Ok((rcr, auth_state)) => {
webauthn_store
.add_authentication(now, Either::Left(auth_state))
.await;
Ok(Json((now, rcr)))
},
Err(e) => Err(e.into()),
}
},
}
}
#[derive(Deserialize, FromForm)]
pub struct PassKeyAuthentication {
id: String,
credential: Option<String>,
}
async fn authenticate(
webauthn_store: &WebAuthnStore,
id: DateTime<Local>,
credential: Option<PublicKeyCredential>,
db: &DbConn,
) -> Result<User> {
let (result, user) = match webauthn_store.fetch_authentication(id).await {
Some(Either::Left(discoverable_state)) => {
let credential = credential.ok_or(ZauthError::LoginError(
LoginError::PasskeyDiscoverableError,
))?;
let (uuid, _) = webauthn_store
.webauthn
.identify_discoverable_authentication(&credential)?;
let user = User::find(uuid.as_u128() as i32, db).await?;
let creds: Vec<DiscoverableKey> =
PassKey::find_credentials(user.id, db)
.await?
.iter()
.map(DiscoverableKey::from)
.collect();
webauthn_store
.webauthn
.finish_discoverable_authentication(
&credential,
discoverable_state,
creds.as_slice(),
)
.map_err(|_| {
ZauthError::LoginError(LoginError::PasskeyDiscoverableError)
})
.map(|result| (result, user))
},
Some(Either::Right((state, userid))) => {
let credential = credential
.ok_or(ZauthError::LoginError(LoginError::PasskeyError))?;
let user = User::find(userid, db).await?;
webauthn_store
.webauthn
.finish_passkey_authentication(&credential, &state)
.map_err(|_| ZauthError::LoginError(LoginError::PasskeyError))
.map(|result| (result, user))
},
None => Err(ZauthError::LoginError(LoginError::PasskeyError)),
}?;
let mut passkey = PassKey::find_by_cred_id(result.cred_id(), db).await?;
passkey.set_last_used();
// Update the stored counter
let mut credential = passkey.credential()?;
if result.needs_update()
&& credential.update_credential(&result).is_some_and(|b| b)
{
passkey.set_credential(credential)?;
}
passkey.update(db).await?;
Ok(user)
}
#[post("/webauthn/finish_auth", data = "<auth>")]
pub async fn finish_authentication<'r>(
// from body
auth: Form<PassKeyAuthentication>,
// from headers
cookies: &'r CookieJar<'_>,
// injected
config: &'r State<Config>,
webauthn_store: &State<WebAuthnStore>,
db: DbConn,
) -> Result<Either<Redirect, impl Responder<'r, 'static> + use<'r>>> {
let id = serde_json::from_str(&auth.id)
.map_err(|e| ZauthError::Unprocessable(e.to_string()))?;
let credential = auth
.credential
.as_ref()
.and_then(|cred| serde_json::from_str(cred).ok());
match authenticate(webauthn_store, id, credential, &db).await {
Ok(user) => {
let session =
Session::create(&user, config.user_session_duration(), &db)
.await?;
SessionCookie::new(session).login(cookies);
user.update_last_login(&db).await?;
Ok(Either::Left(stored_redirect_or(cookies, uri!(home_page))))
},
Err(ZauthError::LoginError(login_error)) => {
Ok(Either::Right(RawHtml(template!("session/login.html", {
error: Option<String> = Some(login_error.to_string()),
}))))
},
Err(e) => Err(e),
}
}
#[get("/passkeys")]
pub async fn list_passkeys<'r>(
// from headers
session: UserSession,
// injected
db: DbConn,
) -> Result<impl Responder<'r, 'static>> {
let passkeys = PassKey::find_by_user_id(session.user.id, &db).await?;
Ok(Accepter {
html: RawHtml(template!("passkeys/index.html", {
passkeys: Vec<PassKey> = passkeys.clone(),
current_user: User = session.user,
})),
json: Json(passkeys),
})
}
#[get("/passkeys/new")]
pub async fn new_passkey<'r>(
// from headers
session: UserSession,
) -> Result<impl Responder<'r, 'static>> {
Ok(RawHtml(template!("passkeys/new_passkey.html", {
current_user: User = session.user,
errors: Option<String> = None,
})))
}
#[delete("/passkeys/<id>")]
pub async fn delete_passkey<'r>(
// from url
id: i32,
// from headers
session: UserSession,
// injected
db: DbConn,
) -> Result<impl Responder<'r, 'static>> {
let passkey = PassKey::find(id, &db).await?;
if session.user.id == passkey.user_id {
passkey.delete(&db).await?;
Ok(Accepter {
html: Redirect::to(uri!(list_passkeys)),
json: Custom(Status::NoContent, ()),
})
} else {
Err(ZauthError::AuthError(AuthenticationError::Unauthorized(
String::from("passkey is owned by another user"),
)))
}
}