Parte "sicurezza" della fase 3 di aKode (e39aae00), senza le funzioni di imeAI:
- via i provider integrati openai, amazon-bedrock, amazon-bedrock-runtime e gcp
(crate model-provider: moduli amazon_bedrock, gcp, chatgpt_base_url; login Bedrock;
onboarding Bedrock/GCP; richieste app-server di setup cloud);
- nessun URL predefinito verso api.openai.com / chatgpt.com: un provider senza
base_url non viene mai contattato; senza model_provider configurato exec e TUI
mostrano come scriverne uno in config.toml (NO_MODEL_PROVIDER_CONFIGURED_ERROR);
- via la skill openai-docs, la sample skill-installer (scaricava da github.com/openai/skills),
request_plugin_install, AppsInstructions, URL predefiniti di realtime e updater;
- test di sicurezza adattati (provider "mock" al posto di quello integrato), non cancellati.
Restano fuori da questo commit (categoria F/D/E, non portate): chiave per provider nel
portachiavi, modelli da /models, unione dei messaggi di sistema, crate web-tools e
SearXNG, header @@ in apply_patch, modello ausiliario, tool function per apply_patch.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
314 lines
9.9 KiB
Rust
314 lines
9.9 KiB
Rust
//! CLI login commands and their direct-user observability surfaces.
|
|
//!
|
|
//! The TUI path already installs a broader tracing stack with feedback, OpenTelemetry, and other
|
|
//! interactive-session layers. Direct `codex login` intentionally does less: it preserves the
|
|
//! existing stderr/browser UX and adds only a small file-backed tracing layer for login-specific
|
|
//! targets. Keeping that setup local avoids pulling the TUI's session-oriented logging machinery
|
|
//! into a one-shot CLI command while still producing a durable `codex-login.log` artifact that
|
|
//! support can request from users.
|
|
|
|
use codex_core::config::Config;
|
|
use codex_login::login_with_api_key;
|
|
use codex_protocol::auth::AuthMode;
|
|
use codex_protocol::config_types::ForcedLoginMethod;
|
|
use codex_utils_cli::CliConfigOverrides;
|
|
use std::fs::OpenOptions;
|
|
use std::io::IsTerminal;
|
|
use std::io::Read;
|
|
use tracing_appender::non_blocking;
|
|
use tracing_appender::non_blocking::WorkerGuard;
|
|
use tracing_subscriber::EnvFilter;
|
|
use tracing_subscriber::Layer;
|
|
use tracing_subscriber::layer::SubscriberExt;
|
|
use tracing_subscriber::util::SubscriberInitExt;
|
|
|
|
const API_KEY_LOGIN_DISABLED_MESSAGE: &str =
|
|
"API key login is disabled by the configured login restrictions.";
|
|
const API_KEY_AUTHENTICATION_NOTICE: &str = "Authentication is checked when you send a request.";
|
|
const DEFAULT_LOGIN_LOG_FILTER: &str =
|
|
"codex_cli=info,codex_core=info,codex_login=info,codex_otel::auth_storage=warn";
|
|
|
|
/// Installs a small file-backed tracing layer for direct `codex login` flows.
|
|
///
|
|
/// This deliberately duplicates a narrow slice of the TUI logging setup instead of reusing it
|
|
/// wholesale. The TUI stack includes session-oriented layers that are valuable for interactive
|
|
/// runs but unnecessary for a one-shot login command. Keeping the direct CLI path local lets this
|
|
/// command produce a durable `codex-login.log` artifact without coupling it to the TUI's broader
|
|
/// telemetry and feedback initialization.
|
|
fn init_login_file_logging(config: &Config) -> Option<WorkerGuard> {
|
|
let log_dir = match codex_core::config::log_dir(config) {
|
|
Ok(log_dir) => log_dir,
|
|
Err(err) => {
|
|
eprintln!("Warning: failed to resolve login log directory: {err}");
|
|
return None;
|
|
}
|
|
};
|
|
|
|
if let Err(err) = std::fs::create_dir_all(&log_dir) {
|
|
eprintln!(
|
|
"Warning: failed to create login log directory {}: {err}",
|
|
log_dir.display()
|
|
);
|
|
return None;
|
|
}
|
|
|
|
let mut log_file_opts = OpenOptions::new();
|
|
log_file_opts.create(true).append(true);
|
|
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
log_file_opts.mode(0o600);
|
|
}
|
|
|
|
let log_path = log_dir.join("codex-login.log");
|
|
let log_file = match log_file_opts.open(&log_path) {
|
|
Ok(log_file) => log_file,
|
|
Err(err) => {
|
|
eprintln!(
|
|
"Warning: failed to open login log file {}: {err}",
|
|
log_path.display()
|
|
);
|
|
return None;
|
|
}
|
|
};
|
|
|
|
let (non_blocking, guard) = non_blocking(log_file);
|
|
let env_filter = EnvFilter::try_from_default_env()
|
|
.unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER));
|
|
let file_layer = tracing_subscriber::fmt::layer()
|
|
.with_writer(non_blocking)
|
|
.with_target(true)
|
|
.with_ansi(false)
|
|
.with_filter(env_filter);
|
|
|
|
// Direct `codex login` otherwise relies on ephemeral stderr and browser output.
|
|
// Persist the same login targets to a file so support can inspect auth failures
|
|
// without reproducing them through TUI or app-server.
|
|
if let Err(err) = tracing_subscriber::registry().with(file_layer).try_init() {
|
|
eprintln!(
|
|
"Warning: failed to initialize login log file {}: {err}",
|
|
log_path.display()
|
|
);
|
|
return None;
|
|
}
|
|
|
|
Some(guard)
|
|
}
|
|
|
|
/// Remote managed configuration (config server / cloud bundles) is not
|
|
/// supported in aKode: requirements that demand it cannot be satisfied.
|
|
async fn sign_in_to_config_server_and_reload_config(
|
|
_config: &mut Config,
|
|
_cli_config_overrides: &CliConfigOverrides,
|
|
) -> std::io::Result<()> {
|
|
Err(std::io::Error::new(
|
|
std::io::ErrorKind::Unsupported,
|
|
"remote managed configuration is not supported in aKode",
|
|
))
|
|
}
|
|
|
|
fn finish_login(result: std::io::Result<()>) -> ! {
|
|
match result {
|
|
Ok(_) => std::process::exit(0),
|
|
Err(e) => {
|
|
eprintln!("Error logging in: {e}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub async fn run_login_with_api_key(
|
|
cli_config_overrides: CliConfigOverrides,
|
|
api_key: String,
|
|
) -> ! {
|
|
let config = load_managed_login_config_or_exit(cli_config_overrides).await;
|
|
let _login_log_guard = init_login_file_logging(&config);
|
|
tracing::info!("starting api key login flow");
|
|
|
|
if !config
|
|
.auth_config()
|
|
.is_login_method_allowed(ForcedLoginMethod::Api)
|
|
{
|
|
eprintln!("{API_KEY_LOGIN_DISABLED_MESSAGE}");
|
|
std::process::exit(1);
|
|
}
|
|
|
|
match login_with_api_key(
|
|
&config.codex_home,
|
|
&api_key,
|
|
config.cli_auth_credentials_store_mode,
|
|
config.auth_keyring_backend_kind(),
|
|
) {
|
|
Ok(_) => {
|
|
eprintln!("API key saved. {API_KEY_AUTHENTICATION_NOTICE}");
|
|
std::process::exit(0);
|
|
}
|
|
Err(e) => {
|
|
eprintln!("Error logging in: {e}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn read_api_key_from_stdin() -> String {
|
|
read_stdin_secret(
|
|
"--with-api-key expects the API key on stdin. Try piping it, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`.",
|
|
"Reading API key from stdin...",
|
|
"No API key provided via stdin.",
|
|
)
|
|
}
|
|
|
|
fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_message: &str) -> String {
|
|
let mut stdin = std::io::stdin();
|
|
|
|
if stdin.is_terminal() {
|
|
eprintln!("{terminal_message}");
|
|
std::process::exit(1);
|
|
}
|
|
|
|
eprintln!("{reading_message}");
|
|
|
|
let mut buffer = String::new();
|
|
if let Err(err) = stdin.read_to_string(&mut buffer) {
|
|
eprintln!("Failed to read stdin: {err}");
|
|
std::process::exit(1);
|
|
}
|
|
|
|
let secret = buffer.trim().to_string();
|
|
if secret.is_empty() {
|
|
eprintln!("{empty_message}");
|
|
std::process::exit(1);
|
|
}
|
|
|
|
secret
|
|
}
|
|
|
|
/// Login using the OAuth device code flow.
|
|
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
|
|
let config = load_config_or_exit(cli_config_overrides).await;
|
|
|
|
let auth_config = config.auth_config();
|
|
match auth_config
|
|
.load_auth(/*enable_codex_api_key_env*/ false)
|
|
.await
|
|
{
|
|
Ok(Some(auth)) => match auth.auth_mode() {
|
|
AuthMode::ApiKey => match auth.get_token() {
|
|
Ok(api_key) => {
|
|
eprintln!("API key configured - {}", safe_format_key(&api_key));
|
|
eprintln!("{API_KEY_AUTHENTICATION_NOTICE}");
|
|
std::process::exit(0);
|
|
}
|
|
Err(e) => {
|
|
eprintln!("Unexpected error retrieving API key: {e}");
|
|
std::process::exit(1);
|
|
}
|
|
},
|
|
AuthMode::Headers => {
|
|
unreachable!("header auth cannot be loaded from auth storage")
|
|
}
|
|
},
|
|
Ok(None) => {
|
|
eprintln!("Not logged in");
|
|
std::process::exit(1);
|
|
}
|
|
Err(err) => {
|
|
eprintln!("Error checking login status: {err}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
|
|
let config = load_config_or_exit(cli_config_overrides).await;
|
|
let logged_out = match codex_login::logout(
|
|
&config.codex_home,
|
|
config.cli_auth_credentials_store_mode,
|
|
config.auth_keyring_backend_kind(),
|
|
) {
|
|
Ok(logged_out) => logged_out,
|
|
Err(err) => {
|
|
eprintln!("Error logging out: {err}");
|
|
std::process::exit(1);
|
|
}
|
|
};
|
|
|
|
if logged_out {
|
|
eprintln!("Successfully logged out");
|
|
} else {
|
|
eprintln!("Not logged in");
|
|
}
|
|
std::process::exit(0);
|
|
}
|
|
|
|
async fn load_managed_login_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
|
|
let mut config = load_config_or_exit(cli_config_overrides.clone()).await;
|
|
if config
|
|
.config_layer_stack
|
|
.requirements_toml()
|
|
.requires_remote_config()
|
|
&& let Err(error) =
|
|
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await
|
|
{
|
|
finish_login(Err(error));
|
|
}
|
|
config
|
|
}
|
|
|
|
async fn load_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
|
|
let cli_overrides = match cli_config_overrides.parse_overrides() {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
eprintln!("Error parsing -c overrides: {e}");
|
|
std::process::exit(1);
|
|
}
|
|
};
|
|
|
|
match Config::load_with_cli_overrides(cli_overrides).await {
|
|
Ok(config) => match config.auth_config().validate() {
|
|
Ok(()) => config,
|
|
Err(e) => {
|
|
eprintln!("Error loading configuration: {e}");
|
|
std::process::exit(1);
|
|
}
|
|
},
|
|
Err(e) => {
|
|
eprintln!("Error loading configuration: {e}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn safe_format_key(key: &str) -> String {
|
|
if key.len() <= 13 {
|
|
return "***".to_string();
|
|
}
|
|
let prefix = &key[..8];
|
|
let suffix = &key[key.len() - 5..];
|
|
format!("{prefix}***{suffix}")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "login_storage_tests.rs"]
|
|
mod storage_tests;
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use pretty_assertions::assert_eq;
|
|
|
|
use super::safe_format_key;
|
|
|
|
#[test]
|
|
fn formats_long_key() {
|
|
let key = "sk-proj-1234567890ABCDE";
|
|
assert_eq!(safe_format_key(key), "sk-proj-***ABCDE");
|
|
}
|
|
|
|
#[test]
|
|
fn short_key_returns_stars() {
|
|
let key = "sk-proj-12345";
|
|
assert_eq!(safe_format_key(key), "***");
|
|
}
|
|
}
|