use sdforge::cli::{CliArgInfo, CliArgType, CliCommandRegistration, CliHandlerRegistration};
use sdforge::core::{ApiError, HandlerArgs, HandlerFuture, HandlerState};
use sdforge::inventory;
use crate::error::{GarrisonError, GarrisonResult};
use crate::i18n::translate_detail;
use crate::GarrisonDao;
fn parse_bool_arg(args: &HandlerArgs, name: &str, default: bool) -> GarrisonResult<bool> {
match args.get(name).map(|s| s.to_ascii_lowercase()).as_deref() {
None => Ok(default),
Some("true") => Ok(true),
Some("false") => Ok(false),
Some(raw) => Err(GarrisonError::InvalidParam(format!(
"cli-arg-bool-invalid::{name}::{raw}::expected true|false"
))),
}
}
fn parse_num_arg<T: std::str::FromStr>(
args: &HandlerArgs,
name: &str,
default: T,
) -> GarrisonResult<T> {
match args.get(name) {
None => Ok(default),
Some(raw) => raw.parse::<T>().map_err(|_| {
GarrisonError::InvalidParam(format!("cli-arg-numeric-invalid::{name}::{raw}"))
}),
}
}
fn require_str_arg(args: &HandlerArgs, name: &str) -> GarrisonResult<String> {
args.get(name)
.filter(|s| !s.trim().is_empty())
.cloned()
.ok_or_else(|| GarrisonError::InvalidParam(format!("cli-arg-missing::{name}::required")))
}
fn optional_str_arg(args: &HandlerArgs, name: &str) -> Option<String> {
args.get(name).filter(|s| !s.trim().is_empty()).cloned()
}
inventory::submit! {
CliCommandRegistration::new(
"key-rotate",
env!("CARGO_PKG_VERSION"),
"Generate a new 256-bit signing key and print ready-to-paste config fragments",
"handle_key_rotate_cmd",
)
.with_args(&[CliArgInfo::new(
"session-key",
"Also generate an independent session key (for split deployments sealing the session layer separately)",
CliArgType::Body,
false,
Some("false"),
)])
}
inventory::submit! { CliHandlerRegistration { name: "key-rotate", handler: handle_key_rotate_cmd } }
fn handle_key_rotate_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
let session_key = parse_bool_arg(&args, "session-key", false).map_err(cli_api_error)?;
run_key_rotate(session_key)
.await
.map(|_| serde_json::Value::Null)
.map_err(cli_api_error)
})
}
inventory::submit! {
CliCommandRegistration::new(
"user-hash",
env!("CARGO_PKG_VERSION"),
"Create an Argon2id password hash and print env/CLI/YAML install fragments",
"handle_user_hash_cmd",
)
.with_args(&[
CliArgInfo::new("user", "Username (non-empty, must not contain ':' — the credential string separates user and hash with ':')", CliArgType::Body, true, None),
CliArgInfo::new("password", "Plaintext password (omit to read GARRISON_CLI_PASSWORD and keep it out of shell history)", CliArgType::Body, false, None),
CliArgInfo::new("pool-size", "Argon2 concurrent token pool size (0 is clamped to 1 by with_pool)", CliArgType::Body, false, Some("1")),
CliArgInfo::new("escape-dollar", "Escape '$' as '$$' in the env fragment (docker-compose interpolation; CLI/YAML fragments unaffected)", CliArgType::Body, false, Some("false")),
])
}
inventory::submit! { CliHandlerRegistration { name: "user-hash", handler: handle_user_hash_cmd } }
fn handle_user_hash_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
let user = require_str_arg(&args, "user").map_err(cli_api_error)?;
let password = optional_str_arg(&args, "password");
let pool_size = parse_num_arg::<usize>(&args, "pool-size", 1).map_err(cli_api_error)?;
let escape_dollar = parse_bool_arg(&args, "escape-dollar", false).map_err(cli_api_error)?;
run_user_hash(user, password, pool_size, escape_dollar)
.await
.map(|_| serde_json::Value::Null)
.map_err(cli_api_error)
})
}
inventory::submit! {
CliCommandRegistration::new(
"one-time-access-token",
env!("CARGO_PKG_VERSION"),
"Issue a short-lived one-time login credential for a user",
"handle_one_time_access_token_cmd",
)
.with_args(&[
CliArgInfo::new("db-url", "Database URL (e.g. sqlite:///var/lib/garrison/garrison.db or postgres://...; the sqlite file must already exist; credential registry and user lookup both run against this DB)", CliArgType::Body, true, None),
CliArgInfo::new("user", "Target username (non-empty)", CliArgType::Body, true, None),
CliArgInfo::new("tenant-id", "Tenant ID (0 = default tenant)", CliArgType::Body, false, Some("0")),
CliArgInfo::new("ttl-seconds", "Credential validity in seconds (0 < ttl <= 86400)", CliArgType::Body, false, Some("300")),
CliArgInfo::new("secret", "Signing key (default: GARRISON_JWT_SECRET; an explicit error when neither is set)", CliArgType::Body, false, None),
CliArgInfo::new("migrate", "Run core migrations against the target DB first (off by default — a write side effect on production DBs; issuance fails explicitly when the DB is uninitialized)", CliArgType::Body, false, Some("false")),
CliArgInfo::new("migrations-dir", "Migration script base directory (only used with --migrate)", CliArgType::Body, false, Some("migrations/sqlite")),
])
}
inventory::submit! { CliHandlerRegistration { name: "one-time-access-token", handler: handle_one_time_access_token_cmd } }
fn handle_one_time_access_token_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
let db_url = require_str_arg(&args, "db-url").map_err(cli_api_error)?;
let user = require_str_arg(&args, "user").map_err(cli_api_error)?;
let tenant_id = parse_num_arg::<i64>(&args, "tenant-id", 0).map_err(cli_api_error)?;
let ttl_seconds = parse_num_arg::<u64>(&args, "ttl-seconds", 300).map_err(cli_api_error)?;
let secret = optional_str_arg(&args, "secret");
let migrate = parse_bool_arg(&args, "migrate", false).map_err(cli_api_error)?;
let migrations_dir = args
.get("migrations-dir")
.cloned()
.unwrap_or_else(|| "migrations/sqlite".to_string());
run_one_time_access_token(
db_url,
user,
tenant_id,
ttl_seconds,
secret,
migrate,
migrations_dir,
)
.await
.map(|_| serde_json::Value::Null)
.map_err(cli_api_error)
})
}
inventory::submit! {
CliCommandRegistration::new(
"change-key",
env!("CARGO_PKG_VERSION"),
"Re-encrypt all field-encrypted rows to a new primary key (transactional batches)",
"handle_change_key_cmd",
)
.with_args(&[
CliArgInfo::new("db-url", "Database URL (the sqlite file must already exist)", CliArgType::Body, true, None),
CliArgInfo::new("tenant", "Tenant identifier (AAD binding component; must match the runtime configuration)", CliArgType::Body, false, Some("default")),
CliArgInfo::new("keys", "Comma-separated key set, entries `key_id:hex` (hex exactly 64 chars = 32 bytes); the first entry is the primary key (new writes encrypt with it); empty falls back to GARRISON_FIELD_ENCRYPTION_KEYS", CliArgType::Body, false, None),
CliArgInfo::new("batch-size", "Batch size (sensitive-namespace keys scanned per batch, must be > 0)", CliArgType::Body, false, Some("200")),
])
}
inventory::submit! { CliHandlerRegistration { name: "change-key", handler: handle_change_key_cmd } }
fn handle_change_key_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
let db_url = require_str_arg(&args, "db-url").map_err(cli_api_error)?;
let tenant = args
.get("tenant")
.cloned()
.unwrap_or_else(|| "default".to_string());
let keys = optional_str_arg(&args, "keys")
.map(|spec| spec.split(',').map(str::to_string).collect())
.unwrap_or_default();
let batch_size = parse_num_arg::<usize>(&args, "batch-size", 200).map_err(cli_api_error)?;
run_change_key(db_url, tenant, keys, batch_size)
.await
.map(|_| serde_json::Value::Null)
.map_err(cli_api_error)
})
}
inventory::submit! {
CliCommandRegistration::new(
"check-key",
env!("CARGO_PKG_VERSION"),
"Verify field-encryption decryptability (read-only, touches no rows)",
"handle_check_key_cmd",
)
.with_args(&[
CliArgInfo::new("db-url", "Database URL (the sqlite file must already exist)", CliArgType::Body, true, None),
CliArgInfo::new("tenant", "Tenant identifier (AAD binding component; must match the runtime configuration)", CliArgType::Body, false, Some("default")),
CliArgInfo::new("keys", "Comma-separated key set, entries `key_id:hex`; empty falls back to GARRISON_FIELD_ENCRYPTION_KEYS", CliArgType::Body, false, None),
CliArgInfo::new("pattern", "Sensitive-namespace glob (default scans everything)", CliArgType::Body, false, Some("*")),
])
}
inventory::submit! { CliHandlerRegistration { name: "check-key", handler: handle_check_key_cmd } }
fn handle_check_key_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
let db_url = require_str_arg(&args, "db-url").map_err(cli_api_error)?;
let tenant = args
.get("tenant")
.cloned()
.unwrap_or_else(|| "default".to_string());
let keys = optional_str_arg(&args, "keys")
.map(|spec| spec.split(',').map(str::to_string).collect())
.unwrap_or_default();
let pattern = args
.get("pattern")
.cloned()
.unwrap_or_else(|| "*".to_string());
run_check_key(db_url, tenant, keys, pattern)
.await
.map(|_| serde_json::Value::Null)
.map_err(cli_api_error)
})
}
inventory::submit! {
CliCommandRegistration::new(
"vacuum-kv",
env!("CARGO_PKG_VERSION"),
"Delete expired rows from the garrison_kv table (untouched rows stay)",
"handle_vacuum_kv_cmd",
)
.with_args(&[
CliArgInfo::new("db-url", "Database URL (the sqlite file must already exist)", CliArgType::Body, true, None),
CliArgInfo::new("sweep-legacy-session-keys", "Also sweep legacy raw-key rows left over from the session-key digest migration (rows under `token:session:` whose remainder is not 64-char lowercase hex)", CliArgType::Body, false, Some("false")),
])
}
inventory::submit! { CliHandlerRegistration { name: "vacuum-kv", handler: handle_vacuum_kv_cmd } }
fn handle_vacuum_kv_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
let db_url = require_str_arg(&args, "db-url").map_err(cli_api_error)?;
let sweep_legacy =
parse_bool_arg(&args, "sweep-legacy-session-keys", false).map_err(cli_api_error)?;
run_vacuum_kv(db_url, sweep_legacy)
.await
.map(|_| serde_json::Value::Null)
.map_err(cli_api_error)
})
}
fn cli_api_error(e: GarrisonError) -> ApiError {
ApiError::internal_error(e.to_string(), "garrison.cli")
}
fn parse_key_entries(specs: &[String]) -> GarrisonResult<Vec<(String, String)>> {
if specs.is_empty() {
return Err(GarrisonError::InvalidParam(
"cli-key-specs-empty::".to_string(),
));
}
let mut keys = Vec::with_capacity(specs.len());
for spec in specs {
let (key_id, hex) = spec
.split_once(':')
.ok_or_else(|| GarrisonError::InvalidParam(format!("cli-key-spec-format::{spec}")))?;
if key_id.is_empty() {
return Err(GarrisonError::InvalidParam(format!(
"cli-key-spec-empty-id::{spec}"
)));
}
if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(GarrisonError::InvalidParam(format!(
"cli-key-spec-hex-invalid::{key_id}"
)));
}
keys.push((key_id.to_string(), hex.to_ascii_lowercase()));
}
Ok(keys)
}
async fn run_change_key(
db_url: String,
tenant: String,
key_specs: Vec<String>,
batch_size: usize,
) -> GarrisonResult<()> {
let entries = resolve_key_entries(key_specs)?;
let cipher = crate::secure::encryption::FieldCipher::from_key_entries(&entries)?;
let pool = crate::dao::init_dbnexus(&db_url).await?;
let kv = crate::dao::DbnexusKvDao::new(pool.clone());
kv.ensure_table().await?;
let inner: std::sync::Arc<dyn GarrisonDao> = std::sync::Arc::new(
crate::dao::GarrisonDaoDbnexus::new(pool, std::sync::Arc::new(kv)),
);
let dao = crate::secure::encryption::FieldEncryptionDao::new(
inner.clone(),
std::sync::Arc::new(cipher.clone()),
&tenant,
)?;
let new_cipher = crate::secure::encryption::FieldCipher::from_key_entries(&entries)?;
let report = dao.change_key(new_cipher, batch_size).await?;
let batch = batch_size.to_string();
let scanned = report.scanned.to_string();
let reencrypted = report.reencrypted.to_string();
let legacy_plaintext_reencrypted = report.legacy_plaintext_reencrypted.to_string();
let legacy_key_migrated = report.legacy_key_migrated.to_string();
let skipped_current_key = report.skipped_current_key.to_string();
let failed = report.failed.len().to_string();
println!(
"{}",
translate_detail(
"cli-change-key-report",
&[
("tenant", tenant.as_str()),
("batch_size", batch.as_str()),
("scanned", scanned.as_str()),
("reencrypted", reencrypted.as_str()),
(
"legacy_plaintext_reencrypted",
legacy_plaintext_reencrypted.as_str()
),
("legacy_key_migrated", legacy_key_migrated.as_str()),
("skipped_current_key", skipped_current_key.as_str()),
("failed", failed.as_str()),
]
)
);
for line in &report.failed {
let row = format!("{line:?}");
println!(
" {}",
translate_detail("cli-change-key-failed-row", &[("row", row.as_str())])
);
}
if report.scanned == 0 {
println!(
"\n{}",
translate_detail("cli-change-key-empty-scan-warning", &[])
);
return Err(GarrisonError::Config(
"cli-change-key-empty-scan::data-addressing-likely-unavailable::refusing-to-report-success"
.to_string(),
));
}
if !report.failed.is_empty() {
return Err(GarrisonError::Dao(format!(
"cli-change-key-rows-failed::{}-rows-need-attention",
report.failed.len()
)));
}
Ok(())
}
async fn run_check_key(
db_url: String,
tenant: String,
key_specs: Vec<String>,
pattern: String,
) -> GarrisonResult<()> {
let entries = resolve_key_entries(key_specs)?;
let cipher = crate::secure::encryption::FieldCipher::from_key_entries(&entries)?;
let pool = crate::dao::init_dbnexus(&db_url).await?;
let kv = crate::dao::DbnexusKvDao::new(pool.clone());
kv.ensure_table().await?;
let inner: std::sync::Arc<dyn GarrisonDao> = std::sync::Arc::new(
crate::dao::GarrisonDaoDbnexus::new(pool, std::sync::Arc::new(kv)),
);
let dao = crate::secure::encryption::FieldEncryptionDao::new(
inner,
std::sync::Arc::new(cipher),
&tenant,
)?;
let report = dao.check_key(&pattern).await?;
let scanned = report.scanned.to_string();
let encrypted_ok = report.encrypted_ok.to_string();
let legacy_plaintext = report.legacy_plaintext.to_string();
let legacy_raw_key = report.legacy_raw_key.to_string();
let corrupt = report.corrupt.len().to_string();
println!(
"{}",
translate_detail(
"cli-check-key-report",
&[
("tenant", tenant.as_str()),
("pattern", pattern.as_str()),
("scanned", scanned.as_str()),
("encrypted_ok", encrypted_ok.as_str()),
("legacy_plaintext", legacy_plaintext.as_str()),
("legacy_raw_key", legacy_raw_key.as_str()),
("corrupt", corrupt.as_str()),
]
)
);
for line in &report.corrupt {
let row = format!("{line:?}");
println!(
" {}",
translate_detail("cli-check-key-corrupt-row", &[("row", row.as_str())])
);
}
if report.scanned == 0 {
println!(
"\n{}",
translate_detail("cli-check-key-empty-scan-hint", &[])
);
return Err(GarrisonError::Config(
"cli-check-key-empty-scan::data-addressing-likely-unavailable::see-module-docs"
.to_string(),
));
}
if !report.corrupt.is_empty() {
return Err(GarrisonError::Dao(format!(
"cli-check-key-corrupt-rows::{}-rows-need-attention",
report.corrupt.len()
)));
}
Ok(())
}
async fn run_vacuum_kv(db_url: String, sweep_legacy: bool) -> GarrisonResult<()> {
let pool = crate::dao::init_dbnexus(&db_url).await?;
let kv = crate::dao::DbnexusKvDao::new(pool);
kv.ensure_table().await?;
let deleted = kv.vacuum_expired().await?;
let count = deleted.to_string();
println!(
"{}",
translate_detail("cli-vacuum-kv-report", &[("count", count.as_str())])
);
if sweep_legacy {
let swept = sweep_legacy_session_keys(&kv).await?;
let count = swept.to_string();
println!(
"{}",
translate_detail("cli-vacuum-kv-swept", &[("count", count.as_str())])
);
}
Ok(())
}
async fn sweep_legacy_session_keys(dao: &dyn GarrisonDao) -> GarrisonResult<u64> {
const TOKEN_SESSION_PREFIX: &str = "token:session:";
let keys = dao.keys(&format!("{TOKEN_SESSION_PREFIX}*")).await?;
let mut removed = 0u64;
for key in keys {
let Some(rest) = key.strip_prefix(TOKEN_SESSION_PREFIX) else {
continue;
};
let is_digest = rest.len() == 64
&& rest
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if is_digest {
continue;
}
dao.delete(&key).await?;
removed += 1;
}
Ok(removed)
}
fn resolve_key_entries(explicit: Vec<String>) -> GarrisonResult<Vec<(String, String)>> {
if !explicit.is_empty() {
return parse_key_entries(&explicit);
}
let spec = std::env::var("GARRISON_FIELD_ENCRYPTION_KEYS").map_err(|_| {
GarrisonError::InvalidParam(
"cli-key-source-missing::pass --keys or set GARRISON_FIELD_ENCRYPTION_KEYS".to_string(),
)
})?;
let specs: Vec<String> = spec.split(',').map(str::to_string).collect();
parse_key_entries(&specs)
}
fn generate_signing_key() -> GarrisonResult<String> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes)
.map_err(|e| GarrisonError::Internal(format!("cli-keygen-csprng::{}", e)))?;
let mut out = String::with_capacity(64);
for b in bytes {
out.push_str(&format!("{b:02x}"));
}
Ok(out)
}
fn key_rotate_report(with_session_key: bool) -> GarrisonResult<String> {
let signing = generate_signing_key()?;
let signing_secret = crate::config::JwtSecret::from(signing);
let mut report = String::new();
report.push_str(
"Generated new signing key (256-bit, OS CSPRNG).\n\
Install the fragment below and restart: tokens signed with the \
previous key fail verification immediately after rotation.\n\n",
);
report.push_str("env:\n");
report.push_str(&format!(
"export GARRISON_JWT_SECRET={}\n\n",
signing_secret.as_str()
));
report.push_str("toml:\n");
report.push_str(&format!("jwt_secret = \"{}\"\n", signing_secret.as_str()));
if with_session_key {
let session = generate_signing_key()?;
let session_secret = crate::config::JwtSecret::from(session);
report.push_str("\nsession key (--session-key, generated independently):\n");
report.push_str(&format!("{}\n", session_secret.as_str()));
report.push_str(
"\n note: session tokens (simple/jwt token_style) are signed with\n \
jwt_secret in this version - stock deployments only need the\n signing fragment above; use this value when the session layer\n is sealed with a separate key in split deployments.\n",
);
}
Ok(report)
}
async fn run_key_rotate(with_session_key: bool) -> GarrisonResult<()> {
print!("{}", key_rotate_report(with_session_key)?);
Ok(())
}
async fn run_user_hash(
user: String,
password: Option<String>,
pool_size: usize,
escape_dollar: bool,
) -> GarrisonResult<()> {
let password = match password {
Some(p) => p,
None => std::env::var("GARRISON_CLI_PASSWORD").map_err(|_| {
GarrisonError::InvalidParam("cli-user-hash-password-missing::".to_string())
})?,
};
print!(
"{}",
user_hash_report(&user, &password, pool_size, escape_dollar)?
);
Ok(())
}
fn validate_username(user: &str) -> GarrisonResult<()> {
if user.is_empty() {
return Err(GarrisonError::InvalidParam(
"cli-user-hash-user-empty::".to_string(),
));
}
if user.contains(':') {
return Err(GarrisonError::InvalidParam(
"cli-user-hash-user-colon::".to_string(),
));
}
Ok(())
}
fn user_hash_report(
user: &str,
password: &str,
pool_size: usize,
escape_dollar: bool,
) -> GarrisonResult<String> {
validate_username(user)?;
if password.is_empty() {
return Err(GarrisonError::InvalidParam(
"cli-user-hash-password-empty::".to_string(),
));
}
use crate::account::credential::password::{Argon2Hasher, PasswordHasher as _};
let hasher = Argon2Hasher::default().with_pool(pool_size);
let hash = hasher.hash(password)?;
let credential = format!("{user}:{hash}");
let env_value = if escape_dollar {
credential.replace('$', "$$")
} else {
credential.clone()
};
Ok(format!(
"Created Argon2id hash for user '{user}' (pool={pool_size}; pool_size=0 is clamped to 1).\n\n\
env:\nexport GARRISON_BOOTSTRAP_USERS={env_value}\n\n\
cli:\n--bootstrap-users '{credential}'\n\n\
yaml:\nbootstrap_users: \"{credential}\"\n\n\
note: for docker-compose env interpolation use --escape-dollar;\n\
wire the credential into your bootstrap seeding (app_user.username /\n\
app_user.password_hash) and restart.\n"
))
}
const ONE_TIME_LOGIN_REGISTRY_KEY: &str = "one_time_login";
const MAX_TTL_SECS: u64 = 86_400;
struct IssuedOneTimeToken {
token: String,
jti: String,
user_id: String,
username: String,
tenant_id: i64,
expires_at_unix: i64,
registry_field_key: String,
}
impl std::fmt::Debug for IssuedOneTimeToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IssuedOneTimeToken")
.field("token", &"<redacted>")
.field("jti", &self.jti)
.field("user_id", &self.user_id)
.field("username", &self.username)
.field("tenant_id", &self.tenant_id)
.field("expires_at_unix", &self.expires_at_unix)
.field("registry_field_key", &self.registry_field_key)
.finish()
}
}
async fn issue_one_time_access_token(
users: &dyn crate::dao::repository::UserRepository,
ext: &dyn crate::dao::repository::UserExtRepository,
tenant_id: i64,
username: &str,
ttl_seconds: u64,
signing_secret: &str,
) -> GarrisonResult<IssuedOneTimeToken> {
if ttl_seconds == 0 {
return Err(GarrisonError::InvalidParam(format!(
"cli-one-time-ttl-invalid::{ttl_seconds}::allowed=1..={MAX_TTL_SECS}"
)));
}
if signing_secret.is_empty() {
return Err(GarrisonError::InvalidParam(
"cli-one-time-secret-empty::signing secret must not be empty".to_string(),
));
}
let user = users
.find_by_username(tenant_id, username)
.await?
.ok_or_else(|| {
GarrisonError::InvalidParam(format!(
"cli-one-time-user-not-found::{username}::{tenant_id}"
))
})?;
if user.status != "active" {
return Err(GarrisonError::InvalidParam(format!(
"cli-one-time-user-not-active::{username}::{}",
user.status
)));
}
let handler = crate::protocol::jwt::JwtHandler::new(signing_secret);
let token = handler.sign(&user.id, ttl_seconds as i64)?;
let claims = handler.verify(&token)?;
let jti = claims.jti.clone().ok_or_else(|| {
GarrisonError::Internal("cli-one-time-jti-missing::signed token lacks jti".to_string())
})?;
let expires_at_rfc3339 = chrono::DateTime::from_timestamp(claims.exp, 0).ok_or_else(|| {
GarrisonError::Internal(format!("cli-one-time-exp-out-of-range::{}", claims.exp))
})?;
let registry_value = format!("{jti}|{}", expires_at_rfc3339.to_rfc3339());
ext.upsert(
tenant_id,
&user.id,
ONE_TIME_LOGIN_REGISTRY_KEY,
Some(registry_value),
"string",
)
.await?;
Ok(IssuedOneTimeToken {
token,
jti,
user_id: user.id,
username: user.username,
tenant_id,
expires_at_unix: claims.exp,
registry_field_key: ONE_TIME_LOGIN_REGISTRY_KEY.to_string(),
})
}
async fn run_one_time_access_token(
db_url: String,
user: String,
tenant_id: i64,
ttl_seconds: u64,
secret: Option<String>,
migrate: bool,
migrations_dir: String,
) -> GarrisonResult<()> {
if ttl_seconds == 0 || ttl_seconds > MAX_TTL_SECS {
return Err(GarrisonError::InvalidParam(format!(
"cli-one-time-ttl-invalid::{ttl_seconds}::allowed=1..={MAX_TTL_SECS}"
)));
}
let signing_secret = match secret {
Some(s) => s,
None => std::env::var("GARRISON_JWT_SECRET").map_err(|_| {
GarrisonError::InvalidParam("cli-one-time-secret-missing::".to_string())
})?,
};
let pool = crate::dao::init_dbnexus(&db_url).await?;
if migrate {
let migration =
crate::dao::GarrisonMigration::with_base_dir(pool.clone(), migrations_dir.into());
migration
.migrate_core()
.await
.map_err(|e| GarrisonError::Config(format!("cli-one-time-migrate::{e}")))?;
}
let users = crate::dao::repository::sqlite::DbnexusUserRepository::new(pool.clone());
let ext = crate::dao::repository::sqlite::DbnexusUserExtRepository::new(pool);
let issued =
issue_one_time_access_token(&users, &ext, tenant_id, &user, ttl_seconds, &signing_secret)
.await?;
let expires_at_rfc3339 = chrono::DateTime::from_timestamp(issued.expires_at_unix, 0)
.map(|dt| dt.to_rfc3339())
.unwrap_or_else(|| issued.expires_at_unix.to_string());
let tenant_arg = issued.tenant_id.to_string();
let expires_at_unix_arg = issued.expires_at_unix.to_string();
println!(
"{}",
translate_detail(
"cli-one-time-access-token-issued",
&[
("user", issued.username.as_str()),
("tenant", tenant_arg.as_str()),
("token", issued.token.as_str()),
("expires_at", expires_at_rfc3339.as_str()),
("unix", expires_at_unix_arg.as_str()),
("field_key", issued.registry_field_key.as_str()),
]
)
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ops_command_surface_is_six_commands() {
let names: Vec<&str> = sdforge::inventory::iter::<CliCommandRegistration>()
.map(|r| r.name)
.collect();
for expected in [
"key-rotate",
"user-hash",
"one-time-access-token",
"change-key",
"check-key",
"vacuum-kv",
] {
assert!(
names.contains(&expected),
"缺少子命令 {expected}: {names:?}"
);
}
assert!(
!names.contains(&"healthcheck")
|| names.iter().filter(|n| **n == "healthcheck").count() == 1,
"healthcheck 只允许顶层一处注册: {names:?}"
);
}
#[test]
fn ops_handlers_match_command_registrations() {
let commands: std::collections::BTreeSet<&str> =
sdforge::inventory::iter::<CliCommandRegistration>()
.map(|r| r.name)
.collect();
let handlers: std::collections::BTreeSet<&str> =
sdforge::inventory::iter::<CliHandlerRegistration>()
.map(|r| r.name)
.collect();
for cmd in [
"key-rotate",
"user-hash",
"one-time-access-token",
"change-key",
"check-key",
"vacuum-kv",
"healthcheck",
"serve",
] {
if commands.contains(cmd) {
assert!(handlers.contains(cmd), "{cmd} 注册了命令但缺 handler");
}
}
}
#[test]
fn parse_bool_arg_semantics() {
let mut args = HandlerArgs::new();
assert!(parse_bool_arg(&args, "flag", true).unwrap(), "缺参回退默认");
args.insert("flag".to_string(), "TRUE".to_string());
assert!(parse_bool_arg(&args, "flag", false).unwrap());
args.insert("flag".to_string(), "False".to_string());
assert!(!parse_bool_arg(&args, "flag", true).unwrap());
args.insert("flag".to_string(), "yes".to_string());
assert!(
parse_bool_arg(&args, "flag", true)
.unwrap_err()
.to_string()
.contains("cli-arg-bool-invalid"),
"非法 bool 值必须显性报错"
);
}
#[test]
fn parse_num_arg_semantics() {
let mut args = HandlerArgs::new();
assert_eq!(
parse_num_arg::<u64>(&args, "ttl-seconds", 300).unwrap(),
300
);
args.insert("ttl-seconds".to_string(), "120".to_string());
assert_eq!(
parse_num_arg::<u64>(&args, "ttl-seconds", 300).unwrap(),
120
);
args.insert("ttl-seconds".to_string(), "soon".to_string());
assert!(
parse_num_arg::<u64>(&args, "ttl-seconds", 300)
.unwrap_err()
.to_string()
.contains("cli-arg-numeric-invalid"),
"非法数值必须显性报错"
);
}
#[test]
fn require_and_optional_str_arg_semantics() {
let mut args = HandlerArgs::new();
assert!(require_str_arg(&args, "db-url")
.unwrap_err()
.to_string()
.contains("cli-arg-missing"));
args.insert("db-url".to_string(), " ".to_string());
assert!(require_str_arg(&args, "db-url").is_err(), "空白串视为缺失");
assert_eq!(optional_str_arg(&args, "db-url"), None);
args.insert("db-url".to_string(), "sqlite::memory:".to_string());
assert_eq!(require_str_arg(&args, "db-url").unwrap(), "sqlite::memory:");
}
#[test]
fn comma_separated_keys_split() {
let mut args = HandlerArgs::new();
args.insert(
"keys".to_string(),
"k1:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef,k2:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210".to_string(),
);
let keys = optional_str_arg(&args, "keys")
.map(|spec| spec.split(',').map(str::to_string).collect::<Vec<_>>())
.unwrap_or_default();
assert_eq!(keys.len(), 2, "逗号分隔应拆为两把钥");
}
#[test]
fn generated_signing_key_is_256bit_hex_and_unique() {
let first = generate_signing_key().expect("keygen must succeed");
let second = generate_signing_key().expect("keygen must succeed");
assert_eq!(first.len(), 64, "256-bit 密钥应编码为 64 个 hex 字符");
assert!(
first.chars().all(|c| c.is_ascii_hexdigit()),
"密钥必须为 hex 编码,实际: {first}"
);
assert_ne!(first, second, "两次生成必须得到独立密钥");
}
#[test]
fn key_rotate_report_contains_all_install_fragments() {
let report = key_rotate_report(true).expect("report must build");
assert!(
report.contains("GARRISON_JWT_SECRET="),
"env 安装片段缺失:\n{report}"
);
assert!(
report.contains("jwt_secret = \""),
"TOML 安装片段缺失:\n{report}"
);
let signing = report
.lines()
.find(|l| l.starts_with("export GARRISON_JWT_SECRET="))
.map(|l| {
l.trim_start_matches("export GARRISON_JWT_SECRET=")
.to_string()
})
.expect("env 片段行必须携带签名密钥值");
let session = report
.lines()
.find(|l| l.len() == 64 && l.chars().all(|c| c.is_ascii_hexdigit()) && *l != signing)
.expect("--session-key 必须额外产出独立会话密钥裸值");
assert_ne!(signing, session, "签名密钥与会话密钥必须独立生成");
}
#[test]
fn key_rotation_rejects_old_key_tokens_and_accepts_new() {
use crate::protocol::jwt::JwtHandler;
let old_key = generate_signing_key().expect("old keygen");
let new_key = key_rotate_report(false)
.expect("rotation report")
.lines()
.find(|l| l.starts_with("export GARRISON_JWT_SECRET="))
.map(|l| {
l.trim_start_matches("export GARRISON_JWT_SECRET=")
.to_string()
})
.expect("轮换报告必须携带新签名密钥");
let old_handler = JwtHandler::new(&old_key);
let new_handler = JwtHandler::new(&new_key);
let old_token = old_handler.sign("user-1", 3600).expect("旧钥签发必须成功");
let old_under_new = new_handler.verify(&old_token);
assert!(
old_under_new.is_err(),
"轮换后旧钥 token 必须验证失败,不得静默通过"
);
let new_token = new_handler.sign("user-1", 3600).expect("新钥签发必须成功");
let claims = new_handler
.verify(&new_token)
.expect("新钥 token 必须验证成功");
assert_eq!(claims.login_id, "user-1");
}
const HASH_TEST_USER: &str = "ops-admin";
const HASH_TEST_PASSWORD: &str = "correct horse battery staple";
fn extract_yaml_credential(report: &str) -> String {
let line = report
.lines()
.find(|l| l.starts_with("bootstrap_users: \""))
.expect("YAML 片段行必须存在");
line.trim_start_matches("bootstrap_users: \"")
.trim_end_matches('"')
.to_string()
}
#[test]
fn user_hash_report_emits_hash_that_verifies() {
let report = user_hash_report(HASH_TEST_USER, HASH_TEST_PASSWORD, 1, false)
.expect("report must build");
let credential = extract_yaml_credential(&report);
let hash = credential
.strip_prefix(&format!("{HASH_TEST_USER}:"))
.expect("凭据串必须以 user: 开头");
assert!(
hash.starts_with("$argon2id$"),
"必须是 Argon2id PHC 格式,实际: {hash}"
);
use crate::account::credential::password::{Argon2Hasher, PasswordHasher as _};
let verifier = Argon2Hasher::default();
assert!(
verifier
.verify(HASH_TEST_PASSWORD, hash)
.expect("verify must not error"),
"报告中的哈希必须能验证原密码"
);
assert!(
!verifier
.verify("wrong-password", hash)
.expect("verify must not error"),
"错误密码必须验证失败"
);
}
#[derive(Debug, serde::Deserialize, confers::Config)]
#[config(env_prefix = "GARRISON_")]
struct BootstrapUsersFixture {
bootstrap_users: Option<String>,
}
#[test]
#[serial_test::serial]
fn env_fragment_is_loadable_by_confers() {
let report = user_hash_report(HASH_TEST_USER, HASH_TEST_PASSWORD, 1, false)
.expect("report must build");
let credential = report
.lines()
.find(|l| l.starts_with("export GARRISON_BOOTSTRAP_USERS="))
.map(|l| {
l.trim_start_matches("export GARRISON_BOOTSTRAP_USERS=")
.to_string()
})
.expect("env 片段行必须存在");
std::env::set_var("GARRISON_BOOTSTRAP_USERS", &credential);
let loaded = BootstrapUsersFixture::load_sync().expect("confers 加载必须成功");
std::env::remove_var("GARRISON_BOOTSTRAP_USERS");
assert_eq!(
loaded.bootstrap_users.as_deref(),
Some(credential.as_str()),
"env 片段必须无损还原"
);
}
#[test]
fn yaml_fragment_is_loadable_by_confers() {
let report = user_hash_report(HASH_TEST_USER, HASH_TEST_PASSWORD, 1, false)
.expect("report must build");
let credential = extract_yaml_credential(&report);
let yaml = format!("bootstrap_users: \"{credential}\"\n");
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("bootstrap.yaml");
std::fs::write(&path, yaml).expect("write yaml fragment");
let config = confers::config::ConfigBuilder::<BootstrapUsersFixture>::new()
.source(Box::new(
confers::config::FileSource::new(path.to_str().expect("utf8 path"))
.with_priority(10)
.with_loader_config(
confers::loader::LoaderConfig::new()
.allow_absolute()
.max_size(64 * 1024)
.redact_error_paths(),
),
))
.build()
.expect("yaml 片段必须可被 confers 加载");
assert_eq!(
config.bootstrap_users.as_deref(),
Some(credential.as_str()),
"YAML 片段必须无损还原"
);
}
#[test]
#[serial_test::serial]
fn cli_fragment_payload_is_loadable_by_confers() {
let report = user_hash_report(HASH_TEST_USER, HASH_TEST_PASSWORD, 1, false)
.expect("report must build");
let credential = report
.lines()
.find(|l| l.starts_with("--bootstrap-users "))
.map(|l| l.trim_start_matches("--bootstrap-users ").to_string())
.expect("CLI 片段行必须存在");
std::env::set_var("GARRISON_BOOTSTRAP_USERS", &credential);
let loaded = BootstrapUsersFixture::load_sync().expect("confers 加载必须成功");
std::env::remove_var("GARRISON_BOOTSTRAP_USERS");
assert_eq!(
loaded.bootstrap_users.as_deref(),
Some(credential.as_str()),
"CLI 片段必须无损还原"
);
}
#[test]
fn user_hash_rejects_invalid_input_explicitly() {
let empty_user =
user_hash_report("", HASH_TEST_PASSWORD, 1, false).expect_err("空用户名必须显性报错");
assert!(matches!(
empty_user,
GarrisonError::InvalidParam(ref m) if m.contains("user-empty")
));
let colon_user = user_hash_report("a:b", HASH_TEST_PASSWORD, 1, false)
.expect_err("含 ':' 用户名必须显性报错");
assert!(matches!(
colon_user,
GarrisonError::InvalidParam(ref m) if m.contains("user-colon")
));
let empty_password =
user_hash_report(HASH_TEST_USER, "", 1, false).expect_err("空密码必须显性报错");
assert!(matches!(
empty_password,
GarrisonError::InvalidParam(ref m) if m.contains("password-empty")
));
}
#[test]
fn escape_dollar_only_affects_env_fragment() {
let plain =
user_hash_report(HASH_TEST_USER, HASH_TEST_PASSWORD, 1, false).expect("plain report");
let plain_cred = extract_yaml_credential(&plain);
let plain_env_value = plain
.lines()
.find(|l| l.starts_with("export GARRISON_BOOTSTRAP_USERS="))
.map(|l| {
l.trim_start_matches("export GARRISON_BOOTSTRAP_USERS=")
.to_string()
})
.expect("env 行");
assert!(plain_cred.contains('$'), "PHC 哈希必然含 $");
assert_eq!(plain_env_value, plain_cred, "默认 env 片段不转义");
let escaped =
user_hash_report(HASH_TEST_USER, HASH_TEST_PASSWORD, 1, true).expect("escaped report");
let escaped_cred = extract_yaml_credential(&escaped);
let escaped_env_value = escaped
.lines()
.find(|l| l.starts_with("export GARRISON_BOOTSTRAP_USERS="))
.map(|l| {
l.trim_start_matches("export GARRISON_BOOTSTRAP_USERS=")
.to_string()
})
.expect("escaped env 行");
assert_eq!(
escaped_env_value,
escaped_cred.replace('$', "$$"),
"escape_dollar 开启时仅 env 片段将 $ 转义为 $$"
);
assert!(!escaped_cred.contains("$$"), "YAML 片段不应转义");
assert!(
escaped.contains(&format!("--bootstrap-users '{escaped_cred}'")),
"CLI 片段应单引号包裹(PHC 以 $ 开头,防 shell 变量展开)且不转义"
);
}
use crate::dao::repository::sqlite::{DbnexusUserExtRepository, DbnexusUserRepository};
use crate::dao::repository::{NewUser, UserExtRepository, UserRepository};
use crate::dao::{init_dbnexus, GarrisonMigration};
const ONE_TIME_SECRET: &str = "one-time-access-token-test-secret-0123456789abcdef";
async fn one_time_fixture(
seed_users: &[(&str, &str)], ) -> (DbnexusUserRepository, DbnexusUserExtRepository) {
let pool = init_dbnexus("sqlite::memory:")
.await
.expect("init_dbnexus must succeed");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("migrations")
.join("sqlite");
GarrisonMigration::with_base_dir(pool.clone(), migrations_dir)
.migrate_core()
.await
.expect("migrate_core must succeed");
let users = DbnexusUserRepository::new(pool.clone());
for (i, (username, status)) in seed_users.iter().enumerate() {
users
.create(
0,
NewUser {
username: username.to_string(),
password_hash: "$argon2id$m=8,t=1,p=1$seed".to_string(),
status: status.to_string(),
},
)
.await
.unwrap_or_else(|e| panic!("seed user {i} must insert: {e}"));
}
(users, DbnexusUserExtRepository::new(pool))
}
#[tokio::test(flavor = "multi_thread")]
async fn one_time_token_exp_matches_ttl() {
let (users, ext) = one_time_fixture(&[("alice", "active")]).await;
let ttl = 300u64;
let issued = issue_one_time_access_token(&users, &ext, 0, "alice", ttl, ONE_TIME_SECRET)
.await
.expect("issuance must succeed");
let handler = crate::protocol::jwt::JwtHandler::new(ONE_TIME_SECRET);
let claims = handler
.verify(&issued.token)
.expect("issued token must verify");
assert_eq!(
claims.exp,
claims.iat + ttl as i64,
"exp 必须等于 iat + ttl"
);
assert_eq!(claims.sub, issued.user_id, "sub 必须绑定目标用户");
assert_eq!(issued.jti, claims.jti.expect("jti 必须存在"));
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("clock")
.as_secs() as i64;
assert!(
issued.expires_at_unix > now,
"有效期必须落在未来(时钟未回拨的前提下)"
);
assert!(
issued.expires_at_unix - now <= ttl as i64,
"有效期不得超过 ttl"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn one_time_token_unknown_user_is_explicit_error() {
let (users, ext) = one_time_fixture(&[]).await;
let err = issue_one_time_access_token(&users, &ext, 0, "ghost", 300, ONE_TIME_SECRET)
.await
.expect_err("unknown user must fail explicitly");
let reason = err.to_string();
assert!(
matches!(err, GarrisonError::InvalidParam(ref m) if m.contains("user-not-found") && m.contains("ghost")),
"未知用户必须显性报错且点名目标,实际: {reason}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn one_time_token_inactive_user_is_explicit_error() {
let (users, ext) = one_time_fixture(&[("bob", "suspended")]).await;
let err = issue_one_time_access_token(&users, &ext, 0, "bob", 300, ONE_TIME_SECRET)
.await
.expect_err("suspended user must fail explicitly");
let reason = err.to_string();
assert!(
matches!(err, GarrisonError::InvalidParam(ref m) if m.contains("user-not-active")),
"非 active 用户必须显性报错,实际: {reason}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn one_time_token_persists_one_time_registry_row() {
let (users, ext) = one_time_fixture(&[("carol", "active")]).await;
let issued = issue_one_time_access_token(&users, &ext, 0, "carol", 300, ONE_TIME_SECRET)
.await
.expect("issuance must succeed");
let row = ext
.find_by_user_and_key(0, &issued.user_id, &issued.registry_field_key)
.await
.expect("registry lookup must succeed")
.expect("登记行必须存在(存在 = 未消费)");
let stored = row.field_value.expect("登记值必须存在");
let expected_exp = chrono::DateTime::from_timestamp(issued.expires_at_unix, 0)
.expect("valid exp")
.to_rfc3339();
assert_eq!(
stored,
format!("{}|{}", issued.jti, expected_exp),
"登记值必须为 jti|exp 形式且与凭据一致,实际: {stored}"
);
let second = issue_one_time_access_token(&users, &ext, 0, "carol", 300, ONE_TIME_SECRET)
.await
.expect("second issuance must succeed");
let replaced = ext
.find_by_user_and_key(0, &second.user_id, &second.registry_field_key)
.await
.expect("registry lookup must succeed")
.expect("登记行必须仍存在");
let stored = replaced.field_value.expect("登记值必须存在");
assert!(
stored.starts_with(&second.jti),
"重复签发后登记行必须指向新 jti,实际: {stored}"
);
assert!(
!stored.contains(&issued.jti),
"旧 jti 登记必须被覆盖,不得残留: {stored}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn one_time_token_rejects_zero_ttl_and_empty_secret() {
let (users, ext) = one_time_fixture(&[("dave", "active")]).await;
let zero_ttl = issue_one_time_access_token(&users, &ext, 0, "dave", 0, ONE_TIME_SECRET)
.await
.expect_err("ttl=0 must fail explicitly");
assert!(
matches!(zero_ttl, GarrisonError::InvalidParam(ref m) if m.contains("ttl-invalid"))
);
let empty_secret = issue_one_time_access_token(&users, &ext, 0, "dave", 300, "")
.await
.expect_err("空密钥必须显性报错");
assert!(matches!(
empty_secret,
GarrisonError::InvalidParam(ref m) if m.contains("secret-empty")
));
}
mod field_crypto_tests {
use super::*;
use crate::dao::GarrisonDao;
use crate::secure::encryption::{FieldCipher, FieldEncryptionDao};
use std::sync::Arc;
fn key_spec(id: &str, seed: u8) -> String {
let hex: String = (0..32)
.map(|i| format!("{:02x}", seed.wrapping_add((i as u8).wrapping_mul(37))))
.collect();
format!("{id}:{hex}")
}
async fn field_crypto_fixture() -> (tempfile::TempDir, String, Arc<dyn GarrisonDao>) {
let dir = tempfile::tempdir().expect("tempdir");
let db_path = dir.path().join("fields.db");
std::fs::File::create(&db_path).expect("sqlite 文件必须先建");
let db_url = format!("sqlite://{}", db_path.display());
let pool = init_dbnexus(&db_url)
.await
.expect("init_dbnexus must succeed");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("migrations")
.join("sqlite");
GarrisonMigration::with_base_dir(pool.clone(), migrations_dir)
.migrate_core()
.await
.expect("migrate_core must succeed");
let kv = Arc::new(crate::dao::DbnexusKvDao::new(pool.clone()));
kv.ensure_table().await.expect("ensure_table must succeed");
let kv: Arc<dyn GarrisonDao> = kv;
let inner: Arc<dyn GarrisonDao> =
Arc::new(crate::dao::GarrisonDaoDbnexus::new(pool, Arc::clone(&kv)));
let old_hex = key_spec("oldk", 0xaa)
.split_once(':')
.expect("spec must contain ':'")
.1
.to_string();
let old_cipher = FieldCipher::from_key_entries(&[("oldk".to_string(), old_hex)])
.expect("old cipher must build");
let facade = FieldEncryptionDao::new(Arc::clone(&kv), Arc::new(old_cipher), "tenant-a")
.expect("facade must build");
for (key, value) in [
("oauth2:atoken:tok-1", "token-1"),
("oauth2:rtoken:rt-1", "refresh-1"),
("totp:seed:uid", "seed-1"),
] {
facade
.set(key, value, 0)
.await
.expect("seed row must insert");
}
(dir, db_url, inner)
}
async fn raw_snapshot(inner: &Arc<dyn GarrisonDao>) -> Vec<(String, Option<String>)> {
let mut rows = Vec::new();
for prefix in ["oauth2:atoken:", "oauth2:rtoken:", "totp:seed:"] {
for key in inner
.keys(&format!("{prefix}*"))
.await
.expect("keys must list")
{
rows.push((
key.clone(),
inner.get(&key).await.expect("get must succeed"),
));
}
}
rows.sort();
rows
}
#[tokio::test]
async fn change_key_reencrypts_sqlite_rows_to_new_primary() {
let (_dir, db_url, inner) = field_crypto_fixture().await;
for (key, raw) in raw_snapshot(&inner).await {
assert!(
raw.unwrap().starts_with("enc:v1:oldk:"),
"{key} 应为旧钥密文"
);
}
run_change_key(
db_url.clone(),
"tenant-a".to_string(),
vec![key_spec("newk", 0xbb), key_spec("oldk", 0xaa)],
2,
)
.await
.expect("change-key must succeed");
let snapshot = raw_snapshot(&inner).await;
assert_eq!(snapshot.len(), 3, "行数不变");
for (key, raw) in &snapshot {
assert!(
raw.as_deref().unwrap_or("").starts_with("enc:v1:newk:"),
"{key} 应重加密为新主钥密文: {raw:?}"
);
}
let before = raw_snapshot(&inner).await;
run_check_key(
db_url,
"tenant-a".to_string(),
vec![key_spec("newk", 0xbb)],
"*".to_string(),
)
.await
.expect("check-key with new key must be clean");
assert_eq!(
before,
raw_snapshot(&inner).await,
"check-key 不得改动任何行"
);
}
#[tokio::test]
async fn check_key_reports_wrong_tenant_rows_explicitly_and_readonly() {
let (_dir, db_url, inner) = field_crypto_fixture().await;
let before = raw_snapshot(&inner).await;
let err = run_check_key(
db_url.clone(),
"tenant-b".to_string(),
vec![key_spec("oldk", 0xaa)],
"oauth2:*".to_string(),
)
.await
.expect_err("错误租户必须显性失败");
assert!(
matches!(err, GarrisonError::Dao(ref m) if m.contains("cli-check-key-corrupt-rows")),
"实际: {err:?}"
);
assert_eq!(
before,
raw_snapshot(&inner).await,
"check-key 失败路径不得改动任何行"
);
}
#[tokio::test]
async fn change_key_without_old_key_fails_rows_explicitly() {
let (_dir, db_url, _inner) = field_crypto_fixture().await;
let err = run_change_key(
db_url,
"tenant-a".to_string(),
vec![key_spec("newk", 0xbb)],
200,
)
.await
.expect_err("缺旧钥必须显性失败");
assert!(
matches!(err, GarrisonError::Dao(ref m) if m.contains("cli-change-key-rows-failed")),
"实际: {err:?}"
);
}
#[tokio::test]
async fn change_key_empty_scan_refuses_success() {
let dir = tempfile::tempdir().expect("tempdir");
let db_path = dir.path().join("empty.db");
std::fs::File::create(&db_path).expect("sqlite 文件必须先建");
let db_url = format!("sqlite://{}", db_path.display());
let pool = init_dbnexus(&db_url)
.await
.expect("init_dbnexus must succeed");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("migrations")
.join("sqlite");
GarrisonMigration::with_base_dir(pool, migrations_dir)
.migrate_core()
.await
.expect("migrate_core must succeed");
let err = run_change_key(
db_url,
"tenant-a".to_string(),
vec![key_spec("newk", 0xbb)],
200,
)
.await
.expect_err("空扫描必须显性拒绝(数据寻址不可用的疑似故障面)");
assert!(
matches!(err, GarrisonError::Config(ref m) if m.contains("cli-change-key-empty-scan")),
"实际: {err:?}"
);
}
}
#[tokio::test]
async fn sweep_legacy_session_keys_removes_only_raw_token_rows() {
let dir = tempfile::tempdir().expect("tempdir");
let db_path = dir.path().join("sweep_legacy.db");
std::fs::File::create(&db_path).expect("create sqlite file");
let db_url = format!("sqlite://{}", db_path.display());
let pool = init_dbnexus(&db_url).await.expect("init_dbnexus 应成功");
let kv = crate::dao::DbnexusKvDao::new(pool);
kv.ensure_table().await.expect("ensure_table 应成功");
kv.set("token:session:legacy-raw-token", "x", 0)
.await
.unwrap();
kv.set(&format!("token:session:{}", "a".repeat(64)), "x", 0)
.await
.unwrap();
kv.set("account:session:legacy-user", "x", 0).await.unwrap();
let swept = sweep_legacy_session_keys(&kv).await.unwrap();
assert_eq!(swept, 1, "只应清除余段非 64 hex 的遗留 raw 行");
assert!(
kv.get("token:session:legacy-raw-token")
.await
.unwrap()
.is_none(),
"遗留 raw 行应被删除"
);
assert!(
kv.get(&format!("token:session:{}", "a".repeat(64)))
.await
.unwrap()
.is_some(),
"摘要形态行不得被误删(余段 64 hex 即保留)"
);
assert!(
kv.get("account:session:legacy-user")
.await
.unwrap()
.is_some(),
"account 命名空间行不在清扫范围"
);
let swept_again = sweep_legacy_session_keys(&kv).await.unwrap();
assert_eq!(swept_again, 0, "二次清扫应幂等");
}
}