1use crate::{
2 credential::Credential,
3 event::SearchEvent,
4 idm::{
5 account::Account,
6 event::GeneratePasswordEvent,
7 server::{IdmServerProxyReadTransaction, IdmServerProxyWriteTransaction},
8 },
9 prelude::*,
10 utils::password_from_random,
11 value::ApiToken,
12};
13use compact_jwt::{jws::JwsBuilder, Jws, JwsCompact};
14use kanidm_proto::internal::ApiToken as ProtoApiToken;
15use std::{collections::BTreeMap, time::Duration};
16use time::OffsetDateTime;
17
18macro_rules! try_from_entry {
19 ($value:expr) => {{
20 if !$value.attribute_equality(Attribute::Class, &EntryClass::ServiceAccount.into()) {
22 return Err(OperationError::MissingClass(
23 ENTRYCLASS_SERVICE_ACCOUNT.into(),
24 ));
25 }
26
27 let api_tokens = $value
28 .get_ava_as_apitoken_map(Attribute::ApiTokenSession)
29 .cloned()
30 .unwrap_or_default();
31
32 let valid_from = $value.get_ava_single_datetime(Attribute::AccountValidFrom);
33
34 let expire = $value.get_ava_single_datetime(Attribute::AccountExpire);
35
36 let uuid = $value.get_uuid().clone();
37
38 Ok(ServiceAccount {
39 uuid,
40 valid_from,
41 expire,
42 api_tokens,
43 })
44 }};
45}
46
47pub struct ServiceAccount {
48 pub uuid: Uuid,
49
50 pub valid_from: Option<OffsetDateTime>,
51 pub expire: Option<OffsetDateTime>,
52
53 pub api_tokens: BTreeMap<Uuid, ApiToken>,
54}
55
56impl ServiceAccount {
57 #[instrument(level = "debug", skip_all)]
58 pub(crate) fn try_from_entry_rw(
59 value: &Entry<EntrySealed, EntryCommitted>,
60 ) -> Result<Self, OperationError> {
62 try_from_entry!(value)
64 }
65
66 pub(crate) fn check_api_token_valid(
67 ct: Duration,
68 apit: &ProtoApiToken,
69 entry: &Entry<EntrySealed, EntryCommitted>,
70 ) -> bool {
71 let within_valid_window = Account::check_within_valid_time(
72 ct,
73 entry
74 .get_ava_single_datetime(Attribute::AccountValidFrom)
75 .as_ref(),
76 entry
77 .get_ava_single_datetime(Attribute::AccountExpire)
78 .as_ref(),
79 );
80
81 if !within_valid_window {
82 security_info!("Account has expired or is not yet valid, not allowing to proceed");
83 return false;
84 }
85
86 let session_present = entry
88 .get_ava_as_apitoken_map(Attribute::ApiTokenSession)
89 .map(|session_map| session_map.get(&apit.token_id).is_some())
90 .unwrap_or(false);
91
92 if session_present {
93 security_info!("A valid session value exists for this token");
94 true
95 } else {
96 let grace = apit.issued_at + AUTH_TOKEN_GRACE_WINDOW;
97 let current = time::OffsetDateTime::UNIX_EPOCH + ct;
98 trace!(%grace, %current);
99 if current >= grace {
100 security_info!(
101 "The token grace window has passed, and no session exists. Assuming invalid."
102 );
103 false
104 } else {
105 security_info!("The token grace window is in effect. Assuming valid.");
106 true
107 }
108 }
109 }
110}
111
112pub struct ListApiTokenEvent {
113 pub ident: Identity,
115 pub target: Uuid,
117}
118
119pub struct GenerateApiTokenEvent {
120 pub ident: Identity,
122 pub target: Uuid,
124 pub label: String,
126 pub expiry: Option<time::OffsetDateTime>,
128 pub read_write: bool,
130 pub compact: bool,
134}
135
136impl GenerateApiTokenEvent {
137 #[cfg(test)]
138 pub fn new_internal(target: Uuid, label: &str, expiry: Option<Duration>) -> Self {
139 GenerateApiTokenEvent {
140 ident: Identity::from_internal(),
141 target,
142 label: label.to_string(),
143 expiry: expiry.map(|ct| time::OffsetDateTime::UNIX_EPOCH + ct),
144 read_write: false,
145 compact: false,
146 }
147 }
148}
149
150pub struct DestroyApiTokenEvent {
151 pub ident: Identity,
153 pub target: Uuid,
155 pub token_id: Uuid,
157}
158
159impl DestroyApiTokenEvent {
160 #[cfg(test)]
161 pub fn new_internal(target: Uuid, token_id: Uuid) -> Self {
162 DestroyApiTokenEvent {
163 ident: Identity::from_internal(),
164 target,
165 token_id,
166 }
167 }
168}
169
170impl IdmServerProxyWriteTransaction<'_> {
171 pub fn service_account_generate_api_token(
172 &mut self,
173 gte: &GenerateApiTokenEvent,
174 ct: Duration,
175 ) -> Result<JwsCompact, OperationError> {
176 let service_account = self
177 .qs_write
178 .internal_search_uuid(gte.target)
179 .and_then(|account_entry| ServiceAccount::try_from_entry_rw(&account_entry))
180 .map_err(|e| {
181 admin_error!(?e, "Failed to search service account");
182 e
183 })?;
184
185 let session_id = Uuid::new_v4();
186 let issued_at = time::OffsetDateTime::UNIX_EPOCH + ct;
187
188 let expiry = gte.expiry.map(|odt| odt.to_offset(time::UtcOffset::UTC));
190
191 let scope = if gte.read_write {
192 ApiTokenScope::ReadWrite
193 } else {
194 ApiTokenScope::ReadOnly
195 };
196
197 let session = Value::ApiToken(
199 session_id,
200 ApiToken {
201 label: gte.label.clone(),
202 expiry,
203 issued_at,
206 issued_by: gte.ident.get_event_origin_id(),
208 scope,
211 },
212 );
213
214 let token = if gte.compact {
215 let payload = session_id.as_bytes().to_vec();
218 JwsBuilder::from(payload).build()
219 } else {
220 let purpose = scope.try_into()?;
221 let proto_api_token = ProtoApiToken {
223 account_id: service_account.uuid,
224 token_id: session_id,
225 label: gte.label.clone(),
226 expiry: gte.expiry,
227 issued_at,
228 purpose,
229 };
230
231 let token = Jws::into_json(&proto_api_token).map_err(|err| {
232 error!(?err, "Unable to serialise JWS");
233 OperationError::SerdeJsonError
234 })?;
235
236 token
237 };
238
239 let modlist =
241 ModifyList::new_list(vec![Modify::Present(Attribute::ApiTokenSession, session)]);
242
243 self.qs_write
244 .impersonate_modify(
245 &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(gte.target))),
247 &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(gte.target))),
249 &modlist,
250 >e.ident,
252 )
253 .map_err(|err| {
254 error!(?err, "Failed to generate api token");
255 err
256 })?;
257
258 self.qs_write
259 .get_domain_key_object_handle()?
260 .jws_hs256_sign(&token, ct)
261 }
262
263 pub fn service_account_destroy_api_token(
264 &mut self,
265 dte: &DestroyApiTokenEvent,
266 ) -> Result<(), OperationError> {
267 let modlist = ModifyList::new_list(vec![Modify::Removed(
269 Attribute::ApiTokenSession,
270 PartialValue::Refer(dte.token_id),
271 )]);
272
273 self.qs_write
274 .impersonate_modify(
275 &filter!(f_and!([
277 f_eq(Attribute::Uuid, PartialValue::Uuid(dte.target)),
278 f_eq(
279 Attribute::ApiTokenSession,
280 PartialValue::Refer(dte.token_id)
281 )
282 ])),
283 &filter_all!(f_and!([
285 f_eq(Attribute::Uuid, PartialValue::Uuid(dte.target)),
286 f_eq(
287 Attribute::ApiTokenSession,
288 PartialValue::Refer(dte.token_id)
289 )
290 ])),
291 &modlist,
292 &dte.ident,
294 )
295 .map_err(|e| {
296 admin_error!("Failed to destroy api token {:?}", e);
297 e
298 })
299 }
300
301 pub fn generate_service_account_password(
302 &mut self,
303 gpe: &GeneratePasswordEvent,
304 ) -> Result<String, OperationError> {
305 let cleartext = password_from_random();
308 let timestamp = self.qs_write.get_curtime_odt();
309 let ncred =
310 Credential::new_generatedpassword_only(self.crypto_policy(), &cleartext, timestamp)
311 .map_err(|e| {
312 admin_error!("Unable to generate password mod {:?}", e);
313 e
314 })?;
315 let vcred = Value::new_credential("primary", ncred);
316 let modlist = ModifyList::new_list(vec![
318 m_purge(Attribute::PassKeys),
319 m_purge(Attribute::PrimaryCredential),
320 Modify::Present(Attribute::PrimaryCredential, vcred),
321 ]);
322
323 trace!(?modlist, "processing change");
324 self.qs_write
327 .impersonate_modify(
328 &filter_all!(f_and!([
330 f_eq(Attribute::Uuid, PartialValue::Uuid(gpe.target)),
331 f_eq(Attribute::Class, EntryClass::ServiceAccount.into())
332 ])),
333 &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(gpe.target))),
335 &modlist,
336 &gpe.ident,
338 )
339 .map(|_| cleartext)
340 .map_err(|e| {
341 admin_error!("Failed to generate account password {:?}", e);
342 e
343 })
344 }
345}
346
347impl IdmServerProxyReadTransaction<'_> {
348 pub fn service_account_list_api_token(
349 &mut self,
350 lte: &ListApiTokenEvent,
351 ) -> Result<Vec<ProtoApiToken>, OperationError> {
352 let srch = match SearchEvent::from_target_uuid_request(
354 lte.ident.clone(),
355 lte.target,
356 &self.qs_read,
357 ) {
358 Ok(s) => s,
359 Err(e) => {
360 admin_error!("Failed to begin service account api token list: {:?}", e);
361 return Err(e);
362 }
363 };
364
365 match self.qs_read.search_ext(&srch) {
366 Ok(mut entries) => {
367 entries
368 .pop()
369 .and_then(|e| {
371 let account_id = e.get_uuid();
372 e.get_ava_as_apitoken_map(Attribute::ApiTokenSession)
374 .map(|smap| {
375 smap.iter()
376 .map(|(u, s)| {
377 s.scope
378 .try_into()
379 .map(|purpose| ProtoApiToken {
380 account_id,
381 token_id: *u,
382 label: s.label.clone(),
383 expiry: s.expiry,
384 issued_at: s.issued_at,
385 purpose,
386 })
387 .inspect_err(|err| {
388 admin_error!(?err, "Invalid api_token {}", u);
389 })
390 })
391 .collect::<Result<Vec<_>, _>>()
392 })
393 })
394 .unwrap_or_else(|| {
395 Ok(Vec::with_capacity(0))
397 })
398 }
399 Err(e) => Err(e),
400 }
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use std::time::Duration;
407
408 use compact_jwt::{dangernoverify::JwsDangerReleaseWithoutVerify, JwsVerifier};
409 use kanidm_proto::internal::ApiToken;
410
411 use super::{DestroyApiTokenEvent, GenerateApiTokenEvent};
412 use crate::{idm::server::IdmServerTransaction, prelude::*};
413
414 const TEST_CURRENT_TIME: u64 = 6000;
415
416 #[idm_test]
417 async fn test_idm_service_account_api_token(
418 idms: &IdmServer,
419 _idms_delayed: &mut IdmServerDelayed,
420 ) {
421 let ct = Duration::from_secs(TEST_CURRENT_TIME);
422 let past_grc = Duration::from_secs(TEST_CURRENT_TIME + 1) + AUTH_TOKEN_GRACE_WINDOW;
423 let exp = Duration::from_secs(TEST_CURRENT_TIME + 6000);
424 let post_exp = Duration::from_secs(TEST_CURRENT_TIME + 6010);
425 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
426
427 let testaccount_uuid = Uuid::new_v4();
428
429 let e1 = entry_init!(
430 (Attribute::Class, EntryClass::Object.to_value()),
431 (Attribute::Class, EntryClass::Account.to_value()),
432 (Attribute::Class, EntryClass::ServiceAccount.to_value()),
433 (Attribute::Name, Value::new_iname("test_account_only")),
434 (Attribute::Uuid, Value::Uuid(testaccount_uuid)),
435 (Attribute::Description, Value::new_utf8s("testaccount")),
436 (Attribute::DisplayName, Value::new_utf8s("testaccount"))
437 );
438
439 idms_prox_write
440 .qs_write
441 .internal_create(vec![e1])
442 .expect("Failed to create service account");
443
444 let gte = GenerateApiTokenEvent::new_internal(testaccount_uuid, "TestToken", Some(exp));
445
446 let api_token = idms_prox_write
447 .service_account_generate_api_token(>e, ct)
448 .expect("failed to generate new api token");
449
450 trace!(?api_token);
451
452 let jws_verifier = JwsDangerReleaseWithoutVerify::default();
454
455 let apitoken_inner = jws_verifier
456 .verify(&api_token)
457 .unwrap()
458 .from_json::<ApiToken>()
459 .unwrap();
460
461 let ident = idms_prox_write
462 .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
463 .expect("Unable to verify api token.");
464
465 assert_eq!(ident.get_uuid(), testaccount_uuid);
466
467 assert!(
471 idms_prox_write
472 .validate_client_auth_info_to_ident(api_token.clone().into(), post_exp)
473 .expect_err("Should not succeed")
474 == OperationError::SessionExpired
475 );
476
477 let dte =
479 DestroyApiTokenEvent::new_internal(apitoken_inner.account_id, apitoken_inner.token_id);
480 assert!(idms_prox_write
481 .service_account_destroy_api_token(&dte)
482 .is_ok());
483
484 let ident = idms_prox_write
487 .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
488 .expect("Unable to verify api token.");
489 assert_eq!(ident.get_uuid(), testaccount_uuid);
490
491 assert!(
493 idms_prox_write
494 .validate_client_auth_info_to_ident(api_token.into(), past_grc)
495 .expect_err("Should not succeed")
496 == OperationError::SessionExpired
497 );
498
499 assert!(idms_prox_write.commit().is_ok());
500 }
501
502 #[idm_test]
503 async fn test_idm_service_account_compact_api_token(
504 idms: &IdmServer,
505 _idms_delayed: &mut IdmServerDelayed,
506 ) {
507 let ct = Duration::from_secs(TEST_CURRENT_TIME);
508 let exp = Duration::from_secs(TEST_CURRENT_TIME + 6000);
509 let post_exp = Duration::from_secs(TEST_CURRENT_TIME + 6010);
510 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
511
512 let testaccount_uuid = Uuid::new_v4();
513
514 let e1 = entry_init!(
515 (Attribute::Class, EntryClass::Object.to_value()),
516 (Attribute::Class, EntryClass::Account.to_value()),
517 (Attribute::Class, EntryClass::ServiceAccount.to_value()),
518 (Attribute::Name, Value::new_iname("test_account_only")),
519 (Attribute::Uuid, Value::Uuid(testaccount_uuid)),
520 (Attribute::Description, Value::new_utf8s("testaccount")),
521 (Attribute::DisplayName, Value::new_utf8s("testaccount"))
522 );
523
524 idms_prox_write
525 .qs_write
526 .internal_create(vec![e1])
527 .expect("Failed to create service account");
528
529 let mut gte = GenerateApiTokenEvent::new_internal(testaccount_uuid, "TestToken", Some(exp));
530
531 gte.compact = true;
533
534 let api_token = idms_prox_write
535 .service_account_generate_api_token(>e, ct)
536 .expect("failed to generate new api token");
537
538 trace!(?api_token);
539
540 let jws_verifier = JwsDangerReleaseWithoutVerify::default();
542
543 let apitoken_inner = jws_verifier.verify(&api_token).unwrap();
544
545 let session_id = Uuid::from_slice(apitoken_inner.payload())
546 .expect("Unable to decode compact token as session id");
547
548 let ident = idms_prox_write
549 .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
550 .expect("Unable to verify api token.");
551
552 assert_eq!(ident.get_uuid(), testaccount_uuid);
553
554 assert!(
558 idms_prox_write
559 .validate_client_auth_info_to_ident(api_token.clone().into(), post_exp)
560 .expect_err("Should not succeed")
561 == OperationError::SessionExpired
562 );
563
564 let dte = DestroyApiTokenEvent::new_internal(testaccount_uuid, session_id);
566 assert!(idms_prox_write
567 .service_account_destroy_api_token(&dte)
568 .is_ok());
569
570 assert!(idms_prox_write.commit().is_ok());
573 }
574}