add concept of user/session permissions

(I also considered the names "capabilities" and "scopes", but I think
"permissions" is the most widely understood.)

This is increasingly necessary as the web API becomes more capable.
Among other things, it allows:

* non-administrator users who can view but not access camera passwords
  or change any state
* workers that update signal state based on cameras' built-in motion
  detection or a security system's events but don't need to view videos
* control over what can be done without authenticating

Currently session permissions are just copied from user permissions, but
you can also imagine admin sessions vs not, as a checkbox when signing
in. This would match the standard Unix workflow of using a
non-administrative session most of the time.

Relevant to my current signals work (#28) and to the addition of an
administrative API (#35, including #66).
This commit is contained in:
Scott Lamb
2019-06-19 15:17:50 -07:00
parent d8b8d5d5e0
commit fda7e4ca2b
23 changed files with 336 additions and 741 deletions

View File

@@ -26,7 +26,7 @@ mylog = { git = "https://github.com/scottlamb/mylog" }
odds = { version = "0.3.1", features = ["std-vec"] }
openssl = "0.10"
parking_lot = { version = "0.8", features = [] }
protobuf = "2.0"
protobuf = { git = "https://github.com/stepancheg/rust-protobuf" }
regex = "1.0"
rusqlite = "0.18"
smallvec = "0.6"
@@ -34,3 +34,6 @@ tempdir = "0.3"
time = "0.1"
uuid = { version = "0.7", features = ["std", "v4"] }
itertools = "0.8.0"
[build-dependencies]
protobuf-codegen-pure = { git = "https://github.com/stepancheg/rust-protobuf" }

View File

@@ -31,11 +31,13 @@
use log::info;
use base::strutil;
use blake2_rfc::blake2b::blake2b;
use crate::schema::Permissions;
use failure::{Error, bail, format_err};
use fnv::FnvHashMap;
use lazy_static::lazy_static;
use libpasta;
use parking_lot::Mutex;
use protobuf::Message;
use rusqlite::{Connection, Transaction, types::ToSql};
use std::collections::BTreeMap;
use std::fmt;
@@ -68,6 +70,7 @@ pub struct User {
pub password_id: i32,
pub password_failure_count: i64,
pub unix_uid: Option<i32>,
pub permissions: Permissions,
/// True iff this `User` has changed since the last flush.
/// Only a couple things are flushed lazily: `password_failure_count` and (on upgrade to a new
@@ -79,10 +82,11 @@ impl User {
pub fn change(&self) -> UserChange {
UserChange {
id: Some(self.id),
username: self.username.to_string(),
username: self.username.clone(),
flags: self.flags,
set_password_hash: None,
unix_uid: self.unix_uid,
permissions: self.permissions.clone(),
}
}
@@ -103,6 +107,7 @@ pub struct UserChange {
pub flags: i32,
set_password_hash: Option<Option<String>>,
pub unix_uid: Option<i32>,
pub permissions: Permissions,
}
impl UserChange {
@@ -113,6 +118,7 @@ impl UserChange {
flags: 0,
set_password_hash: None,
unix_uid: None,
permissions: Permissions::default(),
}
}
@@ -215,6 +221,8 @@ pub struct Session {
revocation_reason: Option<i32>, // see RevocationReason enum
revocation_reason_detail: Option<String>,
pub permissions: Permissions,
last_use: Request,
use_count: i32,
dirty: bool,
@@ -342,7 +350,8 @@ impl State {
password_hash,
password_id,
password_failure_count,
unix_uid
unix_uid,
permissions
from
user
"#)?;
@@ -350,6 +359,8 @@ impl State {
while let Some(row) = rows.next()? {
let id = row.get(0)?;
let name: String = row.get(1)?;
let mut permissions = Permissions::new();
permissions.merge_from_bytes(row.get_raw_checked(7)?.as_blob()?)?;
state.users_by_id.insert(id, User {
id,
username: name.clone(),
@@ -359,6 +370,7 @@ impl State {
password_failure_count: row.get(5)?,
unix_uid: row.get(6)?,
dirty: false,
permissions,
});
state.users_by_name.insert(name, id);
}
@@ -385,7 +397,8 @@ impl State {
password_id = :password_id,
password_failure_count = :password_failure_count,
flags = :flags,
unix_uid = :unix_uid
unix_uid = :unix_uid,
permissions = :permissions
where
id = :id
"#)?;
@@ -402,6 +415,7 @@ impl State {
},
Some(h) => (h, e.get().password_id + 1, 0),
};
let permissions = change.permissions.write_to_bytes().expect("proto3->vec is infallible");
stmt.execute_named(&[
(":username", &&change.username[..]),
(":password_hash", phash),
@@ -410,6 +424,7 @@ impl State {
(":flags", &change.flags),
(":unix_uid", &change.unix_uid),
(":id", &id),
(":permissions", &permissions),
])?;
}
let u = e.into_mut();
@@ -421,20 +436,23 @@ impl State {
}
u.flags = change.flags;
u.unix_uid = change.unix_uid;
u.permissions = change.permissions;
Ok(u)
}
fn add_user(&mut self, conn: &Connection, change: UserChange) -> Result<&User, Error> {
let mut stmt = conn.prepare_cached(r#"
insert into user (username, password_hash, flags, unix_uid)
values (:username, :password_hash, :flags, :unix_uid)
insert into user (username, password_hash, flags, unix_uid, permissions)
values (:username, :password_hash, :flags, :unix_uid, :permissions)
"#)?;
let password_hash = change.set_password_hash.unwrap_or(None);
let permissions = change.permissions.write_to_bytes().expect("proto3->vec is infallible");
stmt.execute_named(&[
(":username", &&change.username[..]),
(":password_hash", &password_hash),
(":flags", &change.flags),
(":unix_uid", &change.unix_uid),
(":permissions", &permissions),
])?;
let id = conn.last_insert_rowid() as i32;
self.users_by_name.insert(change.username.clone(), id);
@@ -452,6 +470,7 @@ impl State {
password_failure_count: 0,
unix_uid: change.unix_uid,
dirty: false,
permissions: change.permissions,
}))
}
@@ -503,12 +522,13 @@ impl State {
}
let password_id = u.password_id;
State::make_session(conn, req, u, domain, Some(password_id), session_flags,
&mut self.sessions)
&mut self.sessions, u.permissions.clone())
}
fn make_session<'s>(conn: &Connection, creation: Request, user: &mut User, domain: Vec<u8>,
creation_password_id: Option<i32>, flags: i32,
sessions: &'s mut FnvHashMap<SessionHash, Session>)
sessions: &'s mut FnvHashMap<SessionHash, Session>,
permissions: Permissions)
-> Result<(RawSessionId, &'s Session), Error> {
let mut session_id = RawSessionId::new();
::openssl::rand::rand_bytes(&mut session_id.0).unwrap();
@@ -518,13 +538,16 @@ impl State {
let mut stmt = conn.prepare_cached(r#"
insert into user_session (session_id_hash, user_id, seed, flags, domain,
creation_password_id, creation_time_sec,
creation_user_agent, creation_peer_addr)
creation_user_agent, creation_peer_addr,
permissions)
values (:session_id_hash, :user_id, :seed, :flags, :domain,
:creation_password_id, :creation_time_sec,
:creation_user_agent, :creation_peer_addr)
:creation_user_agent, :creation_peer_addr,
:permissions)
"#)?;
let addr = creation.addr_buf();
let addr: Option<&[u8]> = addr.as_ref().map(|a| a.as_ref());
let permissions_blob = permissions.write_to_bytes().expect("proto3->vec is infallible");
stmt.execute_named(&[
(":session_id_hash", &&hash.0[..]),
(":user_id", &user.id),
@@ -535,6 +558,7 @@ impl State {
(":creation_time_sec", &creation.when_sec),
(":creation_user_agent", &creation.user_agent),
(":creation_peer_addr", &addr),
(":permissions", &permissions_blob),
])?;
let e = match sessions.entry(hash) {
::std::collections::hash_map::Entry::Occupied(_) => panic!("duplicate session hash!"),
@@ -547,6 +571,7 @@ impl State {
creation_password_id,
creation,
seed: Seed(seed),
permissions,
..Default::default()
});
Ok((session_id, session))
@@ -692,7 +717,8 @@ fn lookup_session(conn: &Connection, hash: &SessionHash) -> Result<Session, Erro
last_use_time_sec,
last_use_user_agent,
last_use_peer_addr,
use_count
use_count,
permissions
from
user_session
where
@@ -703,6 +729,8 @@ fn lookup_session(conn: &Connection, hash: &SessionHash) -> Result<Session, Erro
let creation_addr: FromSqlIpAddr = row.get(8)?;
let revocation_addr: FromSqlIpAddr = row.get(11)?;
let last_use_addr: FromSqlIpAddr = row.get(16)?;
let mut permissions = Permissions::new();
permissions.merge_from_bytes(row.get_raw_checked(18)?.as_blob()?)?;
Ok(Session {
user_id: row.get(0)?,
seed: row.get(1)?,
@@ -729,6 +757,7 @@ fn lookup_session(conn: &Connection, hash: &SessionHash) -> Result<Session, Erro
},
use_count: row.get(17)?,
dirty: false,
permissions,
})
}
@@ -961,4 +990,35 @@ mod tests {
let e = state.authenticate_session(&conn, req.clone(), &sid.hash()).unwrap_err();
assert_eq!(format!("{}", e), "no such session");
}
#[test]
fn permissions() {
testutil::init();
let mut conn = Connection::open_in_memory().unwrap();
db::init(&mut conn).unwrap();
let mut state = State::init(&conn).unwrap();
let mut change = UserChange::add_user("slamb".to_owned());
change.permissions.view_video = true;
let u = state.apply(&conn, change).unwrap();
assert!(u.permissions.view_video);
assert!(!u.permissions.update_signals);
let mut change = u.change();
assert!(change.permissions.view_video);
assert!(!change.permissions.update_signals);
change.permissions.update_signals = true;
let u = state.apply(&conn, change).unwrap();
assert!(u.permissions.view_video);
assert!(u.permissions.update_signals);
let uid = u.id;
{
let tx = conn.transaction().unwrap();
state.flush(&tx).unwrap();
tx.commit().unwrap();
}
let state = State::init(&conn).unwrap();
let u = state.users_by_id().get(&uid).unwrap();
assert!(u.permissions.view_video);
assert!(u.permissions.update_signals);
}
}

View File

@@ -37,6 +37,7 @@ use crate::recording;
use failure::Error;
use fnv::FnvHashMap;
use log::error;
use protobuf::prelude::MessageField;
use rusqlite::types::ToSql;
use crate::schema;
use std::os::unix::ffi::OsStrExt;
@@ -69,7 +70,7 @@ pub fn run(conn: &rusqlite::Connection, opts: &Options) -> Result<(), Error> {
meta.db_uuid.extend_from_slice(&db_uuid.as_bytes()[..]);
meta.dir_uuid.extend_from_slice(&dir_uuid.0.as_bytes()[..]);
{
let o = meta.mut_last_complete_open();
let o = meta.last_complete_open.mut_message();
o.id = open_id;
o.uuid.extend_from_slice(&open_uuid.0.as_bytes()[..]);
}

View File

@@ -66,6 +66,7 @@ use log::{error, info, trace};
use lru_cache::LruCache;
use openssl::hash;
use parking_lot::{Mutex,MutexGuard};
use protobuf::prelude::MessageField;
use rusqlite::types::ToSql;
use smallvec::SmallVec;
use std::collections::{BTreeMap, VecDeque};
@@ -326,7 +327,7 @@ impl SampleFileDir {
meta.db_uuid.extend_from_slice(&db_uuid.as_bytes()[..]);
meta.dir_uuid.extend_from_slice(&self.uuid.as_bytes()[..]);
if let Some(o) = self.last_complete_open {
let open = meta.mut_last_complete_open();
let open = meta.last_complete_open.mut_message();
open.id = o.id;
open.uuid.extend_from_slice(&o.uuid.as_bytes()[..]);
}
@@ -1061,7 +1062,7 @@ impl LockedDatabase {
if dir.dir.is_some() { continue }
let mut meta = dir.meta(&self.uuid);
if let Some(o) = self.open.as_ref() {
let open = meta.mut_in_progress_open();
let open = meta.in_progress_open.mut_message();
open.id = o.id;
open.uuid.extend_from_slice(&o.uuid.as_bytes()[..]);
}
@@ -1540,7 +1541,7 @@ impl LockedDatabase {
{
meta.db_uuid.extend_from_slice(&self.uuid.as_bytes()[..]);
meta.dir_uuid.extend_from_slice(uuid_bytes);
let open = meta.mut_in_progress_open();
let open = meta.in_progress_open.mut_message();
open.id = o.id;
open.uuid.extend_from_slice(&o.uuid.as_bytes()[..]);
}

View File

@@ -47,4 +47,5 @@ pub mod writer;
pub mod testutil;
pub use crate::db::*;
pub use crate::schema::Permissions;
pub use crate::signal::Signal;

View File

@@ -60,3 +60,22 @@ message DirMeta {
// guaranteed that no data has yet been written by this open.
Open in_progress_open = 4;
}
// Permissions to perform actions, currently all simple bools.
//
// These indicate actions which may be unnecessary in some contexts. Some
// basic access - like listing the cameras - is currently always allowed.
// See design/api.md for a description of what requires these permissions.
//
// These are used in a few contexts:
// * a session - affects what can be done when using that session to
// authenticate.
// * a user - when a new session is created, it inherits these permissions.
// * on the commandline - to specify what permissions are available for
// unauthenticated access.
message Permissions {
bool view_video = 1;
bool read_camera_configs = 2;
bool update_signals = 3;
}

View File

@@ -1,642 +0,0 @@
// This file is generated by rust-protobuf 2.0.4. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(trivial_casts)]
#![allow(unsafe_code)]
#![allow(unused_imports)]
#![allow(unused_results)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(PartialEq,Clone,Default)]
pub struct DirMeta {
// message fields
pub db_uuid: ::std::vec::Vec<u8>,
pub dir_uuid: ::std::vec::Vec<u8>,
pub last_complete_open: ::protobuf::SingularPtrField<DirMeta_Open>,
pub in_progress_open: ::protobuf::SingularPtrField<DirMeta_Open>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl DirMeta {
pub fn new() -> DirMeta {
::std::default::Default::default()
}
// bytes db_uuid = 1;
pub fn clear_db_uuid(&mut self) {
self.db_uuid.clear();
}
// Param is passed by value, moved
pub fn set_db_uuid(&mut self, v: ::std::vec::Vec<u8>) {
self.db_uuid = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_db_uuid(&mut self) -> &mut ::std::vec::Vec<u8> {
&mut self.db_uuid
}
// Take field
pub fn take_db_uuid(&mut self) -> ::std::vec::Vec<u8> {
::std::mem::replace(&mut self.db_uuid, ::std::vec::Vec::new())
}
pub fn get_db_uuid(&self) -> &[u8] {
&self.db_uuid
}
// bytes dir_uuid = 2;
pub fn clear_dir_uuid(&mut self) {
self.dir_uuid.clear();
}
// Param is passed by value, moved
pub fn set_dir_uuid(&mut self, v: ::std::vec::Vec<u8>) {
self.dir_uuid = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_dir_uuid(&mut self) -> &mut ::std::vec::Vec<u8> {
&mut self.dir_uuid
}
// Take field
pub fn take_dir_uuid(&mut self) -> ::std::vec::Vec<u8> {
::std::mem::replace(&mut self.dir_uuid, ::std::vec::Vec::new())
}
pub fn get_dir_uuid(&self) -> &[u8] {
&self.dir_uuid
}
// .DirMeta.Open last_complete_open = 3;
pub fn clear_last_complete_open(&mut self) {
self.last_complete_open.clear();
}
pub fn has_last_complete_open(&self) -> bool {
self.last_complete_open.is_some()
}
// Param is passed by value, moved
pub fn set_last_complete_open(&mut self, v: DirMeta_Open) {
self.last_complete_open = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_last_complete_open(&mut self) -> &mut DirMeta_Open {
if self.last_complete_open.is_none() {
self.last_complete_open.set_default();
}
self.last_complete_open.as_mut().unwrap()
}
// Take field
pub fn take_last_complete_open(&mut self) -> DirMeta_Open {
self.last_complete_open.take().unwrap_or_else(|| DirMeta_Open::new())
}
pub fn get_last_complete_open(&self) -> &DirMeta_Open {
self.last_complete_open.as_ref().unwrap_or_else(|| DirMeta_Open::default_instance())
}
// .DirMeta.Open in_progress_open = 4;
pub fn clear_in_progress_open(&mut self) {
self.in_progress_open.clear();
}
pub fn has_in_progress_open(&self) -> bool {
self.in_progress_open.is_some()
}
// Param is passed by value, moved
pub fn set_in_progress_open(&mut self, v: DirMeta_Open) {
self.in_progress_open = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_in_progress_open(&mut self) -> &mut DirMeta_Open {
if self.in_progress_open.is_none() {
self.in_progress_open.set_default();
}
self.in_progress_open.as_mut().unwrap()
}
// Take field
pub fn take_in_progress_open(&mut self) -> DirMeta_Open {
self.in_progress_open.take().unwrap_or_else(|| DirMeta_Open::new())
}
pub fn get_in_progress_open(&self) -> &DirMeta_Open {
self.in_progress_open.as_ref().unwrap_or_else(|| DirMeta_Open::default_instance())
}
}
impl ::protobuf::Message for DirMeta {
fn is_initialized(&self) -> bool {
for v in &self.last_complete_open {
if !v.is_initialized() {
return false;
}
};
for v in &self.in_progress_open {
if !v.is_initialized() {
return false;
}
};
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.db_uuid)?;
},
2 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.dir_uuid)?;
},
3 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.last_complete_open)?;
},
4 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.in_progress_open)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if !self.db_uuid.is_empty() {
my_size += ::protobuf::rt::bytes_size(1, &self.db_uuid);
}
if !self.dir_uuid.is_empty() {
my_size += ::protobuf::rt::bytes_size(2, &self.dir_uuid);
}
if let Some(ref v) = self.last_complete_open.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.in_progress_open.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if !self.db_uuid.is_empty() {
os.write_bytes(1, &self.db_uuid)?;
}
if !self.dir_uuid.is_empty() {
os.write_bytes(2, &self.dir_uuid)?;
}
if let Some(ref v) = self.last_complete_open.as_ref() {
os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.in_progress_open.as_ref() {
os.write_tag(4, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &dyn (::std::any::Any) {
self as &dyn (::std::any::Any)
}
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
self as &mut dyn (::std::any::Any)
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> DirMeta {
DirMeta::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"db_uuid",
|m: &DirMeta| { &m.db_uuid },
|m: &mut DirMeta| { &mut m.db_uuid },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"dir_uuid",
|m: &DirMeta| { &m.dir_uuid },
|m: &mut DirMeta| { &mut m.dir_uuid },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<DirMeta_Open>>(
"last_complete_open",
|m: &DirMeta| { &m.last_complete_open },
|m: &mut DirMeta| { &mut m.last_complete_open },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<DirMeta_Open>>(
"in_progress_open",
|m: &DirMeta| { &m.in_progress_open },
|m: &mut DirMeta| { &mut m.in_progress_open },
));
::protobuf::reflect::MessageDescriptor::new::<DirMeta>(
"DirMeta",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static DirMeta {
static mut instance: ::protobuf::lazy::Lazy<DirMeta> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const DirMeta,
};
unsafe {
instance.get(DirMeta::new)
}
}
}
impl ::protobuf::Clear for DirMeta {
fn clear(&mut self) {
self.clear_db_uuid();
self.clear_dir_uuid();
self.clear_last_complete_open();
self.clear_in_progress_open();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for DirMeta {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for DirMeta {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct DirMeta_Open {
// message fields
pub id: u32,
pub uuid: ::std::vec::Vec<u8>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl DirMeta_Open {
pub fn new() -> DirMeta_Open {
::std::default::Default::default()
}
// uint32 id = 1;
pub fn clear_id(&mut self) {
self.id = 0;
}
// Param is passed by value, moved
pub fn set_id(&mut self, v: u32) {
self.id = v;
}
pub fn get_id(&self) -> u32 {
self.id
}
// bytes uuid = 2;
pub fn clear_uuid(&mut self) {
self.uuid.clear();
}
// Param is passed by value, moved
pub fn set_uuid(&mut self, v: ::std::vec::Vec<u8>) {
self.uuid = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_uuid(&mut self) -> &mut ::std::vec::Vec<u8> {
&mut self.uuid
}
// Take field
pub fn take_uuid(&mut self) -> ::std::vec::Vec<u8> {
::std::mem::replace(&mut self.uuid, ::std::vec::Vec::new())
}
pub fn get_uuid(&self) -> &[u8] {
&self.uuid
}
}
impl ::protobuf::Message for DirMeta_Open {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint32()?;
self.id = tmp;
},
2 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.uuid)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if self.id != 0 {
my_size += ::protobuf::rt::value_size(1, self.id, ::protobuf::wire_format::WireTypeVarint);
}
if !self.uuid.is_empty() {
my_size += ::protobuf::rt::bytes_size(2, &self.uuid);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if self.id != 0 {
os.write_uint32(1, self.id)?;
}
if !self.uuid.is_empty() {
os.write_bytes(2, &self.uuid)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &dyn (::std::any::Any) {
self as &dyn (::std::any::Any)
}
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
self as &mut dyn (::std::any::Any)
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> DirMeta_Open {
DirMeta_Open::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>(
"id",
|m: &DirMeta_Open| { &m.id },
|m: &mut DirMeta_Open| { &mut m.id },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"uuid",
|m: &DirMeta_Open| { &m.uuid },
|m: &mut DirMeta_Open| { &mut m.uuid },
));
::protobuf::reflect::MessageDescriptor::new::<DirMeta_Open>(
"DirMeta_Open",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static DirMeta_Open {
static mut instance: ::protobuf::lazy::Lazy<DirMeta_Open> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const DirMeta_Open,
};
unsafe {
instance.get(DirMeta_Open::new)
}
}
}
impl ::protobuf::Clear for DirMeta_Open {
fn clear(&mut self) {
self.clear_id();
self.clear_uuid();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for DirMeta_Open {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for DirMeta_Open {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
static file_descriptor_proto_data: &'static [u8] = b"\
\n\x0cschema.proto\"\xdf\x01\n\x07DirMeta\x12\x17\n\x07db_uuid\x18\x01\
\x20\x01(\x0cR\x06dbUuid\x12\x19\n\x08dir_uuid\x18\x02\x20\x01(\x0cR\x07\
dirUuid\x12;\n\x12last_complete_open\x18\x03\x20\x01(\x0b2\r.DirMeta.Ope\
nR\x10lastCompleteOpen\x127\n\x10in_progress_open\x18\x04\x20\x01(\x0b2\
\r.DirMeta.OpenR\x0einProgressOpen\x1a*\n\x04Open\x12\x0e\n\x02id\x18\
\x01\x20\x01(\rR\x02id\x12\x12\n\x04uuid\x18\x02\x20\x01(\x0cR\x04uuidJ\
\xc1\x17\n\x06\x12\x04\x1e\0=\x01\n\xc2\x0b\n\x01\x0c\x12\x03\x1e\0\x122\
\xb7\x0b\x20This\x20file\x20is\x20part\x20of\x20Moonfire\x20NVR,\x20a\
\x20security\x20camera\x20digital\x20video\x20recorder.\n\x20Copyright\
\x20(C)\x202018\x20Scott\x20Lamb\x20<slamb@slamb.org>\n\n\x20This\x20pro\
gram\x20is\x20free\x20software:\x20you\x20can\x20redistribute\x20it\x20a\
nd/or\x20modify\n\x20it\x20under\x20the\x20terms\x20of\x20the\x20GNU\x20\
General\x20Public\x20License\x20as\x20published\x20by\n\x20the\x20Free\
\x20Software\x20Foundation,\x20either\x20version\x203\x20of\x20the\x20Li\
cense,\x20or\n\x20(at\x20your\x20option)\x20any\x20later\x20version.\n\n\
\x20In\x20addition,\x20as\x20a\x20special\x20exception,\x20the\x20copyri\
ght\x20holders\x20give\n\x20permission\x20to\x20link\x20the\x20code\x20o\
f\x20portions\x20of\x20this\x20program\x20with\x20the\n\x20OpenSSL\x20li\
brary\x20under\x20certain\x20conditions\x20as\x20described\x20in\x20each\
\n\x20individual\x20source\x20file,\x20and\x20distribute\x20linked\x20co\
mbinations\x20including\n\x20the\x20two.\n\n\x20You\x20must\x20obey\x20t\
he\x20GNU\x20General\x20Public\x20License\x20in\x20all\x20respects\x20fo\
r\x20all\n\x20of\x20the\x20code\x20used\x20other\x20than\x20OpenSSL.\x20\
If\x20you\x20modify\x20file(s)\x20with\x20this\n\x20exception,\x20you\
\x20may\x20extend\x20this\x20exception\x20to\x20your\x20version\x20of\
\x20the\n\x20file(s),\x20but\x20you\x20are\x20not\x20obligated\x20to\x20\
do\x20so.\x20If\x20you\x20do\x20not\x20wish\x20to\x20do\n\x20so,\x20dele\
te\x20this\x20exception\x20statement\x20from\x20your\x20version.\x20If\
\x20you\x20delete\n\x20this\x20exception\x20statement\x20from\x20all\x20\
source\x20files\x20in\x20the\x20program,\x20then\n\x20also\x20delete\x20\
it\x20here.\n\n\x20This\x20program\x20is\x20distributed\x20in\x20the\x20\
hope\x20that\x20it\x20will\x20be\x20useful,\n\x20but\x20WITHOUT\x20ANY\
\x20WARRANTY;\x20without\x20even\x20the\x20implied\x20warranty\x20of\n\
\x20MERCHANTABILITY\x20or\x20FITNESS\x20FOR\x20A\x20PARTICULAR\x20PURPOS\
E.\x20\x20See\x20the\n\x20GNU\x20General\x20Public\x20License\x20for\x20\
more\x20details.\n\n\x20You\x20should\x20have\x20received\x20a\x20copy\
\x20of\x20the\x20GNU\x20General\x20Public\x20License\n\x20along\x20with\
\x20this\x20program.\x20\x20If\x20not,\x20see\x20<http://www.gnu.org/lic\
enses/>.\n\n\xf1\x01\n\x02\x04\0\x12\x04$\0=\x01\x1a\xe4\x01\x20Metadata\
\x20stored\x20in\x20sample\x20file\x20dirs\x20as\x20\"<dir>/meta\".\x20T\
his\x20is\x20checked\n\x20against\x20the\x20metadata\x20stored\x20within\
\x20the\x20database\x20to\x20detect\x20inconsistencies\n\x20between\x20t\
he\x20directory\x20and\x20database,\x20such\x20as\x20those\x20described\
\x20in\n\x20design/schema.md.\n\n\n\n\x03\x04\0\x01\x12\x03$\x08\x0f\n\
\xcf\x01\n\x04\x04\0\x02\0\x12\x03(\x02\x14\x1a\xc1\x01\x20A\x20uuid\x20\
associated\x20with\x20the\x20database,\x20in\x20binary\x20form.\x20dir_u\
uid\x20is\x20strictly\n\x20more\x20powerful,\x20but\x20it\x20improves\
\x20diagnostics\x20to\x20know\x20if\x20the\x20directory\n\x20belongs\x20\
to\x20the\x20expected\x20database\x20at\x20all\x20or\x20not.\n\n\r\n\x05\
\x04\0\x02\0\x04\x12\x04(\x02$\x11\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03(\
\x02\x07\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03(\x08\x0f\n\x0c\n\x05\x04\0\
\x02\0\x03\x12\x03(\x12\x13\n;\n\x04\x04\0\x02\x01\x12\x03+\x02\x15\x1a.\
\x20A\x20uuid\x20associated\x20with\x20the\x20directory\x20itself.\n\n\r\
\n\x05\x04\0\x02\x01\x04\x12\x04+\x02(\x14\n\x0c\n\x05\x04\0\x02\x01\x05\
\x12\x03+\x02\x07\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03+\x08\x10\n\x0c\n\
\x05\x04\0\x02\x01\x03\x12\x03+\x13\x14\nE\n\x04\x04\0\x03\0\x12\x04.\
\x021\x03\x1a7\x20Corresponds\x20to\x20an\x20entry\x20in\x20the\x20`open\
`\x20database\x20table.\n\n\x0c\n\x05\x04\0\x03\0\x01\x12\x03.\n\x0e\n\r\
\n\x06\x04\0\x03\0\x02\0\x12\x03/\x04\x12\n\x0f\n\x07\x04\0\x03\0\x02\0\
\x04\x12\x04/\x04.\x10\n\x0e\n\x07\x04\0\x03\0\x02\0\x05\x12\x03/\x04\n\
\n\x0e\n\x07\x04\0\x03\0\x02\0\x01\x12\x03/\x0b\r\n\x0e\n\x07\x04\0\x03\
\0\x02\0\x03\x12\x03/\x10\x11\n\r\n\x06\x04\0\x03\0\x02\x01\x12\x030\x04\
\x13\n\x0f\n\x07\x04\0\x03\0\x02\x01\x04\x12\x040\x04/\x12\n\x0e\n\x07\
\x04\0\x03\0\x02\x01\x05\x12\x030\x04\t\n\x0e\n\x07\x04\0\x03\0\x02\x01\
\x01\x12\x030\n\x0e\n\x0e\n\x07\x04\0\x03\0\x02\x01\x03\x12\x030\x11\x12\
\n\xb0\x02\n\x04\x04\0\x02\x02\x12\x037\x02\x1e\x1a\xa2\x02\x20The\x20la\
st\x20open\x20that\x20was\x20known\x20to\x20be\x20recorded\x20in\x20the\
\x20database\x20as\x20completed.\n\x20Absent\x20if\x20this\x20has\x20nev\
er\x20happened.\x20Note\x20this\x20can\x20backtrack\x20in\x20exactly\x20\
one\n\x20scenario:\x20when\x20deleting\x20the\x20directory,\x20after\x20\
all\x20associated\x20files\x20have\n\x20been\x20deleted,\x20last_complet\
e_open\x20can\x20be\x20moved\x20to\x20in_progress_open.\n\n\r\n\x05\x04\
\0\x02\x02\x04\x12\x047\x021\x03\n\x0c\n\x05\x04\0\x02\x02\x06\x12\x037\
\x02\x06\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x037\x07\x19\n\x0c\n\x05\x04\
\0\x02\x02\x03\x12\x037\x1c\x1d\n\xd6\x01\n\x04\x04\0\x02\x03\x12\x03<\
\x02\x1c\x1a\xc8\x01\x20The\x20last\x20run\x20which\x20is\x20in\x20progr\
ess,\x20if\x20different\x20from\x20last_complete_open.\n\x20This\x20may\
\x20or\x20may\x20not\x20have\x20been\x20recorded\x20in\x20the\x20databas\
e,\x20but\x20it's\n\x20guaranteed\x20that\x20no\x20data\x20has\x20yet\
\x20been\x20written\x20by\x20this\x20open.\n\n\r\n\x05\x04\0\x02\x03\x04\
\x12\x04<\x027\x1e\n\x0c\n\x05\x04\0\x02\x03\x06\x12\x03<\x02\x06\n\x0c\
\n\x05\x04\0\x02\x03\x01\x12\x03<\x07\x17\n\x0c\n\x05\x04\0\x02\x03\x03\
\x12\x03<\x1a\x1bb\x06proto3\
";
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
}

View File

@@ -328,7 +328,11 @@ create table user (
-- a Unix domain socket. (Additionally, the UID running Moonfire NVR can authenticate
-- as anyone; there's no point in trying to do otherwise.) This might be an easy
-- bootstrap method once configuration happens through a web UI rather than text UI.
unix_uid integer
unix_uid integer,
-- Permissions available for newly created tokens or when authenticating via
-- unix_uid above. A serialized "Permissions" protobuf.
permissions blob
);
-- A single session, whether for browser or robot use.
@@ -391,7 +395,10 @@ create table user_session (
last_use_time_sec integer, -- sec since epoch
last_use_user_agent text, -- User-Agent header from inbound HTTP request.
last_use_peer_addr blob, -- IPv4 or IPv6 address, or null for Unix socket.
use_count not null default 0
use_count not null default 0,
-- Permissions associated with this token; a serialized "Permissions" protobuf.
permissions blob
) without rowid;
create index user_session_uid on user_session (user_id);

View File

@@ -33,6 +33,7 @@
use crate::dir;
use failure::{Error, bail, format_err};
use libc;
use protobuf::prelude::MessageField;
use rusqlite::types::ToSql;
use crate::schema::DirMeta;
use std::fs;
@@ -113,7 +114,7 @@ pub fn run(args: &super::Args, tx: &rusqlite::Transaction) -> Result<(), Error>
{
meta.db_uuid.extend_from_slice(db_uuid_bytes);
meta.dir_uuid.extend_from_slice(dir_uuid_bytes);
let open = meta.mut_last_complete_open();
let open = meta.last_complete_open.mut_message();
open.id = open_id;
open.uuid.extend_from_slice(&open_uuid_bytes);
}

View File

@@ -37,10 +37,11 @@ use crate::dir;
use failure::Error;
use libc;
use crate::schema;
use protobuf::prelude::MessageField;
use rusqlite::types::ToSql;
use std::io::{self, Write};
use std::mem;
use std::sync::Arc;
use rusqlite::types::ToSql;
use uuid::Uuid;
/// Opens the sample file dir.
@@ -68,7 +69,7 @@ fn open_sample_file_dir(tx: &rusqlite::Transaction) -> Result<Arc<dir::SampleFil
meta.db_uuid.extend_from_slice(&db_uuid.0.as_bytes()[..]);
meta.dir_uuid.extend_from_slice(&s_uuid.0.as_bytes()[..]);
{
let open = meta.mut_last_complete_open();
let open = meta.last_complete_open.mut_message();
open.id = o_id as u32;
open.uuid.extend_from_slice(&o_uuid.0.as_bytes()[..]);
}

View File

@@ -62,6 +62,9 @@ pub fn run(_args: &super::Args, tx: &rusqlite::Transaction) -> Result<(), Error>
time_90k integer primary key,
changes blob
);
alter table user add column permissions blob;
alter table user_session add column permissions blob;
"#)?;
Ok(())
}