Milestone 3: the hub

lunehub serves accounts, invites, pairing codes, memberships, devices
and vaults as plain bare repos (SPEC §8), checks device key and role on
every Git request, refuses secrets in a pre-receive hook (P3) and logs
every access change. Ships as one container (Dockerfile, compose.yaml).

lunesync gains join, login, pair, vault new/upload, invite, grant,
members and hub log; `run` picks up new vaults and roles from the hub.
Read members' edits stay local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 00:47:54 +07:00
parent 62bc3db416
commit 2b4ca84a6b
23 changed files with 2578 additions and 58 deletions

20
hub/Cargo.toml Normal file
View File

@@ -0,0 +1,20 @@
[package]
name = "lunehub"
version = "0.1.0"
edition = "2024"
[dependencies]
anyhow = "1.0.104"
axum = "0.8.9"
base64 = "0.23.1"
chrono = "0.4.45"
getrandom = "0.4.3"
lune-core = { version = "0.1.0", path = "../core" }
rusqlite = { version = "0.41.0", features = ["bundled"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
sha2 = "0.11.1"
tokio = { version = "1.54.1", features = ["full"] }
[dev-dependencies]
tempfile = "3.27.0"

400
hub/src/api.rs Normal file
View File

@@ -0,0 +1,400 @@
//! The hub's JSON API: joining, pairing, vaults, invites, grants, members and the access log.
use crate::db::{self, Caller};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use base64::Engine;
use rusqlite::{Connection, OptionalExtension, params};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
pub struct Hub {
pub db: Mutex<Connection>,
pub data: PathBuf,
pub url: String,
}
pub type Shared = Arc<Hub>;
impl Hub {
pub fn repo_path(&self, vault_id: i64) -> PathBuf {
self.data.join("repos").join(format!("{vault_id}.git"))
}
pub fn git_url(&self, vault_id: i64) -> String {
format!("{}/git/{vault_id}.git", self.url)
}
}
/// An error with the plain-words message the CLI shows.
pub struct ApiError(pub StatusCode, pub String);
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(self.0, Json(json!({ "error": self.1 }))).into_response()
}
}
impl From<anyhow::Error> for ApiError {
fn from(e: anyhow::Error) -> Self {
eprintln!("hub error: {e:#}");
ApiError(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong on the hub".into())
}
}
impl From<rusqlite::Error> for ApiError {
fn from(e: rusqlite::Error) -> Self {
anyhow::Error::from(e).into()
}
}
type ApiResult = Result<Json<Value>, ApiError>;
fn bad(msg: impl Into<String>) -> ApiError {
ApiError(StatusCode::BAD_REQUEST, msg.into())
}
fn denied(msg: impl Into<String>) -> ApiError {
ApiError(StatusCode::FORBIDDEN, msg.into())
}
/// Device id and key from a Basic `Authorization` header.
pub fn credentials(headers: &HeaderMap) -> Option<(String, String)> {
let value = headers.get("authorization")?.to_str().ok()?;
let encoded = value.strip_prefix("Basic ")?;
let raw = base64::engine::general_purpose::STANDARD.decode(encoded).ok()?;
let (id, key) = std::str::from_utf8(&raw).ok()?.split_once(':')?;
Some((id.to_string(), key.to_string()))
}
pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError> {
let unknown = || ApiError(StatusCode::UNAUTHORIZED, "this device isn't signed in to the hub".into());
let (id, key) = credentials(headers).ok_or_else(unknown)?;
let conn = hub.db.lock().unwrap();
db::caller(&conn, &id, &key)?.ok_or_else(unknown)
}
const ROLES: [&str; 3] = ["read", "edit", "manage"];
fn check_label(label: &str) -> Result<String, ApiError> {
let label = label.trim();
if label.is_empty() || label.len() > 40 {
return Err(bad("a device label needs 1–40 characters"));
}
Ok(label.to_string())
}
/// Owners can manage every vault; others need the Manage role on it.
fn can_manage(conn: &Connection, caller: &Caller, vault_id: i64) -> Result<bool, ApiError> {
Ok(caller.owner || db::role(conn, caller.account_id, vault_id)?.as_deref() == Some("manage"))
}
fn welcome(person: &str, device_id: String, key: String) -> ApiResult {
Ok(Json(json!({ "person": person, "device_id": device_id, "key": key })))
}
#[derive(Deserialize)]
pub struct JoinReq {
token: String,
device_label: String,
}
pub async fn join(State(hub): State<Shared>, Json(req): Json<JoinReq>) -> ApiResult {
let label = check_label(&req.device_label)?;
let mut conn = hub.db.lock().unwrap();
let tx = conn.transaction()?;
let invite: Option<(String, bool, String, i64, Option<i64>)> = tx
.query_row(
"SELECT person, owner, grants, expires, used FROM invites WHERE token_hash = ?1",
[db::hash(&req.token)],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.optional()?;
let Some((person, owner, grants, expires, used)) = invite else {
return Err(denied("that invite link isn't valid"));
};
if used.is_some() {
return Err(denied("that invite link was already used"));
}
if expires < db::now() {
return Err(denied("that invite link has expired — ask for a new one"));
}
let taken: bool = tx.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [&person], |r| r.get(0))?;
if taken {
return Err(denied(format!("{person} already has an account — pair a device instead")));
}
tx.execute("INSERT INTO accounts (name, owner, created) VALUES (?1, ?2, ?3)", params![person, owner, db::now()])?;
let account_id = tx.last_insert_rowid();
let grants: Vec<(i64, String)> = serde_json::from_str(&grants).map_err(anyhow::Error::from)?;
let mut granted = vec![];
for (vault_id, role) in &grants {
db::grant(&tx, account_id, *vault_id, role)?;
let name: Option<String> = tx.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).optional()?;
granted.push(format!("{}: {role}", name.unwrap_or_default()));
}
tx.execute("UPDATE invites SET used = ?1 WHERE token_hash = ?2", params![db::now(), db::hash(&req.token)])?;
let (device_id, key) = db::new_device(&tx, account_id, &label)?;
let who = format!("{person} ({label})");
let what = if owner { "as team owner".to_string() } else if granted.is_empty() { "with no vaults".into() } else { granted.join(", ") };
db::log(&tx, &who, "joined", &format!("accepted the invite {what}"))?;
db::log(&tx, &who, "device added", &format!("{label} (first device)"))?;
tx.commit()?;
welcome(&person, device_id, key)
}
#[derive(Deserialize)]
pub struct LoginReq {
code: String,
device_label: String,
}
pub async fn login(State(hub): State<Shared>, Json(req): Json<LoginReq>) -> ApiResult {
let label = check_label(&req.device_label)?;
let code: String = req.code.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_uppercase();
let conn = hub.db.lock().unwrap();
let found: Option<(i64, i64, Option<i64>)> = conn
.query_row(
"SELECT account_id, expires, used FROM pair_codes WHERE code_hash = ?1",
[db::hash(&code)],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let account_id = match found {
Some((a, expires, None)) if expires >= db::now() => a,
Some((_, _, Some(_))) => return Err(denied("that code was already used — make a new one with `lunesync pair`")),
Some(_) => return Err(denied("that code has expired — make a new one with `lunesync pair`")),
None => return Err(denied("that code isn't valid")),
};
conn.execute("UPDATE pair_codes SET used = ?1 WHERE code_hash = ?2", params![db::now(), db::hash(&code)])?;
let person: String = conn.query_row("SELECT name FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?;
let (device_id, key) = db::new_device(&conn, account_id, &label)?;
db::log(&conn, &format!("{person} ({label})"), "device added", &format!("{label} paired with a code"))?;
welcome(&person, device_id, key)
}
pub async fn pair(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let code = db::token(8);
let conn = hub.db.lock().unwrap();
conn.execute(
"INSERT INTO pair_codes (code_hash, account_id, expires) VALUES (?1, ?2, ?3)",
params![db::hash(&code), caller.account_id, db::now() + 600],
)?;
db::log(&conn, &caller.who(), "pairing code", "made a code to add a device")?;
Ok(Json(json!({ "code": format!("{}-{}", &code[..4], &code[4..]) })))
}
pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT v.id, v.name, m.role FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
)?;
let vaults: Vec<Value> = stmt
.query_map([caller.account_id], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) }))
.collect();
Ok(Json(json!({
"person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults
})))
}
#[derive(Deserialize)]
pub struct LabelReq {
label: String,
}
pub async fn label(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<LabelReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let label = check_label(&req.label)?;
let conn = hub.db.lock().unwrap();
conn.execute("UPDATE devices SET label = ?1 WHERE id = ?2", params![label, caller.device_id])?;
db::log(&conn, &caller.who(), "device renamed", &format!("{} → {label}", caller.device_label))?;
Ok(Json(json!({})))
}
#[derive(Deserialize)]
pub struct VaultReq {
name: String,
}
pub async fn create_vault(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<VaultReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
if !caller.owner {
return Err(denied("only the team owner can create vaults"));
}
let name = req.name.trim();
let ok = !name.is_empty()
&& name.len() <= 60
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_alphanumeric() || " _-.".contains(c));
if !ok {
return Err(bad("vault names use letters, numbers, spaces, - _ . (up to 60)"));
}
let conn = hub.db.lock().unwrap();
if db::vault_id(&conn, name)?.is_some() {
return Err(ApiError(StatusCode::CONFLICT, format!("there's already a vault named {name}")));
}
conn.execute("INSERT INTO vaults (name, created) VALUES (?1, ?2)", params![name, db::now()])?;
let id = conn.last_insert_rowid();
crate::git::create_repo(&hub.repo_path(id))?;
db::grant(&conn, caller.account_id, id, "manage")?;
db::log(&conn, &caller.who(), "vault created", name)?;
Ok(Json(json!({ "id": id, "name": name, "role": "manage", "git_url": hub.git_url(id) })))
}
#[derive(Deserialize)]
pub struct Grant {
vault: String,
role: String,
}
#[derive(Deserialize)]
pub struct InviteReq {
person: String,
grants: Vec<Grant>,
}
/// Resolves (vault name, role) pairs the caller may hand out.
fn allowed_grants(conn: &Connection, caller: &Caller, grants: &[Grant]) -> Result<Vec<(i64, String, String)>, ApiError> {
let mut out = vec![];
for g in grants {
let role = g.role.to_lowercase();
if !ROLES.contains(&role.as_str()) {
return Err(bad(format!("roles are read, edit or manage (not \"{}\")", g.role)));
}
let (id, name) = db::vault_id(conn, &g.vault)?.ok_or_else(|| bad(format!("no vault named {}", g.vault)))?;
if !can_manage(conn, caller, id)? {
return Err(denied(format!("you need Manage on {name} to give access to it")));
}
out.push((id, name, role));
}
Ok(out)
}
pub async fn invite(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<InviteReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let person = req.person.trim();
if person.is_empty() || person.len() > 60 {
return Err(bad("a person's name needs 1–60 characters"));
}
let conn = hub.db.lock().unwrap();
let grants = allowed_grants(&conn, &caller, &req.grants)?;
if grants.is_empty() && !caller.owner {
return Err(bad("say which vault to share, e.g. --vault DevOps:edit"));
}
let taken: bool = conn.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [person], |r| r.get(0))?;
if taken {
return Err(bad(format!("{person} already has an account — use `lunesync grant` instead")));
}
// One invite per person: a new one replaces any unused older one.
conn.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [person])?;
let token = db::token(32);
let ids: Vec<(i64, &str)> = grants.iter().map(|(id, _, role)| (*id, role.as_str())).collect();
conn.execute(
"INSERT INTO invites (token_hash, person, owner, grants, created_by, expires) VALUES (?1, ?2, 0, ?3, ?4, ?5)",
params![db::hash(&token), person, serde_json::to_string(&ids).unwrap(), caller.who(), db::now() + 7 * 86400],
)?;
let what: Vec<String> = grants.iter().map(|(_, n, r)| format!("{n}: {r}")).collect();
db::log(&conn, &caller.who(), "invite created", &format!("for {person} ({})", what.join(", ")))?;
Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) })))
}
#[derive(Deserialize)]
pub struct GrantReq {
person: String,
vault: String,
role: String,
}
pub async fn grant(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<GrantReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let g = allowed_grants(&conn, &caller, &[Grant { vault: req.vault, role: req.role }])?.remove(0);
let (account_id, person): (i64, String) = conn
.query_row("SELECT id, name FROM accounts WHERE name = ?1", [req.person.trim()], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?
.ok_or_else(|| bad(format!("nobody named {} has joined yet — invite them first", req.person.trim())))?;
let before = db::role(&conn, account_id, g.0)?;
db::grant(&conn, account_id, g.0, &g.2)?;
let detail = match before {
Some(old) => format!("{person} on {}: {old} → {}", g.1, g.2),
None => format!("{person} on {}: {}", g.1, g.2),
};
db::log(&conn, &caller.who(), "access granted", &detail)?;
Ok(Json(json!({})))
}
#[derive(Deserialize)]
pub struct MembersReq {
vault: String,
}
pub async fn members(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<MembersReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let (id, name) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
if !caller.owner && db::role(&conn, caller.account_id, id)?.is_none() {
return Err(denied(format!("you're not a member of {name}")));
}
let mut stmt = conn.prepare(
"SELECT a.id, a.name, m.role FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.vault_id = ?1 ORDER BY a.name",
)?;
let rows: Vec<(i64, String, String)> =
stmt.query_map([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
let mut out = vec![];
for (account_id, person, role) in rows {
let mut d = conn.prepare("SELECT label FROM devices WHERE account_id = ?1 ORDER BY created")?;
let devices: Vec<String> = d.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?;
out.push(json!({ "person": person, "role": role, "devices": devices }));
}
Ok(Json(Value::Array(out)))
}
#[derive(Deserialize)]
pub struct LogQuery {
count: Option<i64>,
}
pub async fn log(State(hub): State<Shared>, headers: HeaderMap, Query(q): Query<LogQuery>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
if !caller.owner {
return Err(denied("only the team owner can read the access log"));
}
let conn = hub.db.lock().unwrap();
let mut stmt = conn.prepare("SELECT at, actor, action, detail FROM log ORDER BY id DESC LIMIT ?1")?;
let rows: Vec<Value> = stmt
.query_map([q.count.unwrap_or(30)], |r| {
Ok(json!({ "at": r.get::<_, i64>(0)?, "actor": r.get::<_, String>(1)?, "action": r.get::<_, String>(2)?, "detail": r.get::<_, String>(3)? }))
})?
.collect::<Result<_, _>>()?;
Ok(Json(Value::Array(rows)))
}
#[derive(Deserialize)]
pub struct NotSecretReq {
vault_id: i64,
fingerprint: String,
}
pub async fn not_secret(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<NotSecretReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let role = db::role(&conn, caller.account_id, req.vault_id)?;
if !role.as_deref().is_some_and(|r| r == "edit" || r == "manage") {
return Err(denied("you need Edit on that vault"));
}
if req.fingerprint.len() != 40 || !req.fingerprint.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(bad("that fingerprint doesn't look right"));
}
conn.execute("INSERT OR IGNORE INTO not_secrets (vault_id, fingerprint) VALUES (?1, ?2)", params![req.vault_id, req.fingerprint])?;
let name: String = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [req.vault_id], |r| r.get(0))?;
db::log(&conn, &caller.who(), "not a secret", &format!("a line in {name} was marked as not a secret"))?;
Ok(Json(json!({})))
}

173
hub/src/db.rs Normal file
View File

@@ -0,0 +1,173 @@
//! The hub's records: accounts, devices, vaults, memberships, invites, pairing codes and the access log.
use anyhow::Result;
use rusqlite::{Connection, OptionalExtension, params};
use sha2::{Digest, Sha256};
use std::path::Path;
const SCHEMA: &str = "
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
owner INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS devices (
id TEXT PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES accounts(id),
label TEXT NOT NULL,
key_hash TEXT NOT NULL,
created INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS vaults (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
created INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS memberships (
account_id INTEGER NOT NULL REFERENCES accounts(id),
vault_id INTEGER NOT NULL REFERENCES vaults(id),
role TEXT NOT NULL,
PRIMARY KEY (account_id, vault_id)
);
CREATE TABLE IF NOT EXISTS invites (
token_hash TEXT PRIMARY KEY,
person TEXT NOT NULL,
owner INTEGER NOT NULL DEFAULT 0,
grants TEXT NOT NULL,
created_by TEXT NOT NULL,
expires INTEGER NOT NULL,
used INTEGER
);
CREATE TABLE IF NOT EXISTS pair_codes (
code_hash TEXT PRIMARY KEY,
account_id INTEGER NOT NULL,
expires INTEGER NOT NULL,
used INTEGER
);
CREATE TABLE IF NOT EXISTS not_secrets (
vault_id INTEGER NOT NULL,
fingerprint TEXT NOT NULL,
PRIMARY KEY (vault_id, fingerprint)
);
CREATE TABLE IF NOT EXISTS log (
id INTEGER PRIMARY KEY,
at INTEGER NOT NULL,
actor TEXT NOT NULL,
action TEXT NOT NULL,
detail TEXT NOT NULL
);
";
pub fn open(data: &Path) -> Result<Connection> {
let conn = Connection::open(data.join("hub.sqlite"))?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
conn.execute_batch(SCHEMA)?;
Ok(conn)
}
pub fn now() -> i64 {
chrono::Utc::now().timestamp()
}
pub fn hash(secret: &str) -> String {
Sha256::digest(secret.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
}
/// Random token from an alphabet without look-alike characters.
pub fn token(len: usize) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let mut bytes = vec![0u8; len];
getrandom::fill(&mut bytes).expect("no randomness available");
bytes.iter().map(|b| ALPHABET[*b as usize % ALPHABET.len()] as char).collect()
}
pub fn log(conn: &Connection, actor: &str, action: &str, detail: &str) -> Result<()> {
conn.execute(
"INSERT INTO log (at, actor, action, detail) VALUES (?1, ?2, ?3, ?4)",
params![now(), actor, action, detail],
)?;
Ok(())
}
/// The device signing a request, with its person.
#[derive(Debug, Clone)]
pub struct Caller {
pub device_id: String,
pub device_label: String,
pub account_id: i64,
pub person: String,
pub owner: bool,
}
impl Caller {
/// "Sen (Codex)" — how the access log names whoever did something.
pub fn who(&self) -> String {
format!("{} ({})", self.person, self.device_label)
}
}
pub fn caller(conn: &Connection, device_id: &str, key: &str) -> Result<Option<Caller>> {
Ok(conn
.query_row(
"SELECT d.id, d.label, a.id, a.name, a.owner FROM devices d JOIN accounts a ON a.id = d.account_id
WHERE d.id = ?1 AND d.key_hash = ?2",
params![device_id, hash(key)],
|r| {
Ok(Caller { device_id: r.get(0)?, device_label: r.get(1)?, account_id: r.get(2)?, person: r.get(3)?, owner: r.get(4)? })
},
)
.optional()?)
}
/// Creates a device for `account_id`; returns (device id, key). Only the key's hash is kept.
pub fn new_device(conn: &Connection, account_id: i64, label: &str) -> Result<(String, String)> {
let id = format!("dev_{}", token(10).to_lowercase());
let key = token(40);
conn.execute(
"INSERT INTO devices (id, account_id, label, key_hash, created) VALUES (?1, ?2, ?3, ?4, ?5)",
params![id, account_id, label, hash(&key), now()],
)?;
Ok((id, key))
}
pub fn vault_id(conn: &Connection, name: &str) -> Result<Option<(i64, String)>> {
Ok(conn.query_row("SELECT id, name FROM vaults WHERE name = ?1", [name], |r| Ok((r.get(0)?, r.get(1)?))).optional()?)
}
pub fn role(conn: &Connection, account_id: i64, vault_id: i64) -> Result<Option<String>> {
Ok(conn
.query_row("SELECT role FROM memberships WHERE account_id = ?1 AND vault_id = ?2", [account_id, vault_id], |r| r.get(0))
.optional()?)
}
pub fn grant(conn: &Connection, account_id: i64, vault_id: i64, role: &str) -> Result<()> {
conn.execute(
"INSERT INTO memberships (account_id, vault_id, role) VALUES (?1, ?2, ?3)
ON CONFLICT (account_id, vault_id) DO UPDATE SET role = excluded.role",
params![account_id, vault_id, role],
)?;
Ok(())
}
pub fn not_secrets(conn: &Connection, vault_id: i64) -> Result<std::collections::HashSet<String>> {
let mut stmt = conn.prepare("SELECT fingerprint FROM not_secrets WHERE vault_id = ?1")?;
let rows = stmt.query_map([vault_id], |r| r.get(0))?;
Ok(rows.collect::<Result<_, _>>()?)
}
/// If nobody has an account yet, creates a fresh one-time owner invite (older unused ones stop working).
pub fn owner_invite(conn: &Connection, person: &str) -> Result<Option<String>> {
let accounts: i64 = conn.query_row("SELECT COUNT(*) FROM accounts", [], |r| r.get(0))?;
if accounts > 0 {
return Ok(None);
}
conn.execute("DELETE FROM invites WHERE owner = 1 AND used IS NULL", [])?;
let token = token(32);
conn.execute(
"INSERT INTO invites (token_hash, person, owner, grants, created_by, expires) VALUES (?1, ?2, 1, '[]', 'hub', ?3)",
params![hash(&token), person, now() + 7 * 86400],
)?;
Ok(Some(token))
}

146
hub/src/git.rs Normal file
View File

@@ -0,0 +1,146 @@
//! Vaults over Git's HTTP protocol: check the device key and role, then hand off to `git http-backend`.
use crate::api::{ApiError, Shared, credentials};
use crate::db;
use anyhow::{Context, Result};
use axum::body::{Body, Bytes};
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use std::collections::HashMap;
use std::path::Path as FsPath;
use std::process::Stdio;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
pub fn create_repo(path: &FsPath) -> Result<()> {
let repo = lune_core::git2::Repository::init_bare(path).with_context(|| format!("can't create {}", path.display()))?;
repo.set_head("refs/heads/main")?;
install_hook(path)
}
/// Every incoming change goes through the hub's secret check before it's accepted (P3).
pub fn install_hook(repo: &FsPath) -> Result<()> {
let exe = std::env::current_exe()?;
let hook = repo.join("hooks/pre-receive");
std::fs::create_dir_all(hook.parent().unwrap())?;
std::fs::write(&hook, format!("#!/bin/sh\nexec \"{}\" hook pre-receive\n", exe.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755))?;
}
Ok(())
}
fn ask_for_key() -> Response {
(StatusCode::UNAUTHORIZED, [("WWW-Authenticate", "Basic realm=\"lune\"")], "sign in with a device key").into_response()
}
pub async fn serve(
State(hub): State<Shared>,
Path((repo, rest)): Path<(String, String)>,
Query(query): Query<HashMap<String, String>>,
method: Method,
headers: HeaderMap,
body: Bytes,
) -> Response {
match handle(hub, repo, rest, query, method, headers, body).await {
Ok(r) => r,
Err(e) => e.into_response(),
}
}
async fn handle(
hub: Shared,
repo: String,
rest: String,
query: HashMap<String, String>,
method: Method,
headers: HeaderMap,
body: Bytes,
) -> Result<Response, ApiError> {
let not_found = || ApiError(StatusCode::NOT_FOUND, "no such vault".into());
let vault_id: i64 = repo.strip_suffix(".git").and_then(|s| s.parse().ok()).ok_or_else(not_found)?;
let service = match rest.as_str() {
"info/refs" => query.get("service").cloned().unwrap_or_default(),
"git-upload-pack" | "git-receive-pack" => rest.clone(),
_ => return Err(not_found()),
};
let writing = match service.as_str() {
"git-upload-pack" => false,
"git-receive-pack" => true,
_ => return Err(ApiError(StatusCode::FORBIDDEN, "only the smart Git protocol is served".into())),
};
let Some((id, key)) = credentials(&headers) else { return Ok(ask_for_key()) };
let (caller, role, vault_name) = {
let conn = hub.db.lock().unwrap();
let Some(caller) = db::caller(&conn, &id, &key)? else { return Ok(ask_for_key()) };
let role = db::role(&conn, caller.account_id, vault_id)?;
let name: Option<String> =
conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).ok();
(caller, role, name)
};
let vault_name = vault_name.ok_or_else(not_found)?;
let Some(role) = role else {
return Err(ApiError(StatusCode::FORBIDDEN, format!("{} isn't a member of {vault_name}", caller.person)));
};
if writing && role == "read" {
let conn = hub.db.lock().unwrap();
db::log(&conn, &caller.who(), "change refused", &format!("{vault_name}: read access only"))?;
return Err(ApiError(StatusCode::FORBIDDEN, format!("{} has read access to {vault_name}", caller.person)));
}
let mut cmd = tokio::process::Command::new("git");
cmd.arg("http-backend")
.env_clear()
.env("PATH", std::env::var("PATH").unwrap_or_default())
.env("GIT_PROJECT_ROOT", hub.data.join("repos"))
.env("GIT_HTTP_EXPORT_ALL", "1")
.env("PATH_INFO", format!("/{repo}/{rest}"))
.env("REQUEST_METHOD", method.as_str())
.env("QUERY_STRING", query.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&"))
.env("CONTENT_LENGTH", body.len().to_string())
.env("REMOTE_USER", &caller.device_id)
.env("REMOTE_ADDR", "127.0.0.1")
.env("LUNE_HUB_DATA", &hub.data)
.env("LUNE_ACTOR", caller.who())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
for (header, var) in [("content-type", "CONTENT_TYPE"), ("content-encoding", "HTTP_CONTENT_ENCODING"), ("git-protocol", "GIT_PROTOCOL")] {
if let Some(v) = headers.get(header).and_then(|v| v.to_str().ok()) {
cmd.env(var, v);
}
}
let mut child = cmd.spawn().map_err(|e| anyhow::anyhow!("can't start git http-backend: {e}"))?;
let mut stdin = child.stdin.take().unwrap();
let writer = tokio::spawn(async move {
let _ = stdin.write_all(&body).await;
});
let mut out = vec![];
child.stdout.take().unwrap().read_to_end(&mut out).await.map_err(anyhow::Error::from)?;
let _ = writer.await;
let _ = child.wait().await;
Ok(cgi_response(&out))
}
/// Turns CGI output (headers, blank line, body) into an HTTP response.
fn cgi_response(out: &[u8]) -> Response {
let split = out.windows(4).position(|w| w == b"\r\n\r\n").map(|i| (i, 4)).or_else(|| out.windows(2).position(|w| w == b"\n\n").map(|i| (i, 2)));
let Some((end, sep)) = split else {
return (StatusCode::BAD_GATEWAY, "git gave no answer").into_response();
};
let mut status = StatusCode::OK;
let mut builder = Response::builder();
for line in String::from_utf8_lossy(&out[..end]).lines() {
let Some((k, v)) = line.split_once(':') else { continue };
let v = v.trim();
if k.eq_ignore_ascii_case("status") {
status = v.split_whitespace().next().and_then(|c| c.parse().ok()).and_then(|c| StatusCode::from_u16(c).ok()).unwrap_or(status);
} else {
builder = builder.header(k.trim(), v);
}
}
builder.status(status).body(Body::from(out[end + sep..].to_vec())).unwrap_or_else(|_| StatusCode::BAD_GATEWAY.into_response())
}

86
hub/src/hook.rs Normal file
View File

@@ -0,0 +1,86 @@
//! `lunehub hook pre-receive`: the hub's secret check (P3), run by Git before it accepts any change.
use crate::db;
use anyhow::{Context, Result};
use lune_core::git2::{self, Oid, Repository};
use lune_core::secrets;
use std::io::BufRead;
use std::path::PathBuf;
/// Returns false (refuse) if any new history entry adds a line that looks like a secret.
pub fn pre_receive() -> Result<bool> {
// Open with Git's environment so we can see the incoming (still quarantined) objects.
let repo = Repository::open_from_env().context("can't open the vault")?;
let data = PathBuf::from(std::env::var("LUNE_HUB_DATA").context("LUNE_HUB_DATA not set")?);
let vault_id: i64 = repo
.path()
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.strip_suffix(".git"))
.and_then(|n| n.parse().ok())
.context("unexpected vault folder")?;
let conn = db::open(&data)?;
let allowed = db::not_secrets(&conn, vault_id)?;
let mut found = vec![];
for line in std::io::stdin().lock().lines() {
let line = line?;
let mut parts = line.split_whitespace();
let (Some(_old), Some(new), Some(_name)) = (parts.next(), parts.next(), parts.next()) else { continue };
let new = Oid::from_str(new)?;
if new.is_zero() {
continue;
}
let mut walk = repo.revwalk()?;
walk.push(new)?;
for r in repo.references()? {
if let Some(target) = r?.target() {
walk.hide(target)?;
}
}
for id in walk {
found.extend(check_commit(&repo, &repo.find_commit(id?)?, &allowed)?);
}
}
if found.is_empty() {
return Ok(true);
}
for f in &found {
eprintln!("lune: {f}");
}
let vault: String = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).unwrap_or_default();
let actor = std::env::var("LUNE_ACTOR").unwrap_or_else(|_| "unknown device".into());
db::log(&conn, &actor, "change refused", &format!("{vault}: possible secret — {}", found.join("; ")))?;
Ok(false)
}
/// Lines this history entry adds (relative to all its parents) that look like secrets.
fn check_commit(repo: &Repository, commit: &git2::Commit, allowed: &std::collections::HashSet<String>) -> Result<Vec<String>> {
let parents: Vec<git2::Tree> = commit.parents().map(|p| p.tree()).collect::<Result<_, _>>()?;
let tree = commit.tree()?;
let first = parents.first();
let diff = repo.diff_tree_to_tree(first, Some(&tree), None)?;
let mut out = vec![];
for delta in diff.deltas() {
if !matches!(delta.status(), git2::Delta::Added | git2::Delta::Modified) {
continue;
}
let Some(path) = delta.new_file().path() else { continue };
let new = repo.find_blob(delta.new_file().id())?;
// A line already present in any parent isn't new here.
let mut old = Vec::new();
for p in &parents {
if let Ok(e) = p.get_path(path)
&& let Ok(b) = repo.find_blob(e.id())
{
old.extend_from_slice(b.content());
old.push(b'\n');
}
}
let old = if old.is_empty() { None } else { Some(old.as_slice()) };
for hit in secrets::scan_bytes(new.content(), old, allowed) {
out.push(format!("{} line {}: possible {}", path.display(), hit.line, hit.rule));
}
}
Ok(out)
}

85
hub/src/main.rs Normal file
View File

@@ -0,0 +1,85 @@
//! lunehub: accounts, memberships, devices and vault repos for a team (Milestone 3).
mod api;
mod db;
mod git;
mod hook;
use anyhow::Result;
use axum::Router;
use axum::extract::DefaultBodyLimit;
use axum::routing::{any, get, post};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
fn env(name: &str, default: &str) -> String {
std::env::var(name).unwrap_or_else(|_| default.to_string())
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
["hook", "pre-receive"] => {
let ok = hook::pre_receive()?;
std::process::exit(if ok { 0 } else { 1 });
}
["health"] => {
// For the container healthcheck: is the hub answering?
use std::io::{Read, Write};
let port = env("LUNE_HUB_LISTEN", "0.0.0.0:8080").rsplit(':').next().unwrap_or("8080").to_string();
let mut s = std::net::TcpStream::connect(format!("127.0.0.1:{port}"))?;
s.write_all(b"GET /health HTTP/1.0\r\n\r\n")?;
let mut answer = String::new();
s.read_to_string(&mut answer)?;
std::process::exit(if answer.ends_with("ok") { 0 } else { 1 });
}
[] | ["serve"] => serve(),
_ => {
eprintln!("usage: lunehub [serve] | lunehub health | lunehub hook pre-receive");
std::process::exit(2);
}
}
}
#[tokio::main]
async fn serve() -> Result<()> {
let data = PathBuf::from(env("LUNE_HUB_DATA", "/data"));
let url = env("LUNE_HUB_URL", "http://localhost:8080").trim_end_matches('/').to_string();
let listen = env("LUNE_HUB_LISTEN", "0.0.0.0:8080");
std::fs::create_dir_all(data.join("repos"))?;
let conn = db::open(&data)?;
// Keep every vault's hook pointing at this binary (it may have moved with an update).
for entry in std::fs::read_dir(data.join("repos"))? {
let path = entry?.path();
if path.extension().is_some_and(|e| e == "git") {
git::install_hook(&path)?;
}
}
if let Some(token) = db::owner_invite(&conn, &env("LUNE_OWNER_NAME", "Owner"))? {
println!("No team yet. The owner joins with this one-time link (valid 7 days):");
println!(" lunesync join {url}/join/{token} --name <this device>");
}
let hub = Arc::new(api::Hub { db: Mutex::new(conn), data, url: url.clone() });
let app = Router::new()
.route("/api/join", post(api::join))
.route("/api/login", post(api::login))
.route("/api/pair", post(api::pair))
.route("/api/me", get(api::me))
.route("/api/device/label", post(api::label))
.route("/api/vaults", post(api::create_vault))
.route("/api/invites", post(api::invite))
.route("/api/grants", post(api::grant))
.route("/api/members", post(api::members))
.route("/api/log", get(api::log))
.route("/api/not-secrets", post(api::not_secret))
.route("/git/{repo}/{*rest}", any(git::serve))
.route("/health", get(|| async { "ok" }))
.layer(DefaultBodyLimit::disable())
.with_state(hub);
let listener = tokio::net::TcpListener::bind(&listen).await?;
println!("Lune hub listening on {listen} (public address {url})");
axum::serve(listener, app).await?;
Ok(())
}

108
hub/tests/hub.rs Normal file
View File

@@ -0,0 +1,108 @@
//! The hub end to end: one-time links, pairing, roles enforced by the hub, secrets refused (P3).
use lune_core::hub::{self, HubLink};
use lune_core::vault::{self, Vault};
use lune_core::{remote, secrets, state};
use std::collections::HashSet;
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
struct HubProcess(Child);
impl Drop for HubProcess {
fn drop(&mut self) {
let _ = self.0.kill();
}
}
fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) {
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let url = format!("http://127.0.0.1:{port}");
let mut child = Command::new(env!("CARGO_BIN_EXE_lunehub"))
.env("LUNE_HUB_DATA", data)
.env("LUNE_HUB_URL", &url)
.env("LUNE_HUB_LISTEN", format!("127.0.0.1:{port}"))
.env("LUNE_OWNER_NAME", "Sen")
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut link = String::new();
for line in BufReader::new(child.stdout.take().unwrap()).lines() {
let line = line.unwrap();
if let Some(i) = line.find("http").filter(|_| line.contains("/join/")) {
link = line[i..].split_whitespace().next().unwrap().to_string();
}
if line.contains("listening") {
break;
}
}
(HubProcess(child), url, link)
}
fn as_device(url: &str, w: &hub::Welcome) -> HubLink {
let link = HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() };
remote::set_hub(link.clone());
link
}
#[test]
fn hub_lifecycle() {
let tmp = tempfile::TempDir::new().unwrap();
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
// The owner link works once.
let (_, sen) = hub::join(&owner_link, "Codex").unwrap();
assert_eq!(sen.person, "Sen");
assert!(hub::join(&owner_link, "Again").is_err());
let codex = as_device(&url, &sen);
let devops = codex.create_vault("DevOps").unwrap();
// Pairing: a code works once, and the new device has its own key.
let code = codex.pair().unwrap();
let hermes_w = hub::login(&url, &code, "Hermes").unwrap();
assert!(hub::login(&url, &code, "Again").is_err());
assert_ne!(hermes_w.key, sen.key);
// Codex shares a note; Hermes receives it labeled Codex.
as_device(&url, &sen);
let (cfg, _, err) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap();
assert_eq!(err, None);
let a = Vault::open(&cfg, "Codex").unwrap();
std::fs::write(a.root.join("vm-list.md"), "web-1\n").unwrap();
a.save_changes(None, &HashSet::new()).unwrap();
a.sync().unwrap();
let hermes = as_device(&url, &hermes_w);
assert_eq!(hermes.me().unwrap().vaults[0].role, "manage");
let (cfg_h, _, _) = vault::add("DevOps", &tmp.path().join("hermes"), &devops.git_url, "Hermes").unwrap();
let h = Vault::open(&cfg_h, "Hermes").unwrap();
assert_eq!(std::fs::read(h.root.join("vm-list.md")).unwrap(), b"web-1\n");
// Bob has Read: the hub refuses his changes even from a client that ignores its role.
as_device(&url, &sen);
let bob_link = codex.invite("Bob", &[("DevOps".into(), "read".into())]).unwrap();
let (_, bob_w) = hub::join(&bob_link, "Bob pc").unwrap();
as_device(&url, &bob_w);
let (cfg_b, _, _) = vault::add("DevOps", &tmp.path().join("bob"), &devops.git_url, "Bob pc").unwrap();
let b = Vault::open(&cfg_b, "Bob pc").unwrap();
std::fs::write(b.root.join("bob.md"), "bob\n").unwrap();
b.save_changes(None, &HashSet::new()).unwrap();
assert!(b.sync().is_err(), "read access must not share");
state::write_role(&b.git_dir, "read").unwrap();
assert!(b.sync().unwrap().read_only);
// A line this device calls "not a secret" is still refused by the hub until the hub hears it too.
as_device(&url, &sen);
std::fs::write(a.root.join("aws.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap();
let hit = a.secret_holds().unwrap()[0].hits[0].clone();
secrets::allow(&a.git_dir, &hit, "aws.md").unwrap();
a.save_changes(None, &HashSet::new()).unwrap();
let err = format!("{:#}", a.sync().unwrap_err());
assert!(err.contains("aws.md line 1: possible AWS access key"), "{err}");
codex.not_a_secret(devops.id, &hit.line_hash).unwrap();
a.sync().unwrap();
let log: Vec<String> = codex.log(50).unwrap().into_iter().map(|e| e.action).collect();
for action in ["joined", "device added", "vault created", "invite created", "change refused", "not a secret"] {
assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}");
}
}