Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
61829b0
meta: add device sessions, password change and revoke queries
Skyfuller1303 Nov 3, 2026
862b167
api, proto, server: add account, password change and device routes
Skyfuller1303 Nov 3, 2026
6c9454c
server: sign devices out on password reset, add device revoke-all
Skyfuller1303 Nov 3, 2026
afc44ff
docs: describe device sessions, password change and migration 0007
Skyfuller1303 Nov 3, 2026
6811ec7
server: answer 401 to the long-poll and live socket of a signed-out d…
Skyfuller1303 Nov 3, 2026
8c891b3
meta, server: keep a password change atomic against revokes and races
Skyfuller1303 Nov 3, 2026
00f31da
server: look a long-polling device up again after the change set is read
Skyfuller1303 Nov 3, 2026
62e9151
meta: take the user's row first in every transaction that revokes or …
Skyfuller1303 Nov 3, 2026
3dd9f28
meta tests: let the failure test's check run more than once
Skyfuller1303 Nov 4, 2026
f69dab0
meta, server: lock the account first when a join, a pairing or a sign…
Skyfuller1303 Nov 4, 2026
31d92fd
meta: consume a join code only for the account it was found for
Skyfuller1303 Nov 4, 2026
e516a77
store: say what kind of storage a backend is
Skyfuller1303 Nov 4, 2026
876b181
proto: add the admin API's bodies and error codes
Skyfuller1303 Nov 4, 2026
4586bad
meta: add admin changes, reset codes, removal marks and quotas
Skyfuller1303 Nov 4, 2026
37b8be8
server: enforce the admin role and add the HTTP admin API
Skyfuller1303 Nov 4, 2026
282d04d
server: do not count a try the limiter refuses
Skyfuller1303 Nov 4, 2026
32e8d08
meta: refuse a sign-in checked before a disable and an enable
Skyfuller1303 Nov 4, 2026
39b8e35
proto: add the audit log's bodies
Skyfuller1303 Nov 4, 2026
be81aba
meta: write the security audit log, one event with each change
Skyfuller1303 Nov 4, 2026
d5485ef
server: add the audit routes, the [audit] config and the audit command
Skyfuller1303 Nov 4, 2026
7d80a6f
docs: describe the security audit log
Skyfuller1303 Nov 4, 2026
833e56a
server, docs: hide others' details in own activity, honour before_ms …
Skyfuller1303 Nov 4, 2026
c7b3874
agent: send client kind, platform and version on sign-in and join
Skyfuller1303 Nov 6, 2026
2b63673
Merge device-sessions: the agent sends its device details
Skyfuller1303 Nov 6, 2026
b2da75a
Merge admin-api: the agent sends its device details
Skyfuller1303 Nov 6, 2026
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
1 change: 1 addition & 0 deletions Cargo.lock

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

46 changes: 43 additions & 3 deletions apps/craft-cloud-agent/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,25 @@ pub fn check_compatible(info: &InfoResponse) -> Result<(), TransportError> {
Ok(())
}

/// The most bytes the server takes of a device's `platform` or `app_version`.
const MAX_DEVICE_DETAIL_BYTES: usize = 32;

/// What this agent says about itself when it signs in or joins: `agent`, the operating system and the crate's
/// version, for the account's device list (display only). The server takes at most 32 bytes without control
/// characters per field, so a longer value is cut at a character boundary rather than refused.
fn device_details() -> (Option<String>, Option<String>, Option<String>) {
fn limited(text: &str) -> String {
text.chars()
.filter(|c| !c.is_control())
.scan(0usize, |len, c| {
*len += c.len_utf8();
(*len <= MAX_DEVICE_DETAIL_BYTES).then_some(c)
})
.collect()
}
(Some("agent".to_owned()), Some(limited(std::env::consts::OS)), Some(limited(env!("CARGO_PKG_VERSION"))))
}

/// Signs in and creates a device. `Unauthorized` means a wrong username or password.
pub async fn login(server: &ServerUrl, username: &str, password: &str, device_name: &str) -> Result<LoginResponse, TransportError> {
login_over(&Reqwest::new(server)?, server, username, password, device_name).await
Expand All @@ -505,7 +524,15 @@ pub async fn login_over<C: Connection>(
password: &str,
device_name: &str,
) -> Result<LoginResponse, TransportError> {
let body = LoginRequest { username: username.to_owned(), password: password.to_owned(), device_name: device_name.to_owned() };
let (client_kind, platform, app_version) = device_details();
let body = LoginRequest {
username: username.to_owned(),
password: password.to_owned(),
device_name: device_name.to_owned(),
client_kind,
platform,
app_version,
};
let req = request(Method::POST, server.endpoint("auth/login"), None, 0).json(&body)?;
json(connection.send(req).await?, MAX_SMALL_JSON_BYTES).await
}
Expand Down Expand Up @@ -542,7 +569,15 @@ pub async fn join_over<C: Connection>(
device_name: &str,
password: Option<&str>,
) -> Result<LoginResponse, JoinError> {
let body = JoinRequest { code: code.to_owned(), device_name: device_name.to_owned(), password: password.map(str::to_owned) };
let (client_kind, platform, app_version) = device_details();
let body = JoinRequest {
code: code.to_owned(),
device_name: device_name.to_owned(),
password: password.map(str::to_owned),
client_kind,
platform,
app_version,
};
let req = request(Method::POST, server.endpoint("join"), None, 0).json(&body).map_err(JoinError::Transport)?;
let resp = connection.send(req).await.map_err(JoinError::Transport)?;
if resp.status.is_success() {
Expand Down Expand Up @@ -811,7 +846,12 @@ mod tests {
#[test]
fn requests_keep_bodies_and_tokens_out_of_debug_output() {
let server = ServerUrl::parse("http://127.0.0.1:1").unwrap();
let body = LoginRequest { username: "ana".into(), password: "correct horse battery".into(), device_name: "laptop".into() };
let body = LoginRequest {
username: "ana".into(),
password: "correct horse battery".into(),
device_name: "laptop".into(),
..LoginRequest::default()
};
let login = request(Method::POST, server.endpoint("auth/login"), None, 0).json(&body).unwrap();
let shown = format!("{login:?}");
assert!(!shown.contains("correct horse") && !shown.contains("ana"), "{shown}");
Expand Down
33 changes: 33 additions & 0 deletions apps/craft-cloud-agent/tests/end_to_end.rs
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,39 @@ async fn a_failed_pass_keeps_the_deletes_the_user_was_shown() {
assert_eq!((exit, summary.removed_remotely), (Exit::Done, 12), "{summary:?}");
}

/// The agent tells the server what it is when it signs in and when it joins, so the account's device list shows it.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn login_and_join_send_the_agents_device_details() {
use craft_cloud_agent::cli::JoinArgs;
use craft_cloud_proto::join::{Code, INVITE_CHARS, INVITE_TTL_MS, JoinString};
let server = server().await;
let ana = server.meta.user_by_name("ana").await.unwrap().unwrap();
async fn details(server: &Server, user: craft_cloud_meta::UserId, name: &str) -> (String, String, String) {
let devices = server.meta.list_devices(user).await.unwrap();
let device = devices.into_iter().find(|d| d.name == name).unwrap_or_else(|| panic!("no device {name}"));
(device.client.kind, device.client.platform, device.client.app_version)
}
let expected = ("agent".to_owned(), std::env::consts::OS.to_owned(), env!("CARGO_PKG_VERSION").to_owned());

let a = Agent::signed_in(&server, "desk").await;
assert_eq!(details(&server, ana.id, "desk").await, expected, "after login");
drop(a);

let invite = Code::generate(INVITE_CHARS).unwrap();
let now = i64::try_from(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis()).unwrap();
server.meta.create_invite("ana", &invite.hash(), now, INVITE_TTL_MS).await.unwrap();
let b = Agent::new();
let args = JoinArgs {
join: JoinString::new(server.url.clone(), invite).link(),
folder: Some(b.folder.clone()),
device_name: Some("laptop".into()),
adopt: false,
autostart: false,
};
cli::join(&b.data, &args, None, &mut Vec::new()).await.unwrap();
assert_eq!(details(&server, ana.id, "laptop").await, expected, "after join");
}

#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn login_makes_the_agent_folder_owner_only() {
Expand Down
28 changes: 26 additions & 2 deletions apps/craft-cloud-desktop/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1105,8 +1105,32 @@ pub(crate) mod tests {
let Screen::SignedIn(o) = &m.screen else { panic!() };
assert_eq!(o.status.account.as_deref(), Some("fabio"));
let devices = vec![
DeviceInfo { id: DeviceId::generate(), name: "lptp1".into(), created_ms: 1, last_used_ms: 2, revoked: false, current: true },
DeviceInfo { id: DeviceId::generate(), name: "BEAST".into(), created_ms: 1, last_used_ms: 3, revoked: false, current: false },
DeviceInfo {
id: DeviceId::generate(),
name: "lptp1".into(),
created_ms: 1,
last_used_ms: 2,
revoked: false,
current: true,
client_kind: String::new(),
platform: String::new(),
app_version: String::new(),
revoked_ms: None,
revoke_reason: None,
},
DeviceInfo {
id: DeviceId::generate(),
name: "BEAST".into(),
created_ms: 1,
last_used_ms: 3,
revoked: false,
current: false,
client_kind: String::new(),
platform: String::new(),
app_version: String::new(),
revoked_ms: None,
revoke_reason: None,
},
];
m.update(Event::Devices(Ok(devices.clone())));
// This computer can't be removed from here; another one can, once at a time.
Expand Down
19 changes: 18 additions & 1 deletion apps/craft-cloud-desktop/src/ui/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,31 @@ fn after(agent: &FakeAgent, events: Vec<Event>) -> Model {

fn devices() -> Vec<DeviceInfo> {
vec![
DeviceInfo { id: DeviceId::generate(), name: "lptp1".into(), created_ms: 0, last_used_ms: NOW - 5_000, revoked: false, current: true },
DeviceInfo {
id: DeviceId::generate(),
name: "lptp1".into(),
created_ms: 0,
last_used_ms: NOW - 5_000,
revoked: false,
current: true,
client_kind: String::new(),
platform: String::new(),
app_version: String::new(),
revoked_ms: None,
revoke_reason: None,
},
DeviceInfo {
id: DeviceId::generate(),
name: "BEAST".into(),
created_ms: 0,
last_used_ms: NOW - 3 * 3_600_000,
revoked: false,
current: false,
client_kind: String::new(),
platform: String::new(),
app_version: String::new(),
revoked_ms: None,
revoke_reason: None,
},
]
}
Expand Down
3 changes: 2 additions & 1 deletion apps/craft-cloud-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ clap.workspace = true
craft-cloud-meta.workspace = true
craft-cloud-proto.workspace = true
craft-cloud-store.workspace = true
# The audit export's body is a stream of pages.
futures-util.workspace = true
getrandom.workspace = true
serde.workspace = true
serde_json.workspace = true
Expand All @@ -34,7 +36,6 @@ uuid.workspace = true
[dev-dependencies]
reqwest.workspace = true
tokio-tungstenite.workspace = true
futures-util.workspace = true
serde_json.workspace = true
sqlx.workspace = true
tempfile.workspace = true
Expand Down
125 changes: 125 additions & 0 deletions apps/craft-cloud-server/src/account.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//! The signed-in account: `GET /api/v1/account`, `POST /api/v1/account/password`, and the device routes that change
//! a device (`PATCH /api/v1/devices/{id}`, `POST /api/v1/devices/revoke-others`).
//!
//! - **A wrong current password is `403 wrong_password`, never 401**: on a signed-in route the agent reads every 401
//! as "this device was revoked" and signs out. The same holds for every later route that asks for a password.
//! - **Changing the password** reads the body (at most [`TINY_JSON_BYTES`]), counts the try against the account
//! ([`PASSWORD_CHANGES_PER_USER`] in 15 minutes, wrong passwords included), takes one of the server-wide
//! password-check slots (every slot busy is `429 rate_limited` and the try is given back), checks the current
//! password and the new one's rules, and hashes the new one, all in that one slot. Then one transaction sets the
//! hash, revokes every other device and deletes the account's open invite and pairings
//! ([`craft_cloud_meta::Meta::change_password`]); afterwards each revoked device's live connections end at once.
//! The device that asked stays signed in.
//! - **Nothing secret is logged**: not a password, a hash or a token. The count of revoked devices is logged at
//! `info`, the username at most at `debug`.

use std::sync::Arc;

use axum::Json;
use axum::extract::rejection::PathRejection;
use axum::extract::{Extension, Path, Request, State};
use axum::http::StatusCode;
use craft_cloud_meta::{DeviceAuth, RevokeReason};
use craft_cloud_proto::DeviceId;
use craft_cloud_proto::api::{AccountInfo, ChangePasswordRequest, DeviceInfo, RenameDeviceRequest, RevokedOthers, codes};

use crate::api::{PASSWORD_RETRY_SECS, TINY_JSON_BYTES, device_info, read_json};
use crate::auth::{MAX_PASSWORD_BYTES, check_password_rules, hash_password, verify_password};
use crate::error::ApiError;
use crate::state::AppState;

/// Password change tries one account may make in [`AppState::password_changes`]'s window (15 minutes).
pub const PASSWORD_CHANGES_PER_USER: u32 = 5;

type Shared = Arc<AppState>;

/// `403 wrong_password`: the current password was wrong. Never 401, see the module's notes.
pub(crate) fn wrong_password() -> ApiError {
ApiError::new(StatusCode::FORBIDDEN, codes::WRONG_PASSWORD, "the current password is wrong")
}

/// `GET /api/v1/account`.
pub async fn get_account(State(state): State<Shared>, Extension(auth): Extension<DeviceAuth>) -> Result<Json<AccountInfo>, ApiError> {
let account = state.meta.account(auth.user).await?;
Ok(Json(AccountInfo {
user_id: account.id.0,
username: account.username,
role: account.role.as_str().to_owned(),
created_ms: account.created_ms,
password_changed_ms: account.password_changed_ms,
// Two-factor sign-in isn't part of the server yet.
two_factor_enabled: false,
}))
}

/// `POST /api/v1/account/password`: `204` once the password is changed and the account's other devices are signed out.
pub async fn change_password(State(state): State<Shared>, Extension(auth): Extension<DeviceAuth>, request: Request) -> Result<StatusCode, ApiError> {
let req: ChangePasswordRequest = read_json(&state, request, TINY_JSON_BYTES).await?;
if req.current_password.len() > MAX_PASSWORD_BYTES || req.new_password.len() > MAX_PASSWORD_BYTES {
return Err(ApiError::invalid("passwords are at most 1024 bytes"));
}
// tokio's clock: the system's monotonic clock in the server, the simulated one in a simulation.
let now = tokio::time::Instant::now().into_std();
let key = format!("user:{}", auth.username);
let Some(counted) = state.password_changes.count(&key, PASSWORD_CHANGES_PER_USER, now) else {
return Err(ApiError::rate_limited("too many password change attempts; wait a few minutes", None));
};
// Each check costs 19 MiB and real CPU time (see the sign-in): all slots busy is told to come back, not queued,
// and costs the account no try, since nothing was checked.
let Ok(permit) = state.password_checks.clone().try_acquire_owned() else {
state.password_changes.refund(&key, counted);
return Err(ApiError::rate_limited("the server is busy checking other passwords; try again in a moment", Some(PASSWORD_RETRY_SECS)));
};
let user = state.meta.user_by_name(&auth.username).await?.ok_or_else(ApiError::unauthorized)?;
let current_hash = user.password_hash.clone();
let ChangePasswordRequest { current_password, new_password } = req;
let new_hash = tokio::task::spawn_blocking(move || {
let _permit = permit;
if !verify_password(&current_password, &current_hash) {
return Err(wrong_password());
}
check_password_rules(&new_password).map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, codes::WEAK_PASSWORD, e.message))?;
if new_password == current_password {
return Err(ApiError::new(StatusCode::BAD_REQUEST, codes::WEAK_PASSWORD, "the new password must differ from the current one"));
}
hash_password(&new_password)
})
.await
.map_err(|e| {
tracing::error!(error = %e, "password change task failed");
ApiError::internal()
})??;
let revoked = state.meta.change_password(auth.user, &user.password_hash, &new_hash, auth.device, state.now_ms()).await?;
for device in &revoked {
state.live.revoke(*device);
}
tracing::debug!(user = %auth.username, "password changed");
tracing::info!(device = %auth.device, revoked = revoked.len(), "password changed");
Ok(StatusCode::NO_CONTENT)
}

/// `PATCH /api/v1/devices/{id}`: renames one of the account's own devices that isn't revoked. Anything else is
/// `404 not_found`, so the answer never says whether another account has the device.
pub async fn rename_device(
State(state): State<Shared>,
Extension(auth): Extension<DeviceAuth>,
id: Result<Path<DeviceId>, PathRejection>,
request: Request,
) -> Result<Json<DeviceInfo>, ApiError> {
let Path(id) = id?;
let req: RenameDeviceRequest = read_json(&state, request, TINY_JSON_BYTES).await?;
crate::api::check_device_name(&req.name)?;
let device = state.meta.rename_device(auth.user, id, &req.name).await?;
Ok(Json(device_info(device, auth.device)))
}

/// `POST /api/v1/devices/revoke-others`: signs out every other device of the account.
pub async fn revoke_others(State(state): State<Shared>, Extension(auth): Extension<DeviceAuth>) -> Result<Json<RevokedOthers>, ApiError> {
let revoked = state.meta.revoke_other_devices(auth.user, auth.device, RevokeReason::Others, state.now_ms()).await?;
// Their live connections end now, not at their next request.
for device in &revoked {
state.live.revoke(*device);
}
tracing::info!(device = %auth.device, revoked = revoked.len(), "other devices signed out");
Ok(Json(RevokedOthers { revoked: u32::try_from(revoked.len()).unwrap_or(u32::MAX) }))
}
Loading