Files
imeai-aKode/codex-rs/cli/tests/login.rs
andrea.difonzo e39aae0085 aKode fase 3: provider locali, chiavi per provider, modelli dal server, SearXNG
- Provider: rimossi openai, Bedrock e GCP integrati e ogni fallback a OpenAI;
  restano ollama, lmstudio e i provider personalizzati. Senza provider, exec e
  TUI mostrano come configurarlo.
- Chiave per provider: api_key = "keyring", provider_api_key_store =
  auto|keyring|file (fallback su file 0600 / ACL Windows); `codex login
  --provider <id> --with-api-key`, `logout --provider`; login status e doctor
  mostrano dove sta la chiave senza rivelarla.
- Modelli letti da GET {base_url}/models; contesto da config, poi dal server
  (/props, meta.n_ctx), poi 32768; apply_patch come tool function; niente tool
  ospitati; niente piu' avviso "metadata not found".
- Unione dei soli messaggi system/developer iniziali in un unico system;
  quelli successivi restano al loro posto come user (cache del server
  preservata: turno N prefisso esatto del turno N+1).
- Modelli ausiliari (memorie, guardian-v2) = modello di sessione se il
  preferito gpt-* non e' nel catalogo.
- Ricerca web: crate web-tools, backend SearXNG con web_search e web_fetch
  (protezione SSRF); senza backend nessuno strumento web.
- Skill: rimossa openai-docs; skill-installer punta a git.difonzo.net.
- apply_patch accetta gli header @@ -a,b +c,d @@ dei diff unificati.
- Rimossi resti: request_plugin_install, AppsInstructions, --cyber-access-program,
  URL updater/realtime predefiniti.
- Fix: importazione sessioni con provider vuoto.
- Istruzioni di sistema invariate. Test: cancellati solo quelli del codice
  rimosso, test di sicurezza adattati; restano solo fallimenti d'ambiente.
- Prova reale su imeAI + SearXNG: risposta, modifica file, web_search,
  cache riusata, connessioni solo verso .25 e .57.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:11:45 +01:00

234 lines
7.1 KiB
Rust

use std::path::Path;
use anyhow::Result;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home);
Ok(cmd)
}
fn write_file_auth_config(codex_home: &Path) -> Result<()> {
std::fs::write(
codex_home.join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
Ok(())
}
fn read_auth_json(codex_home: &Path) -> Result<Value> {
let auth_json = std::fs::read_to_string(codex_home.join("auth.json"))?;
Ok(serde_json::from_str(&auth_json)?)
}
#[test]
fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let mut cmd = codex_command(codex_home.path())?;
let login = cmd
.args([
"-c",
"forced_login_method=\"api\"",
"login",
"--with-api-key",
])
.write_stdin("sk-test\n")
.assert()
.success();
insta::assert_snapshot!(String::from_utf8_lossy(&login.get_output().stderr), @r"
Reading API key from stdin...
API key saved. Authentication is checked when you send a request.
");
let auth = read_auth_json(codex_home.path())?;
assert_eq!(auth["OPENAI_API_KEY"], "sk-test");
assert!(auth.get("tokens").is_none());
assert!(auth.get("agent_identity").is_none());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
insta::assert_snapshot!(String::from_utf8_lossy(&status.get_output().stderr), @r"
API key configured - ***
Authentication is checked when you send a request.
");
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\"", "login"])
.assert()
.failure()
.stderr(contains("Only API key login is supported"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
for removed_flag in ["--device-auth", "--with-access-token"] {
codex_command(codex_home.path())?
.args(["login", removed_flag])
.write_stdin("token\n")
.assert()
.failure()
.stderr(contains("unexpected argument"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
}
Ok(())
}
#[test]
fn api_key_auth_commands_work_when_log_dir_is_unavailable() -> Result<()> {
let codex_home = TempDir::new()?;
let log_dir = codex_home.path().join("unavailable-logs");
std::fs::write(&log_dir, "not a directory")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!("cli_auth_credentials_store = \"file\"\nlog_dir = {log_dir:?}\n"),
)?;
codex_command(codex_home.path())?
.args(["login", "--with-api-key"])
.write_stdin("sk-test\n")
.assert()
.success()
.stderr(contains("Warning: failed to create login log directory"));
assert_eq!(
read_auth_json(codex_home.path())?["OPENAI_API_KEY"],
"sk-test"
);
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success()
.stderr(contains("API key"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn login_status_reports_auth_storage_errors() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(codex_home.path().join("auth.json"), "{invalid json")?;
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Error checking login status:"));
Ok(())
}
#[test]
fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
},
}))?,
)?;
codex_command(codex_home.path())?
.env_remove("CODEX_API_KEY")
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Not logged in"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn provider_api_key_login_uses_private_file_store_and_never_prints_the_key() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"provider_api_key_store = \"file\"\n\
model_provider = \"imeai\"\n\
[model_providers.imeai]\n\
name = \"imeAI\"\n\
base_url = \"http://127.0.0.1:9/v1\"\n\
api_key = \"keyring\"\n",
)?;
let secret = "sk-provider-secret-0123456789";
let login = codex_command(codex_home.path())?
.args(["login", "--provider", "imeai", "--with-api-key"])
.write_stdin(format!("{secret}\n"))
.assert()
.success();
let stderr = String::from_utf8_lossy(&login.get_output().stderr).to_string();
assert!(
stderr.contains("API key for `imeai` saved in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
let path = codex_home.path().join("provider_api_keys.json");
let stored: Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
assert_eq!(stored, json!({ "imeai": secret }));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path)?.permissions().mode() & 0o777,
0o600
);
}
// The shared stored key is untouched.
assert!(!codex_home.path().join("auth.json").exists());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
let stderr = String::from_utf8_lossy(&status.get_output().stderr).to_string();
assert!(
stderr.contains("Provider `imeai`: API key stored in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
codex_command(codex_home.path())?
.args(["logout", "--provider", "imeai"])
.assert()
.success()
.stderr(contains("Removed the stored API key for `imeai`"));
assert!(!path.exists());
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains(
"Provider `imeai`: no API key stored (codex login --provider imeai --with-api-key)",
));
Ok(())
}