Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Showcase how state can be used in the cli #958

Draft
wants to merge 6 commits into
base: sqlite-wasm
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 59 additions & 0 deletions crates/bitwarden-core/src/auth/auth_repository.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use bitwarden_crypto::Kdf;
use bitwarden_db::DatabaseError;
use thiserror::Error;

use crate::platform::SettingsRepository;

const SETTINGS_KEY: &str = "auth";

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct AuthSettings {
pub email: String,
pub token: String,
pub refresh_token: Option<String>,
pub kdf: Kdf,

pub user_key: String,
pub private_key: String,
}

#[derive(Debug, Error)]
pub enum AuthRepositoryError {
#[error(transparent)]
Database(#[from] DatabaseError),
#[error(transparent)]
Serde(#[from] serde_json::Error),
}

pub struct AuthRepository {
settings_repository: SettingsRepository,
}

impl AuthRepository {
pub fn new(settings_repository: SettingsRepository) -> Self {
Self {
settings_repository,
}
}

pub(crate) async fn save(&self, setting: AuthSettings) -> Result<(), AuthRepositoryError> {
let serialized = serde_json::to_string(&setting)?;
self.settings_repository
.set(SETTINGS_KEY, &serialized)
.await?;

Ok(())
}

pub(crate) async fn get(&self) -> Result<Option<AuthSettings>, AuthRepositoryError> {
let settings = self.settings_repository.get(SETTINGS_KEY).await?;

match settings {
Some(settings) => {
let settings: AuthSettings = serde_json::from_str(&settings)?;
Ok(Some(settings))
}
None => Ok(None),
}
}
}
21 changes: 17 additions & 4 deletions crates/bitwarden-core/src/auth/client_auth.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#[cfg(feature = "internal")]
use bitwarden_crypto::{AsymmetricEncString, DeviceKey, EncString, Kdf, TrustDeviceResponse};

use super::UnlockError;
#[cfg(feature = "state")]
use super::{unlock, AuthRepository};
#[cfg(feature = "internal")]
use crate::auth::login::NewAuthRequestResponse;
#[cfg(feature = "secrets")]
Expand All @@ -25,6 +28,8 @@ use crate::{auth::renew::renew_token, error::Result, Client};

pub struct ClientAuth<'a> {
pub(crate) client: &'a crate::Client,
#[cfg(feature = "state")]
pub(super) repository: AuthRepository,
}

impl<'a> ClientAuth<'a> {
Expand Down Expand Up @@ -132,10 +137,7 @@ impl<'a> ClientAuth<'a> {
pub fn trust_device(&self) -> Result<TrustDeviceResponse> {
trust_device(self.client)
}
}

#[cfg(feature = "internal")]
impl<'a> ClientAuth<'a> {
pub async fn login_device(
&self,
email: String,
Expand All @@ -153,6 +155,13 @@ impl<'a> ClientAuth<'a> {
}
}

#[cfg(feature = "state")]
impl<'a> ClientAuth<'a> {
pub async fn unlock(&self, password: String) -> Result<(), UnlockError> {
unlock(self.client, password).await
}
}

#[cfg(feature = "internal")]
fn trust_device(client: &Client) -> Result<TrustDeviceResponse> {
let enc = client.internal.get_encryption_settings()?;
Expand All @@ -164,7 +173,11 @@ fn trust_device(client: &Client) -> Result<TrustDeviceResponse> {

impl<'a> Client {
pub fn auth(&'a self) -> ClientAuth<'a> {
ClientAuth { client: self }
ClientAuth {
client: self,
#[cfg(feature = "state")]
repository: AuthRepository::new(self.platform().settings_repository),
}
}
}

Expand Down
33 changes: 28 additions & 5 deletions crates/bitwarden-core/src/auth/login/api_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use bitwarden_crypto::{EncString, MasterKey};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[cfg(feature = "state")]
use crate::auth::AuthSettings;
use crate::{
auth::{
api::{request::ApiTokenRequest, response::IdentityTokenResponse},
Expand Down Expand Up @@ -45,16 +47,37 @@ pub(crate) async fn login_api_key(
.set_login_method(LoginMethod::User(UserLoginMethod::ApiKey {
client_id: input.client_id.to_owned(),
client_secret: input.client_secret.to_owned(),
email,
kdf,
email: email.clone(),
kdf: kdf.clone(),
}));

let user_key: EncString = require!(r.key.as_deref()).parse()?;
let private_key: EncString = require!(r.private_key.as_deref()).parse()?;

client
.internal
.initialize_user_crypto_master_key(master_key, user_key, private_key)?;
client.internal.initialize_user_crypto_master_key(
master_key,
user_key.clone(),
private_key.clone(),
)?;

#[cfg(feature = "state")]
{
let setting = AuthSettings {
email: email.clone(),
token: r.access_token.clone(),
refresh_token: r.refresh_token.clone(),
kdf: kdf.clone(),
user_key: user_key.to_string(),
private_key: private_key.to_string(),
};

client
.auth()
.repository
.save(setting)
.await
.expect("Save settings");
}
}

ApiKeyLoginResponse::process_response(response)
Expand Down
14 changes: 14 additions & 0 deletions crates/bitwarden-core/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ pub use tde::RegisterTdeKeyResponse;
#[cfg(feature = "internal")]
use crate::error::Result;

#[cfg(feature = "state")]
#[path = ""]
mod state {
mod auth_repository;
pub use auth_repository::{AuthRepository, AuthSettings};

mod unlock;
pub(super) use unlock::unlock;
pub use unlock::UnlockError;
}

#[cfg(feature = "state")]
pub use state::*;

#[cfg(feature = "internal")]
fn determine_password_hash(
email: &str,
Expand Down
40 changes: 40 additions & 0 deletions crates/bitwarden-core/src/auth/unlock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use bitwarden_crypto::{CryptoError, MasterKey};
use thiserror::Error;

use super::auth_repository::AuthRepositoryError;
use crate::Client;

#[derive(Debug, Error)]
pub enum UnlockError {
#[error(transparent)]
AuthRepository(#[from] AuthRepositoryError),

#[error(transparent)]
Crypto(#[from] CryptoError),

#[error("The client is not authenticated or the session has expired")]
NotAuthenticated,
}

pub(crate) async fn unlock(
client: &Client,
password: String,
) -> std::result::Result<(), UnlockError> {
let settings = client
.auth()
.repository
.get()
.await?
.ok_or(UnlockError::NotAuthenticated)?;

// client.internal.set_login_method(UserLoginMethod::ApiKey { client_id: (), client_secret: (),
// email: (), kdf: () })
let master_key = MasterKey::derive(&password, &settings.email, &settings.kdf)?;
client.internal.initialize_user_crypto_master_key(
master_key,
settings.user_key.parse()?,
settings.private_key.parse()?,
);

Ok(())
}
10 changes: 9 additions & 1 deletion crates/bitwarden-core/src/platform/client_platform.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#[cfg(feature = "state")]
use super::settings_repository::SettingsRepository;
use super::{
generate_fingerprint::{generate_fingerprint, generate_user_fingerprint},
get_user_api_key, FingerprintRequest, FingerprintResponse, SecretVerificationRequest,
Expand All @@ -7,6 +9,8 @@ use crate::{error::Result, Client};

pub struct ClientPlatform<'a> {
pub(crate) client: &'a Client,
#[cfg(feature = "state")]
pub settings_repository: SettingsRepository,
}

impl<'a> ClientPlatform<'a> {
Expand All @@ -28,6 +32,10 @@ impl<'a> ClientPlatform<'a> {

impl<'a> Client {
pub fn platform(&'a self) -> ClientPlatform<'a> {
ClientPlatform { client: self }
ClientPlatform {
client: self,
#[cfg(feature = "state")]
settings_repository: SettingsRepository::new(self.internal.db.clone()),
}
}
}
5 changes: 4 additions & 1 deletion crates/bitwarden-core/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ pub mod client_platform;
mod generate_fingerprint;
mod get_user_api_key;
mod secret_verification_request;

#[cfg(feature = "state")]
mod settings_repository;
pub use generate_fingerprint::{FingerprintRequest, FingerprintResponse};
pub(crate) use get_user_api_key::get_user_api_key;
pub use get_user_api_key::UserApiKeyResponse;
pub use secret_verification_request::SecretVerificationRequest;
#[cfg(feature = "state")]
pub use settings_repository::SettingsRepository;
43 changes: 43 additions & 0 deletions crates/bitwarden-core/src/platform/settings_repository.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::sync::Arc;

use bitwarden_db::{params, Database, DatabaseError, DatabaseTrait};
use tokio::sync::Mutex;

pub struct SettingsRepository {
db: Arc<Mutex<Database>>,
}

impl SettingsRepository {
pub fn new(db: Arc<Mutex<Database>>) -> Self {
Self { db: db.clone() }
}

pub async fn get(&self, key: &str) -> Result<Option<String>, DatabaseError> {
let guard = self.db.lock().await;

let res = guard
.query_map(
"SELECT value FROM settings WHERE key = ?1",
[key],
|row| -> Result<String, _> { row.get(0) },
)
.await?
.first()
.map(|x| x.to_owned());

Ok(res)
}

pub async fn set(&self, key: &str, value: &str) -> Result<(), DatabaseError> {
let guard = self.db.lock().await;

guard
.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
params![key, value],
)
.await?;

Ok(())
}
}
13 changes: 12 additions & 1 deletion crates/bw/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,26 @@ repository.workspace = true
license-file.workspace = true

[dependencies]
bitwarden = { workspace = true, features = ["internal"] }
bat = { version = "0.24.0", features = [
"regex-onig",
], default-features = false }
bitwarden = { workspace = true, features = ["internal", "state"] }
bitwarden-cli = { workspace = true }
bitwarden-crypto = { workspace = true }
chrono = { version = "0.4.38", features = [
"clock",
"std",
], default-features = false }
clap = { version = "4.5.4", features = ["derive", "env"] }
comfy-table = "7.1.1"
color-eyre = "0.6.3"
env_logger = "0.11.1"
inquire = "0.7.0"
log = "0.4.20"
tokio = { version = "1.36.0", features = ["rt-multi-thread", "macros"] }
serde = "1.0.196"
serde_json = ">=1.0.96, <2"
serde_yaml = "0.9"

[dev-dependencies]
tempfile = "3.10.0"
Expand Down
7 changes: 7 additions & 0 deletions crates/bw/src/auth/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,13 @@ pub(crate) async fn login_api_key(
})
.await?;

let res = client
.vault()
.sync(&SyncRequest {
exclude_subdomains: Some(true),
})
.await?;

debug!("{:?}", result);

Ok(())
Expand Down
1 change: 1 addition & 0 deletions crates/bw/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub(crate) mod vault;
Loading
Loading