M3.1: PHP detection and pinned Phpactor download
- crates/lsp toolchain: PHP from php.executable or PATH, `php -v` with a 5 s timeout and capped output, version parsing (proptest), PHP >= 8.2. - Pinned Phpactor 2026.06.25.0 (SHA-256 832510fe...59e9); newer releases need ext-posix and do not start on Windows. - Download with ureq + rustls (ring, OS roots via rustls-native-certs): HTTPS only, 32 MiB cap, SHA-256 verified before an atomic write, retry with backoff. Tests use a local HTTP server only. - Engine: settings php.executable, phpactor.path, phpactor.autoDownload (bool and string setting kinds), toolchain.status, toolchain.downloadPhpactor, toolchainChanged, notifications; worker thread off the engine lock, results via the pump. Downloads only after the host calls Engine::allow_downloads (the desktop does). - Docs: architecture Toolchain section (network access, D15), G6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
78709dd76b
commit
50f36cce8b
23 changed files with 2577 additions and 10 deletions
|
|
@ -10,12 +10,14 @@
|
|||
//! - [`types`]: the LSP structures the client parses (diagnostics,
|
||||
//! locations, workspace edits), read leniently and capped.
|
||||
//! - [`uri`]: `file:` URIs from and to paths.
|
||||
//! - [`toolchain`]: the user's PHP and the pinned, verified Phpactor PHAR.
|
||||
|
||||
mod capabilities;
|
||||
mod documents;
|
||||
mod error;
|
||||
pub mod jsonrpc;
|
||||
mod server;
|
||||
pub mod toolchain;
|
||||
pub mod types;
|
||||
pub mod uri;
|
||||
|
||||
|
|
|
|||
533
crates/lsp/src/toolchain/download.rs
Normal file
533
crates/lsp/src/toolchain/download.rs
Normal file
|
|
@ -0,0 +1,533 @@
|
|||
//! Downloading a pinned file: the only network access in Lutra.
|
||||
//!
|
||||
//! [`install`] fetches a [`Source`] over HTTP(S) with `ureq` (pure Rust,
|
||||
//! `rustls` with the `ring` provider, certificates checked against the
|
||||
//! operating system's trusted roots, loaded with `rustls-native-certs`). The body is
|
||||
//! read into memory with a size cap and its SHA-256 compared with the
|
||||
//! pinned hash; only a verified body is written, atomically
|
||||
//! ([`lutra_vfs::write_atomic`]), so the target path never holds a partial
|
||||
//! or unverified file. [`install_with_retry`] retries network failures and
|
||||
//! server errors with exponential backoff; a hash mismatch, an oversized
|
||||
//! body or a client error is final.
|
||||
|
||||
use std::fmt;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use ureq::tls::{Certificate, RootCerts, TlsConfig, TlsProvider};
|
||||
|
||||
/// Connect timeout of one attempt.
|
||||
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Time limit of one attempt, from connecting to the last byte.
|
||||
pub const ATTEMPT_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// Most redirects followed (GitHub release assets redirect once).
|
||||
pub const MAX_REDIRECTS: u32 = 5;
|
||||
|
||||
/// A SHA-256 digest.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Hash([u8; 32]);
|
||||
|
||||
impl Hash {
|
||||
/// Parses 64 hex digits, either case; `None` otherwise.
|
||||
pub fn from_hex(hex: &str) -> Option<Self> {
|
||||
let bytes = hex.as_bytes();
|
||||
if bytes.len() != 64 {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
let (pairs, _) = bytes.as_chunks::<2>();
|
||||
for (slot, [hi, lo]) in out.iter_mut().zip(pairs) {
|
||||
*slot = nibble(*hi)?.checked_mul(16)?.checked_add(nibble(*lo)?)?;
|
||||
}
|
||||
Some(Self(out))
|
||||
}
|
||||
|
||||
/// Lowercase hex.
|
||||
pub fn to_hex(&self) -> String {
|
||||
self.0.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// The SHA-256 of `bytes`.
|
||||
pub fn of_bytes(bytes: &[u8]) -> Self {
|
||||
let mut context = ring::digest::Context::new(&ring::digest::SHA256);
|
||||
context.update(bytes);
|
||||
Self::of(context)
|
||||
}
|
||||
|
||||
/// Finishes a SHA-256 `context`.
|
||||
pub fn of(context: ring::digest::Context) -> Self {
|
||||
let digest = context.finish();
|
||||
let mut out = [0u8; 32];
|
||||
for (slot, b) in out.iter_mut().zip(digest.as_ref()) {
|
||||
*slot = *b;
|
||||
}
|
||||
Self(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Hash {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Hash({})", self.to_hex())
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of one hex digit.
|
||||
fn nibble(c: u8) -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What to download and how to check it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Source {
|
||||
/// The URL.
|
||||
pub url: String,
|
||||
/// The version it holds, for messages and the install path.
|
||||
pub version: String,
|
||||
/// The expected SHA-256 of the body.
|
||||
pub sha256: Hash,
|
||||
/// Refuse plain HTTP, also on redirects. Always set for real downloads;
|
||||
/// tests against a local server clear it.
|
||||
pub https_only: bool,
|
||||
}
|
||||
|
||||
/// Why a download failed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum DownloadError {
|
||||
/// Connecting, TLS, a timeout or reading the body failed.
|
||||
#[error("network error: {0}")]
|
||||
Network(String),
|
||||
/// The server answered with an error status.
|
||||
#[error("the server answered HTTP {0}")]
|
||||
Status(u16),
|
||||
/// The body is larger than allowed.
|
||||
#[error("the file is larger than {0} bytes")]
|
||||
TooLarge(u64),
|
||||
/// The body does not have the pinned hash; it was not written.
|
||||
#[error("SHA-256 mismatch: expected {expected}, got {actual}; the file was discarded")]
|
||||
HashMismatch {
|
||||
/// The pinned hash, hex.
|
||||
expected: String,
|
||||
/// The hash of what arrived, hex.
|
||||
actual: String,
|
||||
},
|
||||
/// Writing the verified file failed.
|
||||
#[error("cannot write {path}: {reason}")]
|
||||
Write {
|
||||
/// The target.
|
||||
path: String,
|
||||
/// The I/O error.
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl DownloadError {
|
||||
/// Whether another attempt may succeed: network errors, server errors
|
||||
/// (5xx), 408 and 429.
|
||||
pub fn retryable(&self) -> bool {
|
||||
match self {
|
||||
Self::Network(_) => true,
|
||||
Self::Status(code) => *code >= 500 || *code == 408 || *code == 429,
|
||||
Self::TooLarge(_) | Self::HashMismatch { .. } | Self::Write { .. } => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How often and how patiently to retry.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Retry {
|
||||
/// Attempts in total, at least 1.
|
||||
pub attempts: u32,
|
||||
/// Wait before the second attempt; doubled for each further one.
|
||||
pub first_delay: Duration,
|
||||
/// Longest wait between attempts.
|
||||
pub max_delay: Duration,
|
||||
}
|
||||
|
||||
impl Default for Retry {
|
||||
/// Four attempts, waiting 2 s, 4 s and 8 s in between.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
attempts: 4,
|
||||
first_delay: Duration::from_secs(2),
|
||||
max_delay: Duration::from_secs(30),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a successful download took.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Stats {
|
||||
/// Bytes written.
|
||||
pub bytes: u64,
|
||||
/// Attempts made, the successful one included.
|
||||
pub attempts: u32,
|
||||
/// Wall time from the first attempt to the written file.
|
||||
pub elapsed: Duration,
|
||||
}
|
||||
|
||||
/// Downloads `source` to `dest` with [`install`], retrying retryable
|
||||
/// failures as `retry` says. `on_retry` is called before each wait with the
|
||||
/// attempt that failed (1-based) and its error.
|
||||
///
|
||||
/// # Errors
|
||||
/// The last attempt's error, or the first final one.
|
||||
pub fn install_with_retry(
|
||||
source: &Source,
|
||||
dest: &Path,
|
||||
max_size: u64,
|
||||
retry: Retry,
|
||||
mut on_retry: impl FnMut(u32, &DownloadError),
|
||||
) -> Result<Stats, DownloadError> {
|
||||
let started = Instant::now();
|
||||
let attempts = retry.attempts.max(1);
|
||||
let mut delay = retry.first_delay;
|
||||
let mut attempt = 1u32;
|
||||
loop {
|
||||
match install(source, dest, max_size) {
|
||||
Ok(bytes) => {
|
||||
return Ok(Stats {
|
||||
bytes,
|
||||
attempts: attempt,
|
||||
elapsed: started.elapsed(),
|
||||
});
|
||||
}
|
||||
Err(e) if e.retryable() && attempt < attempts => {
|
||||
on_retry(attempt, &e);
|
||||
std::thread::sleep(delay.min(retry.max_delay));
|
||||
delay = delay.saturating_mul(2);
|
||||
attempt = attempt.saturating_add(1);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads `source`, checks the size and the SHA-256, creates `dest`'s
|
||||
/// directory and writes the verified bytes to `dest` atomically. Nothing is
|
||||
/// written unless the hash matches.
|
||||
///
|
||||
/// # Returns
|
||||
/// The number of bytes written.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`DownloadError`] saying what failed.
|
||||
pub fn install(source: &Source, dest: &Path, max_size: u64) -> Result<u64, DownloadError> {
|
||||
let bytes = fetch(source, max_size)?;
|
||||
let actual = Hash::of_bytes(&bytes);
|
||||
if actual != source.sha256 {
|
||||
return Err(DownloadError::HashMismatch {
|
||||
expected: source.sha256.to_hex(),
|
||||
actual: actual.to_hex(),
|
||||
});
|
||||
}
|
||||
let write_error = |reason: String| DownloadError::Write {
|
||||
path: dest.display().to_string(),
|
||||
reason,
|
||||
};
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| write_error(e.to_string()))?;
|
||||
}
|
||||
lutra_vfs::write_atomic(dest, &bytes).map_err(|e| write_error(e.to_string()))?;
|
||||
Ok(u64::try_from(bytes.len()).unwrap_or(u64::MAX))
|
||||
}
|
||||
|
||||
/// Fetches the body of `source.url`, at most `max_size` bytes.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`DownloadError::Network`], [`DownloadError::Status`] or
|
||||
/// [`DownloadError::TooLarge`].
|
||||
pub fn fetch(source: &Source, max_size: u64) -> Result<Vec<u8>, DownloadError> {
|
||||
let agent = agent(source.https_only);
|
||||
let response = agent.get(&source.url).call().map_err(|e| match e {
|
||||
ureq::Error::StatusCode(code) => DownloadError::Status(code),
|
||||
other => DownloadError::Network(other.to_string()),
|
||||
})?;
|
||||
let mut body = response.into_body();
|
||||
if body.content_length().is_some_and(|n| n > max_size) {
|
||||
return Err(DownloadError::TooLarge(max_size));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
body.as_reader()
|
||||
.take(max_size.saturating_add(1))
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| DownloadError::Network(e.to_string()))?;
|
||||
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > max_size {
|
||||
return Err(DownloadError::TooLarge(max_size));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The HTTP agent: rustls with the `ring` provider, the operating system's
|
||||
/// trusted root certificates ([`native_roots`]), the timeouts and redirect
|
||||
/// limit above, proxies from the environment (`HTTPS_PROXY`, `ALL_PROXY`,
|
||||
/// `NO_PROXY`), no cookies.
|
||||
///
|
||||
/// `rustls-platform-verifier` would ask the OS verifier directly, but it
|
||||
/// pulls `webpki-root-certs` (CDLA-Permissive-2.0, outside Lutra's allowed
|
||||
/// licences) into the graph, so the roots are loaded instead.
|
||||
fn agent(https_only: bool) -> ureq::Agent {
|
||||
let tls = TlsConfig::builder()
|
||||
.provider(TlsProvider::Rustls)
|
||||
.root_certs(RootCerts::Specific(Arc::new(native_roots())))
|
||||
.unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.build();
|
||||
ureq::Agent::config_builder()
|
||||
.https_only(https_only)
|
||||
.max_redirects(MAX_REDIRECTS)
|
||||
.timeout_connect(Some(CONNECT_TIMEOUT))
|
||||
.timeout_global(Some(ATTEMPT_TIMEOUT))
|
||||
.user_agent(concat!("Lutra/", env!("CARGO_PKG_VERSION")))
|
||||
.tls_config(tls)
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
/// The trusted root certificates of the operating system (Windows
|
||||
/// certificate store, macOS keychain, the usual files on Linux or
|
||||
/// `SSL_CERT_FILE` / `SSL_CERT_DIR`). Certificates that fail to load are
|
||||
/// skipped; with none at all every HTTPS connection fails with a
|
||||
/// certificate error, which is reported as a network error.
|
||||
fn native_roots() -> Vec<Certificate<'static>> {
|
||||
rustls_native_certs::load_native_certs()
|
||||
.certs
|
||||
.iter()
|
||||
.map(|der| Certificate::from_der(der.as_ref()).to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// One canned answer of the test server.
|
||||
enum Reply {
|
||||
/// A full response with status and body.
|
||||
Ok(Vec<u8>),
|
||||
/// An error status without body.
|
||||
Status(u16),
|
||||
/// A 200 response without Content-Length whose body ends with the
|
||||
/// connection.
|
||||
Unsized(Vec<u8>),
|
||||
}
|
||||
|
||||
/// A local HTTP server that answers each request with the next reply
|
||||
/// and counts requests. No real network.
|
||||
fn serve(replies: Vec<Reply>) -> (String, Arc<Mutex<usize>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}/phpactor.phar", listener.local_addr().unwrap());
|
||||
let count = Arc::new(Mutex::new(0));
|
||||
let seen = count.clone();
|
||||
std::thread::spawn(move || {
|
||||
for reply in replies {
|
||||
let Ok((mut stream, _)) = listener.accept() else {
|
||||
return;
|
||||
};
|
||||
let mut head = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !head.ends_with(b"\r\n\r\n") && stream.read(&mut byte).unwrap_or(0) == 1 {
|
||||
head.push(byte[0]);
|
||||
}
|
||||
*seen.lock().unwrap() += 1;
|
||||
let _ = match reply {
|
||||
Reply::Ok(body) => stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.and_then(|_| stream.write_all(&body)),
|
||||
Reply::Status(code) => stream.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 {code} Nope\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
.as_bytes(),
|
||||
),
|
||||
Reply::Unsized(body) => stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n")
|
||||
.and_then(|_| stream.write_all(&body)),
|
||||
};
|
||||
}
|
||||
});
|
||||
(url, count)
|
||||
}
|
||||
|
||||
fn source(url: &str, body: &[u8]) -> Source {
|
||||
Source {
|
||||
url: url.to_string(),
|
||||
version: "9.9.9".into(),
|
||||
sha256: Hash::of_bytes(body),
|
||||
https_only: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn quick() -> Retry {
|
||||
Retry {
|
||||
attempts: 3,
|
||||
first_delay: Duration::from_millis(10),
|
||||
max_delay: Duration::from_millis(20),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_round_trip_and_rejects() {
|
||||
let h = Hash::of_bytes(b"abc");
|
||||
assert_eq!(
|
||||
h.to_hex(),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||
);
|
||||
assert_eq!(Hash::from_hex(&h.to_hex().to_uppercase()), Some(h));
|
||||
assert_eq!(Hash::from_hex("ab"), None);
|
||||
assert_eq!(Hash::from_hex(&"g".repeat(64)), None);
|
||||
assert_eq!(Hash::from_hex(&"é".repeat(32)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_a_verified_file() {
|
||||
let body = b"<?php // phar".repeat(1000);
|
||||
let (url, count) = serve(vec![Reply::Ok(body.clone())]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("tools/phpactor/9.9.9/phpactor.phar");
|
||||
let stats =
|
||||
install_with_retry(&source(&url, &body), &dest, 1 << 20, quick(), |_, _| {}).unwrap();
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), body);
|
||||
assert_eq!(stats.bytes, body.len() as u64);
|
||||
assert_eq!(stats.attempts, 1);
|
||||
assert_eq!(*count.lock().unwrap(), 1);
|
||||
let names: Vec<_> = std::fs::read_dir(dest.parent().unwrap())
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["phpactor.phar"], "no temporary files left");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_mismatch_is_rejected_and_keeps_the_old_file() {
|
||||
let (url, count) = serve(vec![Reply::Ok(b"tampered".to_vec())]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("phpactor.phar");
|
||||
std::fs::write(&dest, b"old").unwrap();
|
||||
let err = install_with_retry(
|
||||
&source(&url, b"genuine"),
|
||||
&dest,
|
||||
1 << 20,
|
||||
quick(),
|
||||
|_, _| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, DownloadError::HashMismatch { .. }), "{err:?}");
|
||||
assert!(!err.retryable());
|
||||
assert_eq!(*count.lock().unwrap(), 1, "a mismatch is not retried");
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), b"old");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_target_stays_missing_on_mismatch() {
|
||||
let (url, _) = serve(vec![Reply::Ok(b"tampered".to_vec())]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("v/phpactor.phar");
|
||||
assert!(install(&source(&url, b"genuine"), &dest, 1 << 20).is_err());
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retries_server_errors_with_backoff() {
|
||||
let body = b"payload".to_vec();
|
||||
let (url, count) = serve(vec![
|
||||
Reply::Status(503),
|
||||
Reply::Status(500),
|
||||
Reply::Ok(body.clone()),
|
||||
]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("phpactor.phar");
|
||||
let mut failures = Vec::new();
|
||||
let stats = install_with_retry(&source(&url, &body), &dest, 1 << 20, quick(), |n, e| {
|
||||
failures.push((n, e.clone()))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(stats.attempts, 3);
|
||||
assert_eq!(*count.lock().unwrap(), 3);
|
||||
assert_eq!(
|
||||
failures,
|
||||
vec![
|
||||
(1, DownloadError::Status(503)),
|
||||
(2, DownloadError::Status(500))
|
||||
]
|
||||
);
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_errors_are_final() {
|
||||
let (url, count) = serve(vec![Reply::Status(404), Reply::Status(404)]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let err = install_with_retry(
|
||||
&source(&url, b"x"),
|
||||
&dir.path().join("p"),
|
||||
1 << 20,
|
||||
quick(),
|
||||
|_, _| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, DownloadError::Status(404));
|
||||
assert_eq!(*count.lock().unwrap(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_cap_applies_with_and_without_content_length() {
|
||||
let body = vec![b'x'; 2048];
|
||||
let (url, _) = serve(vec![Reply::Ok(body.clone()), Reply::Unsized(body.clone())]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("phpactor.phar");
|
||||
let src = source(&url, &body);
|
||||
assert_eq!(
|
||||
install(&src, &dest, 1024),
|
||||
Err(DownloadError::TooLarge(1024))
|
||||
);
|
||||
assert_eq!(
|
||||
install(&src, &dest, 1024),
|
||||
Err(DownloadError::TooLarge(1024))
|
||||
);
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_only_refuses_plain_http_without_a_request() {
|
||||
let (url, count) = serve(vec![Reply::Ok(b"x".to_vec())]);
|
||||
let mut src = source(&url, b"x");
|
||||
src.https_only = true;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let err = install(&src, &dir.path().join("p"), 1 << 20).unwrap_err();
|
||||
assert!(matches!(err, DownloadError::Network(_)), "{err:?}");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert_eq!(*count.lock().unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_server_is_a_network_error() {
|
||||
let port = TcpListener::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let src = source(&format!("http://127.0.0.1:{port}/x"), b"x");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let err = install(&src, &dir.path().join("p"), 1 << 20).unwrap_err();
|
||||
assert!(err.retryable(), "{err:?}");
|
||||
}
|
||||
}
|
||||
118
crates/lsp/src/toolchain/mod.rs
Normal file
118
crates/lsp/src/toolchain/mod.rs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
//! The toolchain Lutra needs for PHP language features: the user's PHP
|
||||
//! and a Phpactor PHAR (owner decision D15).
|
||||
//!
|
||||
//! - [`php`] finds the PHP executable (a setting or `PATH`), runs `php -v`
|
||||
//! with a timeout and checks the version. Its output is untrusted.
|
||||
//! - [`phpactor`] knows the pinned Phpactor release (version, URL,
|
||||
//! SHA-256), where Lutra keeps it (`<data_dir>/tools/phpactor/<version>/`)
|
||||
//! and verifies a file against the pinned hash.
|
||||
//! - [`download`] fetches a file over HTTPS (pure Rust: `ureq` with
|
||||
//! `rustls`, roots from the operating system), capped in size, verified
|
||||
//! against a SHA-256 before it is written atomically, with retries and
|
||||
//! backoff. It is the only network access in Lutra; nothing in this crate
|
||||
//! starts it on its own.
|
||||
//! - [`has_php_files`] tells whether a project contains PHP code, which is
|
||||
//! when Lutra downloads Phpactor.
|
||||
//!
|
||||
//! Every function here blocks (process runs, file hashing, network), so
|
||||
//! callers run them off the engine lock.
|
||||
|
||||
pub mod download;
|
||||
pub mod php;
|
||||
pub mod phpactor;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Directory names [`has_php_files`] does not descend into.
|
||||
const SKIPPED_DIRS: &[&str] = &["vendor", "node_modules", ".git", ".idea", "var", "storage"];
|
||||
|
||||
/// Most directory entries [`has_php_files`] looks at.
|
||||
pub const MAX_SCAN_ENTRIES: usize = 20_000;
|
||||
|
||||
/// Deepest directory level [`has_php_files`] looks at; the root is 0.
|
||||
pub const MAX_SCAN_DEPTH: usize = 6;
|
||||
|
||||
/// Whether `root` contains PHP code: a `composer.json` at the root or a file
|
||||
/// with a PHP extension (`php`, `phtml`, `inc`) within [`MAX_SCAN_DEPTH`]
|
||||
/// levels, looking at no more than [`MAX_SCAN_ENTRIES`] entries. Hidden
|
||||
/// directories, dependency and cache directories ([`SKIPPED_DIRS`]) and
|
||||
/// symbolic links are skipped. Directories that cannot be read are skipped
|
||||
/// too, since the answer only decides whether a download is worth it.
|
||||
pub fn has_php_files(root: &Path) -> bool {
|
||||
if root.join("composer.json").is_file() {
|
||||
return true;
|
||||
}
|
||||
let mut queue = std::collections::VecDeque::from([(root.to_path_buf(), 0usize)]);
|
||||
let mut seen = 0usize;
|
||||
while let Some((dir, depth)) = queue.pop_front() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
seen = seen.saturating_add(1);
|
||||
if seen > MAX_SCAN_ENTRIES {
|
||||
return false;
|
||||
}
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if kind.is_file() && is_php_name(&name) {
|
||||
return true;
|
||||
}
|
||||
if kind.is_dir()
|
||||
&& depth < MAX_SCAN_DEPTH
|
||||
&& !name.starts_with('.')
|
||||
&& !SKIPPED_DIRS.contains(&name.as_ref())
|
||||
{
|
||||
queue.push_back((entry.path(), depth.saturating_add(1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether a file name has a PHP extension, ignoring case.
|
||||
fn is_php_name(name: &str) -> bool {
|
||||
let Some((_, ext)) = name.rsplit_once('.') else {
|
||||
return false;
|
||||
};
|
||||
["php", "phtml", "inc"]
|
||||
.iter()
|
||||
.any(|e| ext.eq_ignore_ascii_case(e))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_php_files_and_composer_projects() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert!(!has_php_files(dir.path()));
|
||||
std::fs::create_dir_all(dir.path().join("vendor/x")).unwrap();
|
||||
std::fs::write(dir.path().join("vendor/x/a.php"), "<?php").unwrap();
|
||||
std::fs::write(dir.path().join("readme.md"), "hi").unwrap();
|
||||
assert!(!has_php_files(dir.path()), "vendor is skipped");
|
||||
std::fs::create_dir_all(dir.path().join("src/App")).unwrap();
|
||||
std::fs::write(dir.path().join("src/App/User.PHP"), "<?php").unwrap();
|
||||
assert!(has_php_files(dir.path()));
|
||||
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::write(other.path().join("composer.json"), "{}").unwrap();
|
||||
assert!(has_php_files(other.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_at_the_depth_cap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut deep = dir.path().to_path_buf();
|
||||
for i in 0..=MAX_SCAN_DEPTH {
|
||||
deep.push(format!("d{i}"));
|
||||
}
|
||||
std::fs::create_dir_all(&deep).unwrap();
|
||||
std::fs::write(deep.join("a.php"), "<?php").unwrap();
|
||||
assert!(!has_php_files(dir.path()));
|
||||
}
|
||||
}
|
||||
371
crates/lsp/src/toolchain/php.rs
Normal file
371
crates/lsp/src/toolchain/php.rs
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
//! Finding the user's PHP and checking its version.
|
||||
//!
|
||||
//! Lutra does not ship PHP (owner decision D15). The executable comes from
|
||||
//! the `php.executable` setting or from `PATH`; [`detect`] runs `php -v`
|
||||
//! with a timeout and parses the first line. The output is untrusted: it is
|
||||
//! read with a size cap, and anything that does not look like a PHP
|
||||
//! version line is an error, never a crash.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fmt;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Oldest PHP the pinned Phpactor release runs on
|
||||
/// ([`super::phpactor::VERSION`] declares `"php": "^8.2"` in its
|
||||
/// `composer.json`).
|
||||
pub const MIN_VERSION: PhpVersion = PhpVersion {
|
||||
major: 8,
|
||||
minor: 2,
|
||||
patch: 0,
|
||||
};
|
||||
|
||||
/// How long `php -v` may take.
|
||||
pub const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Most bytes of `php -v` output that are read.
|
||||
pub const MAX_OUTPUT: u64 = 64 * 1024;
|
||||
|
||||
/// A PHP version, `major.minor.patch`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct PhpVersion {
|
||||
/// Major version, e.g. 8.
|
||||
pub major: u32,
|
||||
/// Minor version, e.g. 4.
|
||||
pub minor: u32,
|
||||
/// Patch level, e.g. 24; 0 when the output had none.
|
||||
pub patch: u32,
|
||||
}
|
||||
|
||||
impl fmt::Display for PhpVersion {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
|
||||
}
|
||||
}
|
||||
|
||||
/// A PHP executable that runs and is new enough.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Php {
|
||||
/// The executable.
|
||||
pub path: PathBuf,
|
||||
/// Its version.
|
||||
pub version: PhpVersion,
|
||||
}
|
||||
|
||||
/// Why no usable PHP was found.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum PhpError {
|
||||
/// Neither the setting nor `PATH` names an existing executable.
|
||||
#[error("{0}")]
|
||||
NotFound(String),
|
||||
/// The executable could not be run, timed out or failed.
|
||||
#[error("{path}: {reason}")]
|
||||
Failed {
|
||||
/// The executable.
|
||||
path: PathBuf,
|
||||
/// What went wrong.
|
||||
reason: String,
|
||||
},
|
||||
/// `php -v` did not print a PHP version line.
|
||||
#[error("{path}: no PHP version in the output of php -v")]
|
||||
NoVersion {
|
||||
/// The executable.
|
||||
path: PathBuf,
|
||||
},
|
||||
/// The version is older than [`MIN_VERSION`].
|
||||
#[error("{path} is PHP {version}; Phpactor needs PHP {MIN_VERSION} or newer")]
|
||||
TooOld {
|
||||
/// The executable.
|
||||
path: PathBuf,
|
||||
/// Its version.
|
||||
version: PhpVersion,
|
||||
},
|
||||
}
|
||||
|
||||
impl PhpError {
|
||||
/// The executable the error is about, if one was found.
|
||||
pub fn path(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::NotFound(_) => None,
|
||||
Self::Failed { path, .. } | Self::NoVersion { path } | Self::TooOld { path, .. } => {
|
||||
Some(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The version found, for [`PhpError::TooOld`].
|
||||
pub fn version(&self) -> Option<PhpVersion> {
|
||||
match self {
|
||||
Self::TooOld { version, .. } => Some(*version),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds PHP and checks it: the `setting` (`php.executable`; empty means
|
||||
/// look in `PATH`), resolved with [`locate`], then `php -v` with
|
||||
/// [`PROBE_TIMEOUT`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`PhpError`] saying what is missing or wrong.
|
||||
pub fn detect(setting: &str) -> Result<Php, PhpError> {
|
||||
let path = locate(setting, std::env::var_os("PATH"))?;
|
||||
let output = run_version(&path, PROBE_TIMEOUT)?;
|
||||
let version =
|
||||
parse_version(&output).ok_or_else(|| PhpError::NoVersion { path: path.clone() })?;
|
||||
if version < MIN_VERSION {
|
||||
return Err(PhpError::TooOld { path, version });
|
||||
}
|
||||
Ok(Php { path, version })
|
||||
}
|
||||
|
||||
/// Resolves the PHP executable.
|
||||
///
|
||||
/// - `setting` is the `php.executable` value, trimmed. A value with a path
|
||||
/// separator must name an existing file. A bare name (`php8.3`) is looked
|
||||
/// up in `path_env` like the default.
|
||||
/// - Empty: `php` is looked up in `path_env` (on Windows `php.exe`, then
|
||||
/// `php.bat` and `php.cmd`).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`PhpError::NotFound`] with a message naming the setting.
|
||||
pub fn locate(setting: &str, path_env: Option<OsString>) -> Result<PathBuf, PhpError> {
|
||||
let setting = setting.trim();
|
||||
if setting.contains(['/', '\\']) {
|
||||
let path = PathBuf::from(setting);
|
||||
return if path.is_file() {
|
||||
Ok(path)
|
||||
} else {
|
||||
Err(PhpError::NotFound(format!(
|
||||
"php.executable {setting} is not a file"
|
||||
)))
|
||||
};
|
||||
}
|
||||
let name = if setting.is_empty() { "php" } else { setting };
|
||||
let dirs = path_env
|
||||
.map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
dirs.iter()
|
||||
.flat_map(|dir| candidates(name).into_iter().map(move |n| dir.join(n)))
|
||||
.find(|p| p.is_file())
|
||||
.ok_or_else(|| {
|
||||
PhpError::NotFound(format!(
|
||||
"{name} was not found in PATH; install PHP {MIN_VERSION} or newer or set php.executable"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// File names that run `name` on this platform.
|
||||
fn candidates(name: &str) -> Vec<String> {
|
||||
if cfg!(windows) && !name.contains('.') {
|
||||
["exe", "bat", "cmd"]
|
||||
.iter()
|
||||
.map(|ext| format!("{name}.{ext}"))
|
||||
.collect()
|
||||
} else {
|
||||
vec![name.to_string()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `path -v` and returns at most [`MAX_OUTPUT`] bytes of its standard
|
||||
/// output, killing it after `timeout`. On Windows no console window opens.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`PhpError::Failed`] if it cannot start, times out or exits with an
|
||||
/// error.
|
||||
pub fn run_version(path: &Path, timeout: Duration) -> Result<Vec<u8>, PhpError> {
|
||||
let failed = |reason: String| PhpError::Failed {
|
||||
path: path.to_path_buf(),
|
||||
reason,
|
||||
};
|
||||
let mut command = Command::new(path);
|
||||
command
|
||||
.arg("-v")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
hide_window(&mut command);
|
||||
let mut child = command.spawn().map_err(|e| failed(e.to_string()))?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| failed("no output pipe".into()))?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("lutra-php-probe".into())
|
||||
.spawn(move || {
|
||||
let mut out = Vec::new();
|
||||
let _ = stdout.take(MAX_OUTPUT).read_to_end(&mut out);
|
||||
let _ = tx.send(out);
|
||||
})
|
||||
.map_err(|e| failed(e.to_string()))?;
|
||||
let started = Instant::now();
|
||||
let deadline = started.checked_add(timeout).unwrap_or(started);
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) if Instant::now() >= deadline => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(failed(format!(
|
||||
"php -v did not finish within {} s",
|
||||
timeout.as_secs()
|
||||
)));
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(e) => return Err(failed(e.to_string())),
|
||||
}
|
||||
};
|
||||
let out = rx
|
||||
.recv_timeout(Duration::from_secs(1))
|
||||
.map_err(|_| failed("its output did not end".into()))?;
|
||||
if !status.success() {
|
||||
return Err(failed(format!("php -v exited with {status}")));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Keeps a console window from flashing up when a GUI app runs PHP on
|
||||
/// Windows (`CREATE_NO_WINDOW`).
|
||||
#[cfg(windows)]
|
||||
fn hide_window(command: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000);
|
||||
}
|
||||
|
||||
/// Nothing to hide outside Windows.
|
||||
#[cfg(not(windows))]
|
||||
fn hide_window(_command: &mut Command) {}
|
||||
|
||||
/// Finds the version in `php -v` output: the first line that starts with
|
||||
/// `PHP ` followed by `major.minor` and optionally `.patch`, such as
|
||||
/// `PHP 8.4.24 (cli) (built: …)` or `PHP 8.3.6-1ubuntu1 (cli)`. Lines before
|
||||
/// it (startup warnings) are skipped. Numbers that overflow, missing parts
|
||||
/// and invalid UTF-8 give `None` or are skipped, never a panic.
|
||||
pub fn parse_version(output: &[u8]) -> Option<PhpVersion> {
|
||||
let text = String::from_utf8_lossy(output);
|
||||
text.lines().find_map(|line| {
|
||||
let rest = line.trim_start().strip_prefix("PHP ")?;
|
||||
let token = rest.split_whitespace().next()?;
|
||||
let mut parts = token.splitn(3, '.');
|
||||
let major = number(parts.next()?)?;
|
||||
let minor = number(parts.next()?)?;
|
||||
let patch = match parts.next() {
|
||||
Some(p) => number(p)?,
|
||||
None => 0,
|
||||
};
|
||||
Some(PhpVersion {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The leading decimal digits of `part` as a number; `None` without digits
|
||||
/// or on overflow.
|
||||
fn number(part: &str) -> Option<u32> {
|
||||
let end = part
|
||||
.char_indices()
|
||||
.find(|(_, c)| !c.is_ascii_digit())
|
||||
.map_or(part.len(), |(i, _)| i);
|
||||
part.get(..end)?.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn v(major: u32, minor: u32, patch: u32) -> Option<PhpVersion> {
|
||||
Some(PhpVersion {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_real_outputs() {
|
||||
let windows = b"PHP 8.4.24 (cli) (built: Jul 29 2026 06:00:56) (ZTS Visual C++ 2022 x64)\r\nCopyright (c) The PHP Group\r\nZend Engine v4.4.24\r\n";
|
||||
assert_eq!(parse_version(windows), v(8, 4, 24));
|
||||
assert_eq!(
|
||||
parse_version(b"PHP 8.3.6-1ubuntu1.2 (cli) (built: Jan 1 2026)"),
|
||||
v(8, 3, 6)
|
||||
);
|
||||
assert_eq!(parse_version(b"PHP 8.5.0-dev (cli)"), v(8, 5, 0));
|
||||
assert_eq!(
|
||||
parse_version(b"PHP Warning: Module 'x' already loaded\nPHP 8.2.1 (cli)"),
|
||||
v(8, 2, 1)
|
||||
);
|
||||
assert_eq!(parse_version(b"PHP 8.1 (cli)"), v(8, 1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_versions() {
|
||||
assert_eq!(parse_version(b""), None);
|
||||
assert_eq!(parse_version(b"HHVM 4.0"), None);
|
||||
assert_eq!(parse_version(b"PHP x.y"), None);
|
||||
assert_eq!(parse_version(b"PHP 99999999999.1.1"), None);
|
||||
assert_eq!(parse_version(b"\xff\xfePHP"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_order_and_minimum() {
|
||||
assert!(v(8, 1, 30) < Some(MIN_VERSION));
|
||||
assert!(v(8, 2, 0) >= Some(MIN_VERSION));
|
||||
assert!(v(9, 0, 0) > Some(MIN_VERSION));
|
||||
assert_eq!(MIN_VERSION.to_string(), "8.2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locate_reports_the_setting() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let err = locate("", Some(dir.path().as_os_str().to_owned())).unwrap_err();
|
||||
assert!(err.to_string().contains("php.executable"), "{err}");
|
||||
let missing = dir.path().join("nope").join("php");
|
||||
let err = locate(missing.to_str().unwrap(), None).unwrap_err();
|
||||
assert!(matches!(err, PhpError::NotFound(_)));
|
||||
|
||||
let name = if cfg!(windows) { "php.exe" } else { "php" };
|
||||
std::fs::write(dir.path().join(name), b"").unwrap();
|
||||
let found = locate(" ", Some(dir.path().as_os_str().to_owned())).unwrap();
|
||||
assert_eq!(found, dir.path().join(name));
|
||||
let given = dir.path().join(name);
|
||||
assert_eq!(locate(given.to_str().unwrap(), None).unwrap(), given);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_program_that_is_not_php_fails_cleanly() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fake = dir
|
||||
.path()
|
||||
.join(if cfg!(windows) { "php.exe" } else { "php" });
|
||||
std::fs::write(&fake, b"not a program").unwrap();
|
||||
let err = run_version(&fake, Duration::from_secs(2)).unwrap_err();
|
||||
assert!(matches!(err, PhpError::Failed { .. }), "{err:?}");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn never_panics_on_random_output(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
|
||||
let _ = parse_version(&bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_any_formatted_version(
|
||||
noise in "[a-zA-Z :]{0,40}",
|
||||
major in 0u32..100,
|
||||
minor in 0u32..100,
|
||||
patch in 0u32..1000,
|
||||
suffix in "(-[a-z0-9.]{1,10})?",
|
||||
) {
|
||||
let text = format!("{noise}\nPHP {major}.{minor}.{patch}{suffix} (cli)\nCopyright");
|
||||
prop_assert_eq!(parse_version(text.as_bytes()), v(major, minor, patch));
|
||||
}
|
||||
}
|
||||
}
|
||||
142
crates/lsp/src/toolchain/phpactor.rs
Normal file
142
crates/lsp/src/toolchain/phpactor.rs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
//! The pinned Phpactor release and where Lutra keeps it.
|
||||
//!
|
||||
//! Pinned release: **phpactor 2026.06.25.0** (MIT), the PHAR asset of the
|
||||
//! official GitHub release:
|
||||
//!
|
||||
//! - URL: <https://github.com/phpactor/phpactor/releases/download/2026.06.25.0/phpactor.phar>
|
||||
//! - SHA-256: `832510fe4cdaf27ba056b8cb66a779d18352585c74fdaac54e45a37b589559e9`
|
||||
//! - Size: 4,474,352 bytes.
|
||||
//!
|
||||
//! The hash was computed from a download on 2026-10-17 and matches the
|
||||
//! asset digest GitHub publishes for the release. The newer releases
|
||||
//! (2026.06.23.0, 2026.07.22.0, 2026.10.07.0) declare `ext-posix` as a
|
||||
//! requirement, an extension PHP on Windows does not have, so they refuse to
|
||||
//! start there; 2026.06.25.0 is the newest release without it. It needs
|
||||
//! PHP 8.2 or newer ([`super::php::MIN_VERSION`]).
|
||||
//!
|
||||
//! Updating the pin is a deliberate change: replace [`VERSION`], [`URL`],
|
||||
//! [`SHA256`] and [`SIZE`] together after checking the new PHAR's hash and
|
||||
//! that it runs on Windows, macOS and Linux PHP builds.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::download::{Hash, Source};
|
||||
|
||||
/// The pinned Phpactor version.
|
||||
pub const VERSION: &str = "2026.06.25.0";
|
||||
|
||||
/// Where the pinned PHAR is downloaded from.
|
||||
pub const URL: &str =
|
||||
"https://github.com/phpactor/phpactor/releases/download/2026.06.25.0/phpactor.phar";
|
||||
|
||||
/// SHA-256 of the pinned PHAR, lowercase hex.
|
||||
pub const SHA256: &str = "832510fe4cdaf27ba056b8cb66a779d18352585c74fdaac54e45a37b589559e9";
|
||||
|
||||
/// Size of the pinned PHAR in bytes.
|
||||
pub const SIZE: u64 = 4_474_352;
|
||||
|
||||
/// Largest PHAR Lutra downloads or verifies; a download that grows past it
|
||||
/// is aborted.
|
||||
pub const MAX_SIZE: u64 = 32 * 1024 * 1024;
|
||||
|
||||
/// File name of the PHAR inside its version directory.
|
||||
pub const FILE_NAME: &str = "phpactor.phar";
|
||||
|
||||
/// The pinned release as a download source (HTTPS only).
|
||||
///
|
||||
/// # Errors
|
||||
/// A message if [`SHA256`] is not valid hex, which a unit test rules out.
|
||||
pub fn pinned() -> Result<Source, String> {
|
||||
Ok(Source {
|
||||
url: URL.to_string(),
|
||||
version: VERSION.to_string(),
|
||||
sha256: Hash::from_hex(SHA256).ok_or("the pinned SHA-256 is not valid hex")?,
|
||||
https_only: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where Lutra keeps a managed Phpactor of `version`:
|
||||
/// `<data_dir>/tools/phpactor/<version>/phpactor.phar`.
|
||||
pub fn managed_path(data_dir: &Path, version: &str) -> PathBuf {
|
||||
data_dir
|
||||
.join("tools")
|
||||
.join("phpactor")
|
||||
.join(version)
|
||||
.join(FILE_NAME)
|
||||
}
|
||||
|
||||
/// Whether the file at `path` has the SHA-256 `expected`. Files larger than
|
||||
/// [`MAX_SIZE`] never match.
|
||||
///
|
||||
/// # Errors
|
||||
/// The I/O error if the file cannot be read; a missing file is
|
||||
/// `ErrorKind::NotFound`.
|
||||
pub fn verify(path: &Path, expected: &Hash) -> io::Result<bool> {
|
||||
let file = File::open(path)?;
|
||||
if file.metadata()?.len() > MAX_SIZE {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut hasher = ring::digest::Context::new(&ring::digest::SHA256);
|
||||
let mut reader = file.take(MAX_SIZE);
|
||||
let mut chunk = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = reader.read(&mut chunk)?;
|
||||
let Some(read) = chunk.get(..n) else {
|
||||
break;
|
||||
};
|
||||
if read.is_empty() {
|
||||
break;
|
||||
}
|
||||
hasher.update(read);
|
||||
}
|
||||
Ok(Hash::of(hasher) == *expected)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pinned_source_is_valid() {
|
||||
let source = pinned().unwrap();
|
||||
assert_eq!(source.sha256.to_hex(), SHA256);
|
||||
assert!(
|
||||
source
|
||||
.url
|
||||
.starts_with("https://github.com/phpactor/phpactor/releases/download/")
|
||||
);
|
||||
assert!(source.url.contains(VERSION));
|
||||
assert!(source.https_only);
|
||||
const { assert!(SIZE < MAX_SIZE) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_path_layout() {
|
||||
let p = managed_path(Path::new("data"), "1.2.3");
|
||||
assert_eq!(
|
||||
p,
|
||||
Path::new("data")
|
||||
.join("tools")
|
||||
.join("phpactor")
|
||||
.join("1.2.3")
|
||||
.join("phpactor.phar")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verifies_by_hash() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("x.phar");
|
||||
std::fs::write(&file, b"abc").unwrap();
|
||||
let abc =
|
||||
Hash::from_hex("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
.unwrap();
|
||||
assert!(verify(&file, &abc).unwrap());
|
||||
std::fs::write(&file, b"abd").unwrap();
|
||||
assert!(!verify(&file, &abc).unwrap());
|
||||
let err = verify(&dir.path().join("missing"), &abc).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::NotFound);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue