mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
Merge branch 'main' into feat/auth-callback-handler
# Conflicts: # apps/gpauth/src/cli.rs # apps/gpclient/src/cli.rs # apps/gpclient/src/connect/credential.rs # apps/gpclient/src/connect/gateway.rs # crates/gpapi/src/process/auth_launcher.rs
This commit is contained in:
14 files changed
+792
-93
No files matched your search
+243
-11
@@ -1,33 +1,139 @@
|
||||
use std::io::{self, Write};
|
||||
|
||||
use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
|
||||
use log::Level;
|
||||
|
||||
use crate::error::PortalError;
|
||||
use crate::{
|
||||
error::PortalError,
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
|
||||
pub mod args;
|
||||
|
||||
pub trait Args {
|
||||
fn fix_openssl(&self) -> bool;
|
||||
fn ignore_tls_errors(&self) -> bool;
|
||||
|
||||
/// How this program renders its logs.
|
||||
///
|
||||
/// Required rather than defaulted: a default would let an implementor drop
|
||||
/// the override and silently report failures as prose to a caller that asked
|
||||
/// for JSON, with nothing — not even a warning — to catch it.
|
||||
fn log_format(&self) -> LogFormat;
|
||||
}
|
||||
|
||||
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
|
||||
eprintln!("\nError: {:?}", err);
|
||||
|
||||
/// Suggestions for re-running the command, for failures that have a known
|
||||
/// workaround. Empty when there is nothing useful to say — including when the
|
||||
/// relevant option is already in use.
|
||||
fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
let Some(err) = err.downcast_ref::<PortalError>() else {
|
||||
return;
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let command_line = || {
|
||||
let argv = std::env::args().collect::<Vec<_>>();
|
||||
let program = argv.first().cloned().unwrap_or_default();
|
||||
let rest = argv.get(1..).map(|rest| rest.join(" ")).unwrap_or_default();
|
||||
|
||||
(program, rest)
|
||||
};
|
||||
|
||||
// The blank line between the sentence and the command is part of the output
|
||||
// users already see; keep it exactly.
|
||||
let mut hints = Vec::new();
|
||||
|
||||
if err.is_legacy_openssl_error() && !args.fix_openssl() {
|
||||
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--fix-openssl` option to work around this issue, e.g.:\n\n{program} --fix-openssl {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
if err.is_tls_error() && !args.ignore_tls_errors() {
|
||||
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n\n{program} --ignore-tls-errors {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
hints
|
||||
}
|
||||
|
||||
/// Write one message to `w` the way `format` asks for.
|
||||
///
|
||||
/// Text is emitted exactly as it always was, so existing output does not move.
|
||||
/// JSON is written directly rather than through the `log` macros, because these
|
||||
/// are reports rather than log lines: they must survive `--quiet`, which would
|
||||
/// otherwise discard the only explanation of a failed run.
|
||||
///
|
||||
/// The record is rendered into one buffer and written once. `serde_json`'s
|
||||
/// `Display` would otherwise reach the stream in dozens of fragments, and any
|
||||
/// process sharing this stderr — the spawned authenticator, a connect script —
|
||||
/// could land a line inside a half-written record.
|
||||
fn write_message<W: Write>(w: &mut W, format: LogFormat, level: Level, message: &str) -> io::Result<()> {
|
||||
match format {
|
||||
LogFormat::Text => writeln!(w, "{message}"),
|
||||
LogFormat::Json => {
|
||||
// Callers pass the exact text line, blank-line padding included, so the
|
||||
// text form does not move. A record carries its own separation.
|
||||
let message = message.trim_start_matches('\n');
|
||||
let mut line = Vec::new();
|
||||
|
||||
write_json_record(
|
||||
&mut line,
|
||||
&log::Record::builder()
|
||||
.level(level)
|
||||
.target(module_path!())
|
||||
.args(format_args!("{message}"))
|
||||
.build(),
|
||||
)?;
|
||||
|
||||
w.write_all(&line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Report a user-facing line that is not a log record — a note, a warning, or
|
||||
/// advice about what to try next.
|
||||
///
|
||||
/// Callers used `eprintln!` directly, which in JSON mode drops prose into a
|
||||
/// stream the caller is parsing a line at a time. Routing them here keeps one
|
||||
/// answer to "how does this program emit a user-facing line", and leaves the
|
||||
/// text form byte-for-byte unchanged.
|
||||
pub fn report(format: LogFormat, level: Level, message: &str) {
|
||||
let _ = write_message(&mut io::stderr().lock(), format, level, message);
|
||||
}
|
||||
|
||||
fn write_failure<W: Write>(w: &mut W, format: LogFormat, err: &anyhow::Error, hints: &[String]) -> io::Result<()> {
|
||||
match format {
|
||||
LogFormat::Text => {
|
||||
writeln!(w, "\nError: {err:?}")?;
|
||||
|
||||
for hint in hints {
|
||||
writeln!(w, "\n{hint}\n")?;
|
||||
}
|
||||
}
|
||||
LogFormat::Json => {
|
||||
write_message(w, format, Level::Error, &format!("{err:?}"))?;
|
||||
|
||||
for hint in hints {
|
||||
write_message(w, format, Level::Error, hint)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_error_to<W: Write>(w: &mut W, err: anyhow::Error, args: &impl Args) -> io::Result<()> {
|
||||
let hints = retry_hints(&err, args);
|
||||
|
||||
write_failure(w, args.log_format(), &err, &hints)
|
||||
}
|
||||
|
||||
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
|
||||
// Nothing useful to do if stderr itself is gone.
|
||||
let _ = handle_error_to(&mut io::stderr().lock(), err, args);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -79,3 +185,129 @@ impl ToVerboseArg for Level {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::anyhow;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestArgs {
|
||||
fix_openssl: bool,
|
||||
ignore_tls_errors: bool,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl Args for TestArgs {
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
/// The seam that matters: `handle_error` must ask the args which format to
|
||||
/// use. Testing the writer alone would leave a version that always reports as
|
||||
/// prose passing every test.
|
||||
#[test]
|
||||
fn handle_error_honours_the_requested_format() {
|
||||
let args = TestArgs {
|
||||
log_format: LogFormat::Json,
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
|
||||
handle_error_to(&mut out, anyhow!(PortalError::TlsError), &args).expect("writing to a Vec cannot fail");
|
||||
|
||||
let out = String::from_utf8(out).expect("output should be UTF-8");
|
||||
for line in out.lines() {
|
||||
serde_json::from_str::<serde_json::Value>(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
|
||||
}
|
||||
assert!(!out.is_empty(), "the failure must be reported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tls_failure_suggests_ignoring_tls_errors() {
|
||||
let hints = retry_hints(&anyhow!(PortalError::TlsError), &TestArgs::default());
|
||||
|
||||
assert_eq!(hints.len(), 1, "expected one hint, got {hints:?}");
|
||||
assert!(hints[0].contains("--ignore-tls-errors"), "got {:?}", hints[0]);
|
||||
// The command sits on its own line after a blank one, as it always has.
|
||||
assert!(
|
||||
hints[0].contains("e.g.:\n\n"),
|
||||
"blank line before the command: {:?}",
|
||||
hints[0]
|
||||
);
|
||||
}
|
||||
|
||||
/// Suggesting an option the user already passed is noise, and in JSON mode it
|
||||
/// would be an extra record on every failed run.
|
||||
#[test]
|
||||
fn no_hint_when_the_option_is_already_in_use() {
|
||||
let args = TestArgs {
|
||||
ignore_tls_errors: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(retry_hints(&anyhow!(PortalError::TlsError), &args).is_empty());
|
||||
}
|
||||
|
||||
/// Most failures have no known workaround; inventing advice for them would
|
||||
/// mislead.
|
||||
#[test]
|
||||
fn no_hints_for_an_unrelated_error() {
|
||||
let hints = retry_hints(&anyhow!("something else went wrong"), &TestArgs::default());
|
||||
|
||||
assert!(hints.is_empty(), "got {hints:?}");
|
||||
}
|
||||
|
||||
fn failure_output(format: LogFormat) -> String {
|
||||
let hints = vec!["Re-run it with the `--ignore-tls-errors` option".to_string()];
|
||||
let mut out = Vec::new();
|
||||
|
||||
write_failure(&mut out, format, &anyhow!(PortalError::TlsError), &hints).expect("writing to a Vec cannot fail");
|
||||
|
||||
String::from_utf8(out).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
/// The failure is the program's final report, so in JSON mode it must be one
|
||||
/// more record on the same stream — and it must not be filtered away, which
|
||||
/// is why it does not go through the log macros. A run that fails silently is
|
||||
/// worse than one that fails noisily.
|
||||
#[test]
|
||||
fn the_failure_is_reported_as_records() {
|
||||
let out = failure_output(LogFormat::Json);
|
||||
let lines: Vec<_> = out.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "expected the error and its hint: {out:?}");
|
||||
|
||||
for line in lines {
|
||||
let v: serde_json::Value = serde_json::from_str(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
|
||||
assert_eq!(v["level"], "ERROR");
|
||||
}
|
||||
}
|
||||
|
||||
/// The format has to be honoured, not merely available: reporting the failure
|
||||
/// as prose to a caller that asked for JSON is the defect this whole flag
|
||||
/// exists to remove.
|
||||
#[test]
|
||||
fn the_format_decides_how_the_failure_is_written() {
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(failure_output(LogFormat::Json).lines().next().unwrap()).is_ok(),
|
||||
"json mode must not emit prose"
|
||||
);
|
||||
|
||||
let text = failure_output(LogFormat::Text);
|
||||
assert!(text.starts_with("\nError: "), "text mode keeps its shape: {text:?}");
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(text.trim()).is_err(),
|
||||
"text mode must not emit JSON: {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub mod credential;
|
||||
pub mod error;
|
||||
pub mod gateway;
|
||||
pub mod gp_params;
|
||||
pub mod log_format;
|
||||
pub mod os_profile;
|
||||
pub mod params;
|
||||
pub mod portal;
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Machine-readable log output.
|
||||
//!
|
||||
//! The default human format is fine at a terminal, but tools that drive
|
||||
//! gpclient headless have to parse it — and end up matching on prose, including
|
||||
//! text that comes from dependencies rather than from this project. JSON lines
|
||||
//! give those callers fields instead.
|
||||
//!
|
||||
//! This module deliberately depends only on `log` and `serde_json`, so every
|
||||
//! binary can use it without pulling in a logging backend, and so the rendering
|
||||
//! can be tested without installing a global logger.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
use chrono::{SecondsFormat, Utc};
|
||||
use serde_json::json;
|
||||
|
||||
/// How log records are rendered.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
|
||||
pub enum LogFormat {
|
||||
/// The human-readable default.
|
||||
#[default]
|
||||
Text,
|
||||
/// One JSON object per line.
|
||||
Json,
|
||||
}
|
||||
|
||||
impl LogFormat {
|
||||
/// The name this format is known by on a command line.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Text => "text",
|
||||
Self::Json => "json",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a [`log::Record`] to `w` as one JSON line, newline included.
|
||||
///
|
||||
/// This is the form a logging backend needs, and it writes into the buffer the
|
||||
/// backend already handed us rather than allocating a line to be copied. It
|
||||
/// takes a `Record` and a `Write` rather than any backend's own types, so `log`
|
||||
/// stays the only logging dependency here — with `env_logger`, this function
|
||||
/// *is* the format callback:
|
||||
///
|
||||
/// ```ignore
|
||||
/// // Not compiled as a doctest: env_logger is an optional dependency of this
|
||||
/// // crate, so it is not linked when the docs are built.
|
||||
/// env_logger::builder().format(write_json_record).init();
|
||||
/// ```
|
||||
pub fn write_json_record<W: Write>(w: &mut W, record: &log::Record) -> io::Result<()> {
|
||||
writeln!(
|
||||
w,
|
||||
"{}",
|
||||
json!({
|
||||
"timestamp": Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
|
||||
"level": record.level().as_str(),
|
||||
"target": record.target(),
|
||||
"message": record.args().to_string(),
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{DateTime, SubsecRound};
|
||||
use log::Level;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn parse(line: &str) -> serde_json::Value {
|
||||
serde_json::from_str(line).expect("each line must be valid JSON")
|
||||
}
|
||||
|
||||
fn write_record(record: &log::Record) -> String {
|
||||
let mut buf = Vec::new();
|
||||
write_json_record(&mut buf, record).expect("writing to a Vec cannot fail");
|
||||
String::from_utf8(buf).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
/// The fields a consumer is promised, taken off a `Record` as a backend
|
||||
/// hands it over.
|
||||
#[test]
|
||||
fn record_renders_the_expected_fields() {
|
||||
// Built inline: `format_args!` borrows its arguments for the statement it
|
||||
// appears in, so a `Record` held in a `let` would outlive them.
|
||||
let v = parse(&write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Error)
|
||||
.target("gpclient::connect")
|
||||
.args(format_args!("portal {} unreachable", "vpn.example.com"))
|
||||
.build(),
|
||||
));
|
||||
|
||||
assert_eq!(v["level"], "ERROR");
|
||||
assert_eq!(v["target"], "gpclient::connect");
|
||||
assert_eq!(v["message"], "portal vpn.example.com unreachable");
|
||||
}
|
||||
|
||||
/// Without a timestamp the JSON output would be strictly less informative
|
||||
/// than the text format it replaces, and a consumer could not order or
|
||||
/// correlate events.
|
||||
#[test]
|
||||
fn records_carry_a_utc_timestamp() {
|
||||
let before = Utc::now();
|
||||
let v = parse(&write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("t")
|
||||
.args(format_args!("connected"))
|
||||
.build(),
|
||||
));
|
||||
let after = Utc::now();
|
||||
|
||||
let ts = v["timestamp"].as_str().expect("timestamp must be a string");
|
||||
let parsed = DateTime::parse_from_rfc3339(ts)
|
||||
.unwrap_or_else(|e| panic!("timestamp must be RFC 3339: {ts:?} ({e})"))
|
||||
.with_timezone(&Utc);
|
||||
|
||||
assert!(ts.ends_with('Z'), "timestamp must be UTC, got {ts:?}");
|
||||
assert!(
|
||||
parsed >= before.trunc_subsecs(3) && parsed <= after,
|
||||
"timestamp {parsed} should be between {before} and {after}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The backend appends records to one stream, so each has to terminate its
|
||||
/// own line — exactly one, or the next record joins this one. A message
|
||||
/// containing a newline must be escaped into the JSON string rather than
|
||||
/// splitting the record in two.
|
||||
#[test]
|
||||
fn record_ends_with_a_single_newline() {
|
||||
let out = write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("t")
|
||||
.args(format_args!("first\nsecond"))
|
||||
.build(),
|
||||
);
|
||||
|
||||
assert!(out.ends_with('\n'), "record must terminate its line: {out:?}");
|
||||
assert_eq!(out.matches('\n').count(), 1, "record must be one line: {out:?}");
|
||||
assert_eq!(parse(&out)["message"], "first\nsecond", "the newline must survive");
|
||||
}
|
||||
|
||||
/// `as_str` is what gets passed to a child process on the command line, and
|
||||
/// clap parses that with the names from its own `ValueEnum` derive. If the
|
||||
/// two ever disagree, gpclient hands gpauth a value gpauth rejects.
|
||||
#[cfg(feature = "clap")]
|
||||
#[test]
|
||||
fn as_str_agrees_with_the_names_clap_parses() {
|
||||
use clap::ValueEnum;
|
||||
|
||||
for format in [LogFormat::Text, LogFormat::Json] {
|
||||
let clap_name = format
|
||||
.to_possible_value()
|
||||
.expect("every variant is selectable")
|
||||
.get_name()
|
||||
.to_owned();
|
||||
|
||||
assert_eq!(format.as_str(), clap_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,17 @@ use anyhow::bail;
|
||||
use log::{Level, Log, warn};
|
||||
use log_reload::{ReloadHandle, ReloadLog};
|
||||
|
||||
use crate::log_format::{LogFormat, write_json_record};
|
||||
|
||||
pub const LOG_BACKEND_ENV: &str = "GP_LOG_BACKEND";
|
||||
pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
|
||||
|
||||
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
||||
|
||||
pub fn init(level: Level, subsystem: &str, category: &str) {
|
||||
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if macos_unified_log_enabled() {
|
||||
if log_format == LogFormat::Text && macos_unified_log_enabled() {
|
||||
init_with_logger(level, MacosLogger::new(subsystem, category));
|
||||
return;
|
||||
}
|
||||
@@ -20,10 +22,19 @@ pub fn init(level: Level, subsystem: &str, category: &str) {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = (subsystem, category);
|
||||
|
||||
// Initialize the env_logger and global max level to trace, the logs will be
|
||||
// filtered by the outer logger
|
||||
let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build();
|
||||
init_with_logger(level, logger);
|
||||
init_with_logger(level, build_env_logger(log_format).build());
|
||||
}
|
||||
|
||||
fn build_env_logger(log_format: LogFormat) -> env_logger::Builder {
|
||||
let mut builder = env_logger::builder();
|
||||
// The outer reloadable logger owns filtering.
|
||||
builder.filter_level(log::LevelFilter::Trace);
|
||||
|
||||
if log_format == LogFormat::Json {
|
||||
builder.format(write_json_record);
|
||||
}
|
||||
|
||||
builder
|
||||
}
|
||||
|
||||
pub fn init_with_logger(level: Level, logger: impl Log + Send + Sync + 'static) {
|
||||
@@ -103,11 +114,51 @@ fn macos_log_level(level: Level) -> oslog::Level {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl Write for Captured {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_format_configures_the_env_logger() {
|
||||
let captured = Captured::default();
|
||||
let logger = build_env_logger(LogFormat::Json)
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("gpauth")
|
||||
.args(format_args!("authenticating"))
|
||||
.build(),
|
||||
);
|
||||
|
||||
let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
|
||||
assert_eq!(value["message"], "authenticating");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn info_logs_use_the_persistent_macos_level() {
|
||||
assert_eq!(macos_log_level(Level::Info) as u8, oslog::Level::Default as u8);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use std::{net::IpAddr, path::PathBuf, process::Stdio};
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
path::{Path, PathBuf},
|
||||
process::Stdio,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
@@ -6,7 +10,7 @@ use tokio::process::Command;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
|
||||
@@ -36,6 +40,7 @@ pub struct SamlAuthLauncher<'a> {
|
||||
browser: Option<&'a str>,
|
||||
browser_listen: Option<IpAddr>,
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
@@ -66,6 +71,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
browser: None,
|
||||
browser_listen: None,
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,18 +162,27 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Render the child's logs the same way as ours.
|
||||
///
|
||||
/// gpauth inherits this process's stderr, so both processes must use the same
|
||||
/// format to keep the stream consistent.
|
||||
pub fn log_format(mut self, log_format: LogFormat) -> Self {
|
||||
self.log_format = log_format;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let mut auth_cmd = Command::new(&program);
|
||||
/// The command line this launcher will run.
|
||||
///
|
||||
/// Split out from `launch` so a test can observe the argv the child actually
|
||||
/// receives: asserting on the builder's own fields would not catch an
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -241,10 +256,23 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
auth_cmd.arg("--browser-listen").arg(browser_listen.to_string());
|
||||
}
|
||||
|
||||
auth_cmd.arg("--log-format").arg(self.log_format.as_str());
|
||||
|
||||
if let Some(verbose) = self.verbose {
|
||||
auth_cmd.arg(verbose);
|
||||
}
|
||||
|
||||
auth_cmd
|
||||
}
|
||||
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let mut non_root_cmd = auth_cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
|
||||
@@ -297,6 +325,45 @@ mod tests {
|
||||
assert_eq!(launcher.client_version, Some("6.0.0"));
|
||||
}
|
||||
|
||||
fn child_args(launcher: SamlAuthLauncher) -> Vec<String> {
|
||||
launcher
|
||||
.build_command(Path::new("gpauth"))
|
||||
.as_std()
|
||||
.get_args()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
#[test]
|
||||
fn json_is_forwarded_to_the_child() {
|
||||
let args = child_args(SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Json));
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "json"]),
|
||||
"expected --log-format json in {args:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The launcher always passes the selected format so the parent and child
|
||||
/// cannot silently drift onto different output formats.
|
||||
#[test]
|
||||
fn text_is_forwarded_to_the_child() {
|
||||
for launcher in [
|
||||
SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Text),
|
||||
SamlAuthLauncher::new("portal.example.com"),
|
||||
] {
|
||||
let args = child_args(launcher);
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "text"]),
|
||||
"expected --log-format text in {args:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_options_are_stored() {
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com")
|
||||
|
||||
Reference in new issue
Block a user