Debian Codegraph @

src/system/timestamp.rs

raw symbols SCIP
1 use std::{
2 fs::File,
3 io::{self, Cursor, Read, Seek, Write},
4 path::PathBuf,
5 time::Duration,
6 };
7
8 use crate::common::resolve::AuthUser;
9 use crate::{
10 common::resolve::CurrentUser,
11 log::{auth_info, auth_warn},
12 };
13
14 use super::{
15 Process, WithProcess,
16 audit::secure_open_cookie_file,
17 file::FileLock,
18 interface::{DeviceId, ProcessId, UserId},
19 time::{ProcessCreateTime, SystemTime},
20 };
21
22 type BoolStorage = u8;
23
24 const SIZE_OF_TS: i64 = std::mem::size_of::<SystemTime>() as i64;
25 const SIZE_OF_BOOL: i64 = std::mem::size_of::<BoolStorage>() as i64;
26 const MOD_OFFSET: i64 = SIZE_OF_TS + SIZE_OF_BOOL;
27
28 #[derive(Debug)]
29 pub struct SessionRecordFile {
30 file: File,
31 timeout: Duration,
32 for_user: UserId,
33 }
34
35 impl SessionRecordFile {
36 const BASE_PATH: &'static str = "/var/run/sudo-rs/ts";
37
38 pub fn open_for_user(user: &CurrentUser, timeout: Duration) -> io::Result<Self> {
39 let uid = user.uid;
40 let mut path = PathBuf::from(Self::BASE_PATH);
41 path.push(uid.to_string());
42 SessionRecordFile::new(uid, secure_open_cookie_file(&path)?, timeout)
43 }
44
45 const FILE_VERSION: u16 = 2;
46 const MAGIC_NUM: u16 = 0x50D0;
47 const VERSION_OFFSET: u64 = Self::MAGIC_NUM.to_le_bytes().len() as u64;
48 const FIRST_RECORD_OFFSET: u64 =
49 Self::VERSION_OFFSET + Self::FILE_VERSION.to_le_bytes().len() as u64;
50
51 /// Create a new SessionRecordFile from the given i/o stream.
52 /// Timestamps in this file are considered valid if they were created or
53 /// updated at most `timeout` time ago.
54 pub fn new(for_user: UserId, io: File, timeout: Duration) -> io::Result<Self> {
55 let mut session_records = SessionRecordFile {
56 file: io,
57 timeout,
58 for_user,
59 };
60
61 // match the magic number, otherwise reset the file
62 match session_records.read_magic()? {
63 Some(magic) if magic == Self::MAGIC_NUM => (),
64 x => {
65 if let Some(_magic) = x {
66 auth_info!("Session records file for user '{for_user}' is invalid, resetting");
67 }
68
69 session_records.init(Self::VERSION_OFFSET)?;
70 }
71 }
72
73 // match the file version
74 match session_records.read_version()? {
75 Some(v) if v == Self::FILE_VERSION => (),
76 x => {
77 if let Some(v) = x {
78 auth_info!(
79 "Session records file for user '{for_user}' has invalid version {v}, only file version {} is supported, resetting",
80 Self::FILE_VERSION
81 );
82 } else {
83 auth_info!(
84 "Session records file did not contain file version information, resetting"
85 );
86 }
87
88 session_records.init(Self::FIRST_RECORD_OFFSET)?;
89 }
90 }
91
92 // we are ready to read records
93 Ok(session_records)
94 }
95
96 /// Read the magic number from the input stream
97 fn read_magic(&mut self) -> io::Result<Option<u16>> {
98 let mut magic_bytes = [0; std::mem::size_of::<u16>()];
99 match self.file.read_exact(&mut magic_bytes) {
100 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None),
101 Err(e) => Err(e),
102 Ok(()) => Ok(Some(u16::from_le_bytes(magic_bytes))),
103 }
104 }
105
106 /// Read the version number from the input stream
107 fn read_version(&mut self) -> io::Result<Option<u16>> {
108 let mut version_bytes = [0; std::mem::size_of::<u16>()];
109 match self.file.read_exact(&mut version_bytes) {
110 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None),
111 Err(e) => Err(e),
112 Ok(()) => Ok(Some(u16::from_le_bytes(version_bytes))),
113 }
114 }
115
116 /// Initialize a new empty stream. If the stream/file was already filled
117 /// before it will be truncated.
118 fn init(&mut self, offset: u64) -> io::Result<()> {
119 // lock the file to indicate that we are currently writing to it
120 let lock = FileLock::exclusive(&self.file, false)?;
121
122 self.file.set_len(0)?;
123 self.file.rewind()?;
124 self.file.write_all(&Self::MAGIC_NUM.to_le_bytes())?;
125 self.file.write_all(&Self::FILE_VERSION.to_le_bytes())?;
126 self.file.seek(io::SeekFrom::Start(offset))?;
127
128 lock.unlock()?;
129
130 Ok(())
131 }
132
133 /// Read the next record and keep note of the start and end positions in the file of that record
134 ///
135 /// This method assumes that the file is already exclusively locked.
136 fn next_record(&mut self) -> io::Result<Option<SessionRecord>> {
137 // record the position at which this record starts (including size bytes)
138 let mut record_length_bytes = [0; std::mem::size_of::<u16>()];
139
140 let curr_pos = self.file.stream_position()?;
141
142 // if eof occurs here we assume we reached the end of the file
143 let record_length = match self.file.read_exact(&mut record_length_bytes) {
144 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
145 Err(e) => return Err(e),
146 Ok(()) => u16::from_le_bytes(record_length_bytes),
147 };
148
149 // special case when record_length is zero
150 if record_length == 0 {
151 return Err(io::Error::new(
152 io::ErrorKind::InvalidInput,
153 "Found empty record",
154 ));
155 }
156
157 let mut buf = vec![0; record_length as usize];
158 match self.file.read_exact(&mut buf) {
159 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
160 // there was half a record here, we clear the rest of the file
161 auth_info!(
162 "Found incomplete record in session records file for {}, clearing rest of the file",
163 self.for_user
164 );
165 self.file.set_len(curr_pos)?;
166 return Ok(None);
167 }
168 Err(e) => return Err(e),
169 Ok(()) => (),
170 }
171
172 // we now try and decode the data read into a session record
173 match SessionRecord::from_bytes(&buf) {
174 Err(_) => {
175 // any error assumes that this file is nonsense from this point
176 // onwards, so we clear the file up to the start of this record
177 auth_info!(
178 "Found invalid record in session records file for {}, clearing rest of the file",
179 self.for_user
180 );
181
182 self.file.set_len(curr_pos)?;
183 Ok(None)
184 }
185 Ok(record) => Ok(Some(record)),
186 }
187 }
188
189 /// Try and find a record for the given scope and auth user id and update
190 /// that record time to the current time. This will not create a new record
191 /// when one is not found. A record will only be updated if it is still
192 /// valid at this time.
193 pub fn touch(&mut self, scope: RecordScope, auth_user: &AuthUser) -> io::Result<TouchResult> {
194 // lock the file to indicate that we are currently in a writing operation
195 let lock = FileLock::exclusive(&self.file, false)?;
196 self.seek_to_first_record()?;
197 while let Some(record) = self.next_record()? {
198 // only touch if record is enabled
199 if record.enabled && record.matches(&scope, auth_user) {
200 let now = SystemTime::now()?;
201 if record.written_between(now - self.timeout, now) {
202 // move back to where the timestamp is and overwrite with the latest time
203 self.file.seek(io::SeekFrom::Current(-MOD_OFFSET))?;
204 let new_time = SystemTime::now()?;
205 new_time.encode(&mut self.file)?;
206
207 // make sure we can still go to the end of the record
208 self.file.seek(io::SeekFrom::Current(SIZE_OF_BOOL))?;
209
210 // writing is done, unlock and return
211 lock.unlock()?;
212 return Ok(TouchResult::Updated {
213 old_time: record.timestamp,
214 new_time,
215 });
216 } else {
217 lock.unlock()?;
218 return Ok(TouchResult::Outdated {
219 time: record.timestamp,
220 });
221 }
222 }
223 }
224
225 lock.unlock()?;
226 Ok(TouchResult::NotFound)
227 }
228
229 /// Disable all records that match the given scope.
230 pub fn disable(&mut self, scope: RecordScope) -> io::Result<()> {
231 let lock = FileLock::exclusive(&self.file, false)?;
232 self.seek_to_first_record()?;
233 while let Some(record) = self.next_record()? {
234 if record.scope == scope {
235 self.file.seek(io::SeekFrom::Current(-SIZE_OF_BOOL))?;
236 write_bool(false, &mut self.file)?;
237 }
238 }
239 lock.unlock()?;
240 Ok(())
241 }
242
243 /// Create a new record for the given scope and auth user id.
244 /// If there is an existing record that matches the scope and auth user,
245 /// then that record will be updated.
246 pub fn create(&mut self, scope: RecordScope, auth_user: &AuthUser) -> io::Result<CreateResult> {
247 // lock the file to indicate that we are currently writing to it
248 let lock = FileLock::exclusive(&self.file, false)?;
249 self.seek_to_first_record()?;
250 while let Some(record) = self.next_record()? {
251 if record.matches(&scope, auth_user) {
252 self.file.seek(io::SeekFrom::Current(-MOD_OFFSET))?;
253 let new_time = SystemTime::now()?;
254 new_time.encode(&mut self.file)?;
255 write_bool(true, &mut self.file)?;
256 lock.unlock()?;
257 return Ok(CreateResult::Updated {
258 old_time: record.timestamp,
259 new_time,
260 });
261 }
262 }
263
264 // record was not found in the list so far, create a new one
265 let record = SessionRecord::new(scope, auth_user.uid)?;
266
267 // make sure we really are at the end of the file
268 self.file.seek(io::SeekFrom::End(0))?;
269
270 self.write_record(&record)?;
271 lock.unlock()?;
272
273 Ok(CreateResult::Created {
274 time: record.timestamp,
275 })
276 }
277
278 /// Completely resets the entire file and removes all records.
279 pub fn reset(&mut self) -> io::Result<()> {
280 self.init(0)
281 }
282
283 /// Write a new record at the current position in the file.
284 fn write_record(&mut self, record: &SessionRecord) -> io::Result<()> {
285 // convert the new record to byte representation and make sure that it fits
286 let bytes = record.as_bytes()?;
287 let record_length = bytes.len();
288 if record_length > u16::MAX as usize {
289 return Err(io::Error::new(
290 io::ErrorKind::InvalidInput,
291 "A record with an unexpectedly large size was created",
292 ));
293 }
294 let record_length = record_length as u16; // store as u16
295
296 // write the record
297 self.file.write_all(&record_length.to_le_bytes())?;
298 self.file.write_all(&bytes)?;
299
300 Ok(())
301 }
302
303 /// Move to where the first record starts.
304 fn seek_to_first_record(&mut self) -> io::Result<()> {
305 self.file
306 .seek(io::SeekFrom::Start(Self::FIRST_RECORD_OFFSET))?;
307 Ok(())
308 }
309 }
310
311 #[derive(Debug, PartialEq, Eq, Clone)]
312 pub enum TouchResult {
313 /// The record was found and within the timeout, and it was refreshed
314 Updated {
315 old_time: SystemTime,
316 new_time: SystemTime,
317 },
318 /// A record was found, but it was no longer valid
319 Outdated { time: SystemTime },
320 /// A record was not found that matches the input
321 NotFound,
322 }
323
324 #[cfg_attr(not(test), allow(dead_code))]
325 pub enum CreateResult {
326 /// The record was found and it was refreshed
327 Updated {
328 old_time: SystemTime,
329 new_time: SystemTime,
330 },
331 /// A new record was created and was set to the time returned
332 Created { time: SystemTime },
333 }
334
335 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
336 pub enum RecordScope {
337 Tty {
338 tty_device: DeviceId,
339 session_pid: ProcessId,
340 init_time: ProcessCreateTime,
341 },
342 Ppid {
343 group_pid: ProcessId,
344 session_pid: ProcessId,
345 init_time: ProcessCreateTime,
346 },
347 }
348
349 impl RecordScope {
350 fn encode(&self, target: &mut impl Write) -> std::io::Result<()> {
351 match self {
352 RecordScope::Tty {
353 tty_device,
354 session_pid,
355 init_time,
356 } => {
357 target.write_all(&[1u8])?;
358 let b = tty_device.inner().to_le_bytes();
359 target.write_all(&b)?;
360 let b = session_pid.inner().to_le_bytes();
361 target.write_all(&b)?;
362 init_time.encode(target)?;
363 }
364 RecordScope::Ppid {
365 group_pid,
366 session_pid,
367 init_time,
368 } => {
369 target.write_all(&[2u8])?;
370 let b = group_pid.inner().to_le_bytes();
371 target.write_all(&b)?;
372 let b = session_pid.inner().to_le_bytes();
373 target.write_all(&b)?;
374 init_time.encode(target)?;
375 }
376 }
377
378 Ok(())
379 }
380
381 fn decode(from: &mut impl Read) -> std::io::Result<RecordScope> {
382 let mut buf = [0; 1];
383 from.read_exact(&mut buf)?;
384 match buf[0] {
385 1 => {
386 let mut buf = [0; std::mem::size_of::<libc::dev_t>()];
387 from.read_exact(&mut buf)?;
388 let tty_device = libc::dev_t::from_le_bytes(buf);
389 let mut buf = [0; std::mem::size_of::<libc::pid_t>()];
390 from.read_exact(&mut buf)?;
391 let session_pid = libc::pid_t::from_le_bytes(buf);
392 let init_time = ProcessCreateTime::decode(from)?;
393 Ok(RecordScope::Tty {
394 tty_device: DeviceId::new(tty_device),
395 session_pid: ProcessId::new(session_pid),
396 init_time,
397 })
398 }
399 2 => {
400 let mut buf = [0; std::mem::size_of::<libc::pid_t>()];
401 from.read_exact(&mut buf)?;
402 let group_pid = libc::pid_t::from_le_bytes(buf);
403 let mut buf = [0; std::mem::size_of::<libc::pid_t>()];
404 from.read_exact(&mut buf)?;
405 let session_pid = libc::pid_t::from_le_bytes(buf);
406 let init_time = ProcessCreateTime::decode(from)?;
407 Ok(RecordScope::Ppid {
408 group_pid: ProcessId::new(group_pid),
409 session_pid: ProcessId::new(session_pid),
410 init_time,
411 })
412 }
413 x => Err(io::Error::new(
414 io::ErrorKind::InvalidInput,
415 format!("Unexpected scope variant discriminator: {x}"),
416 )),
417 }
418 }
419
420 /// Tries to determine a record match scope for the current context.
421 /// This should never produce an error since any actual error should just be
422 /// ignored and no session record file should be used in that case.
423 pub fn for_process(process: &Process) -> Option<RecordScope> {
424 let tty = Process::tty_device_id(WithProcess::Current);
425 if let Ok(Some(tty_device)) = tty {
426 if let Ok(init_time) = Process::starting_time(WithProcess::Other(process.session_id)) {
427 Some(RecordScope::Tty {
428 tty_device,
429 session_pid: process.session_id,
430 init_time,
431 })
432 } else {
433 auth_warn!("Could not get terminal foreground process starting time");
434 None
435 }
436 } else if let Some(parent_pid) = process.parent_pid {
437 if let Ok(init_time) = Process::starting_time(WithProcess::Other(parent_pid)) {
438 Some(RecordScope::Ppid {
439 group_pid: parent_pid,
440 session_pid: process.session_id,
441 init_time,
442 })
443 } else {
444 auth_warn!("Could not get parent process starting time");
445 None
446 }
447 } else {
448 None
449 }
450 }
451 }
452
453 fn write_bool(b: bool, target: &mut impl Write) -> io::Result<()> {
454 let s: BoolStorage = if b { 0xFF } else { 0x00 };
455 let bytes = s.to_le_bytes();
456 target.write_all(&bytes)?;
457 Ok(())
458 }
459
460 /// A record in the session record file
461 #[derive(Debug, PartialEq, Eq)]
462 pub struct SessionRecord {
463 /// The scope for which the current record applies, i.e. what process group
464 /// or which TTY for interactive sessions
465 scope: RecordScope,
466 /// The user that needs to be authenticated against
467 auth_user: UserId,
468 /// The timestamp at which the time was created. This must always be a time
469 /// originating from a monotonic clock that continues counting during system
470 /// sleep.
471 timestamp: SystemTime,
472 /// Disabled records act as if they do not exist, but their storage can
473 /// be re-used when recreating for the same scope and auth user
474 enabled: bool,
475 }
476
477 impl SessionRecord {
478 /// Create a new record that is scoped to the specified scope and has `auth_user` as
479 /// the target for authentication for the session.
480 fn new(scope: RecordScope, auth_user: UserId) -> io::Result<SessionRecord> {
481 Ok(Self::init(scope, auth_user, true, SystemTime::now()?))
482 }
483
484 /// Initialize a new record with the given parameters
485 fn init(
486 scope: RecordScope,
487 auth_user: UserId,
488 enabled: bool,
489 timestamp: SystemTime,
490 ) -> SessionRecord {
491 SessionRecord {
492 scope,
493 auth_user,
494 timestamp,
495 enabled,
496 }
497 }
498
499 /// Encode a record into the given stream
500 fn encode(&self, target: &mut impl Write) -> std::io::Result<()> {
501 self.scope.encode(target)?;
502
503 // write user id
504 let buf = self.auth_user.inner().to_le_bytes();
505 target.write_all(&buf)?;
506
507 // write timestamp
508 self.timestamp.encode(target)?;
509
510 // write enabled boolean
511 write_bool(self.enabled, target)?;
512
513 Ok(())
514 }
515
516 /// Decode a record from the given stream
517 fn decode(from: &mut impl Read) -> std::io::Result<SessionRecord> {
518 let scope = RecordScope::decode(from)?;
519
520 // auth user id
521 let mut buf = [0; std::mem::size_of::<libc::uid_t>()];
522 from.read_exact(&mut buf)?;
523 let auth_user = libc::uid_t::from_le_bytes(buf);
524 let auth_user = UserId::new(auth_user);
525
526 // timestamp
527 let timestamp = SystemTime::decode(from)?;
528
529 // enabled boolean
530 let mut buf = [0; std::mem::size_of::<BoolStorage>()];
531 from.read_exact(&mut buf)?;
532 let enabled = match BoolStorage::from_le_bytes(buf) {
533 0xFF => true,
534 0x00 => false,
535 _ => {
536 return Err(io::Error::new(
537 io::ErrorKind::InvalidData,
538 "Invalid boolean value detected in input stream",
539 ));
540 }
541 };
542
543 Ok(SessionRecord::init(scope, auth_user, enabled, timestamp))
544 }
545
546 /// Convert the record to a vector of bytes for storage.
547 pub fn as_bytes(&self) -> std::io::Result<Vec<u8>> {
548 let mut v = vec![];
549 self.encode(&mut v)?;
550 Ok(v)
551 }
552
553 /// Convert the given byte slice to a session record, the byte slice must
554 /// be fully consumed for this conversion to be valid.
555 pub fn from_bytes(data: &[u8]) -> std::io::Result<SessionRecord> {
556 let mut cursor = Cursor::new(data);
557 let record = SessionRecord::decode(&mut cursor)?;
558 if cursor.position() != data.len() as u64 {
559 Err(io::Error::new(
560 io::ErrorKind::InvalidInput,
561 "Record size and record length did not match",
562 ))
563 } else {
564 Ok(record)
565 }
566 }
567
568 /// Returns true if this record matches the specified scope and is for the
569 /// specified target auth user.
570 pub fn matches(&self, scope: &RecordScope, auth_user: &AuthUser) -> bool {
571 self.scope == *scope && self.auth_user == auth_user.uid
572 }
573
574 /// Returns true if this record was written somewhere in the time range
575 /// between `early_time` (inclusive) and `later_time` (inclusive), where
576 /// early timestamp may not be later than the later timestamp.
577 pub fn written_between(&self, early_time: SystemTime, later_time: SystemTime) -> bool {
578 early_time <= later_time && self.timestamp >= early_time && self.timestamp <= later_time
579 }
580 }
581
582 #[cfg(test)]
583 mod tests {
584 use std::path::Path;
585
586 use super::*;
587 use crate::common::{SudoPath, SudoString};
588 use crate::system::User;
589 use crate::system::interface::GroupId;
590 use crate::system::tests::tempfile;
591
592 static TEST_USER_ID: UserId = UserId::ROOT;
593
594 fn auth_user_from_uid(uid: libc::uid_t) -> AuthUser {
595 AuthUser::from_user_for_targetpw(User {
596 uid: UserId::new(uid),
597 gid: GroupId::new(0),
598 name: SudoString::new("dummy".to_owned()).unwrap(),
599 home: SudoPath::new(Path::new("/nonexistent").to_owned()).unwrap(),
600 shell: Path::new("/bin/sh").to_owned(),
601 groups: vec![],
602 })
603 }
604
605 #[test]
606 fn can_encode_and_decode() {
607 let tty_sample = SessionRecord::new(
608 RecordScope::Tty {
609 tty_device: DeviceId::new(10),
610 session_pid: ProcessId::new(42),
611 init_time: ProcessCreateTime::new(1, 0),
612 },
613 UserId::new(999),
614 )
615 .unwrap();
616
617 let mut bytes = tty_sample.as_bytes().unwrap();
618 let decoded = SessionRecord::from_bytes(&bytes).unwrap();
619 assert_eq!(tty_sample, decoded);
620
621 // we provide some invalid input
622 assert!(SessionRecord::from_bytes(&bytes[1..]).is_err());
623
624 // we have remaining input after decoding
625 bytes.push(0);
626 assert!(SessionRecord::from_bytes(&bytes).is_err());
627
628 let ppid_sample = SessionRecord::new(
629 RecordScope::Ppid {
630 group_pid: ProcessId::new(42),
631 session_pid: ProcessId::new(43),
632 init_time: ProcessCreateTime::new(151, 0),
633 },
634 UserId::new(123),
635 )
636 .unwrap();
637 let bytes = ppid_sample.as_bytes().unwrap();
638 let decoded = SessionRecord::from_bytes(&bytes).unwrap();
639 assert_eq!(ppid_sample, decoded);
640 }
641
642 #[test]
643 fn timestamp_record_matches_works() {
644 let init_time = ProcessCreateTime::new(1, 0);
645 let scope = RecordScope::Tty {
646 tty_device: DeviceId::new(12),
647 session_pid: ProcessId::new(1234),
648 init_time,
649 };
650
651 let tty_sample = SessionRecord::new(scope, UserId::new(675)).unwrap();
652
653 assert!(tty_sample.matches(&scope, &auth_user_from_uid(675)));
654 assert!(!tty_sample.matches(&scope, &auth_user_from_uid(789)));
655 assert!(!tty_sample.matches(
656 &RecordScope::Tty {
657 tty_device: DeviceId::new(20),
658 session_pid: ProcessId::new(1234),
659 init_time
660 },
661 &auth_user_from_uid(675),
662 ));
663 assert!(!tty_sample.matches(
664 &RecordScope::Ppid {
665 group_pid: ProcessId::new(42),
666 session_pid: ProcessId::new(43),
667 init_time
668 },
669 &auth_user_from_uid(675),
670 ));
671
672 // make sure time is different
673 std::thread::sleep(std::time::Duration::from_millis(1));
674 assert!(!tty_sample.matches(
675 &RecordScope::Tty {
676 tty_device: DeviceId::new(12),
677 session_pid: ProcessId::new(1234),
678 init_time: ProcessCreateTime::new(1, 1)
679 },
680 &auth_user_from_uid(675),
681 ));
682 }
683
684 #[test]
685 fn timestamp_record_written_between_works() {
686 let some_time = SystemTime::now().unwrap() + Duration::from_secs(100 * 60);
687 let scope = RecordScope::Tty {
688 tty_device: DeviceId::new(12),
689 session_pid: ProcessId::new(1234),
690 init_time: ProcessCreateTime::new(0, 0),
691 };
692 let sample = SessionRecord::init(scope, UserId::new(1234), true, some_time);
693
694 let dur = Duration::from_secs(30);
695
696 assert!(sample.written_between(some_time, some_time));
697 assert!(sample.written_between(some_time, some_time + dur));
698 assert!(sample.written_between(some_time - dur, some_time));
699 assert!(!sample.written_between(some_time + dur, some_time - dur));
700 assert!(!sample.written_between(some_time + dur, some_time + dur + dur));
701 assert!(!sample.written_between(some_time - dur - dur, some_time - dur));
702 }
703
704 fn tempfile_with_data(data: &[u8]) -> io::Result<File> {
705 let mut file = tempfile()?;
706 file.write_all(data)?;
707 file.rewind()?;
708 Ok(file)
709 }
710
711 fn data_from_tempfile(mut f: File) -> io::Result<Vec<u8>> {
712 let mut v = vec![];
713 f.rewind()?;
714 f.read_to_end(&mut v)?;
715 Ok(v)
716 }
717
718 #[test]
719 fn session_record_file_header_checks() {
720 // valid header should remain valid
721 let c = tempfile_with_data(&[0xD0, 0x50, 0x02, 0x00]).unwrap();
722 let timeout = Duration::from_secs(30);
723 assert!(SessionRecordFile::new(TEST_USER_ID, c.try_clone().unwrap(), timeout).is_ok());
724 let v = data_from_tempfile(c).unwrap();
725 assert_eq!(&v[..], &[0xD0, 0x50, 0x02, 0x00]);
726
727 // invalid headers should be corrected
728 let c = tempfile_with_data(&[0xAB, 0xBA]).unwrap();
729 assert!(SessionRecordFile::new(TEST_USER_ID, c.try_clone().unwrap(), timeout).is_ok());
730 let v = data_from_tempfile(c).unwrap();
731 assert_eq!(&v[..], &[0xD0, 0x50, 0x02, 0x00]);
732
733 // empty header should be filled in
734 let c = tempfile_with_data(&[]).unwrap();
735 assert!(SessionRecordFile::new(TEST_USER_ID, c.try_clone().unwrap(), timeout).is_ok());
736 let v = data_from_tempfile(c).unwrap();
737 assert_eq!(&v[..], &[0xD0, 0x50, 0x02, 0x00]);
738
739 // invalid version should reset file
740 let c = tempfile_with_data(&[0xD0, 0x50, 0xAB, 0xBA, 0x0, 0x0]).unwrap();
741 assert!(SessionRecordFile::new(TEST_USER_ID, c.try_clone().unwrap(), timeout).is_ok());
742 let v = data_from_tempfile(c).unwrap();
743 assert_eq!(&v[..], &[0xD0, 0x50, 0x02, 0x00]);
744 }
745
746 #[test]
747 fn can_create_and_update_valid_file() {
748 let timeout = Duration::from_secs(30);
749 let c = tempfile_with_data(&[]).unwrap();
750 let mut srf =
751 SessionRecordFile::new(TEST_USER_ID, c.try_clone().unwrap(), timeout).unwrap();
752 let tty_scope = RecordScope::Tty {
753 tty_device: DeviceId::new(0),
754 session_pid: ProcessId::new(0),
755 init_time: ProcessCreateTime::new(0, 0),
756 };
757 let auth_user = auth_user_from_uid(2424);
758 let res = srf.create(tty_scope, &auth_user).unwrap();
759 let CreateResult::Created { time } = res else {
760 panic!("Expected record to be created");
761 };
762
763 std::thread::sleep(std::time::Duration::from_millis(1));
764 let second = srf.touch(tty_scope, &auth_user).unwrap();
765 let TouchResult::Updated { old_time, new_time } = second else {
766 panic!("Expected record to be updated");
767 };
768 assert_eq!(time, old_time);
769 assert_ne!(old_time, new_time);
770
771 std::thread::sleep(std::time::Duration::from_millis(1));
772 let res = srf.create(tty_scope, &auth_user).unwrap();
773 let CreateResult::Updated { old_time, new_time } = res else {
774 panic!("Expected record to be updated");
775 };
776 assert_ne!(old_time, new_time);
777
778 // reset the file
779 assert!(srf.reset().is_ok());
780
781 // after all this the data should be just an empty header
782 let data = data_from_tempfile(c).unwrap();
783 assert_eq!(&data, &[0xD0, 0x50, 0x02, 0x00]);
784 }
785 }