use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use laravel::config::{Config, Env, Section};
use laravel::foundation::ServiceProvider;
use crate::gate::DevtoolsGate;
#[cfg(debug_assertions)]
use crate::gate::Gate;
#[derive(Clone, Section)]
#[non_exhaustive]
pub struct DevtoolsConfig {
#[env("DEVTOOLS_ENABLED")]
pub enabled: Enabled,
#[env("DEVTOOLS_ERROR_TEXT", default = false)]
pub error_text: bool,
#[env("DEVTOOLS_KEY")]
pub key: Option<DevtoolsKey>,
#[env("DEVTOOLS_LOCAL", default = true)]
pub local: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Enabled {
#[default]
Auto,
Off,
Required,
}
impl FromStr for Enabled {
type Err = ParseEnabledError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"true" => Ok(Self::Required),
"false" => Ok(Self::Off),
_ => Err(ParseEnabledError),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseEnabledError;
impl fmt::Display for ParseEnabledError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("expected `true` or `false`, or leave it unset")
}
}
impl std::error::Error for ParseEnabledError {}
#[derive(Clone)]
pub struct DevtoolsKey {
#[cfg(debug_assertions)]
key: Arc<str>,
}
impl DevtoolsKey {
pub fn new(key: impl Into<Arc<str>>) -> Self {
#[cfg(debug_assertions)]
{
Self { key: key.into() }
}
#[cfg(not(debug_assertions))]
{
drop(key);
Self {}
}
}
#[cfg(debug_assertions)]
pub(crate) fn expose(&self) -> &str {
&self.key
}
}
impl FromStr for DevtoolsKey {
type Err = std::convert::Infallible;
fn from_str(key: &str) -> Result<Self, Self::Err> {
Ok(Self::new(key))
}
}
impl fmt::Debug for DevtoolsKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("DevtoolsKey([masked])")
}
}
impl fmt::Debug for DevtoolsConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DevtoolsConfig")
.field("enabled", &self.enabled)
.field("error_text", &self.error_text)
.field("key", &self.key)
.field("local", &self.local)
.finish()
}
}
#[derive(Clone, Default)]
#[must_use]
pub struct DevtoolsServiceProvider {
#[cfg(debug_assertions)]
gate: Option<Gate>,
#[cfg(debug_assertions)]
crates: Vec<String>,
}
impl DevtoolsServiceProvider {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn is_active(config: &Config) -> bool {
#[cfg(debug_assertions)]
{
debug::runs(config) || debug::asked_in_tests(config)
}
#[cfg(not(debug_assertions))]
{
let _ = config;
false
}
}
pub fn with_gate(self, gate: impl DevtoolsGate) -> Self {
#[cfg(debug_assertions)]
{
Self {
gate: Some(Gate::Narrowing(Arc::new(gate))),
..self
}
}
#[cfg(not(debug_assertions))]
{
drop(gate);
self
}
}
pub fn with_admitting_gate(self, gate: impl DevtoolsGate) -> Self {
#[cfg(debug_assertions)]
{
Self {
gate: Some(Gate::Admitting(Arc::new(gate))),
..self
}
}
#[cfg(not(debug_assertions))]
{
drop(gate);
self
}
}
pub fn with_crates<I>(self, crates: I) -> Self
where
I: IntoIterator,
I::Item: Into<String>,
{
#[cfg(debug_assertions)]
{
let mut provider = self;
provider.crates.extend(crates.into_iter().map(Into::into));
provider
}
#[cfg(not(debug_assertions))]
{
drop(crates);
self
}
}
}
impl fmt::Debug for DevtoolsServiceProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("DevtoolsServiceProvider");
#[cfg(debug_assertions)]
debug.field(
"gate",
&self.gate.as_ref().map(|gate| match gate {
Gate::Narrowing(_) => "[narrowing]",
Gate::Admitting(_) => "[admitting]",
}),
);
#[cfg(debug_assertions)]
debug.field("crates", &self.crates);
debug.finish()
}
}
impl ServiceProvider for DevtoolsServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
#[cfg(debug_assertions)]
fn register(&self, app: &mut laravel::container::Registrar) {
debug::register(app, self.gate.clone(), &self.crates);
}
#[cfg(debug_assertions)]
fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
std::future::ready(debug::boot(app.config()))
}
#[cfg(not(debug_assertions))]
fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
warn_of_what_this_build_ignores(app.config().section::<DevtoolsConfig>());
std::future::ready(Ok(()))
}
}
#[cfg(not(debug_assertions))]
fn warn_of_what_this_build_ignores(section: &DevtoolsConfig) {
if section.enabled == Enabled::Required {
tracing::warn!(
"DEVTOOLS_ENABLED=true is ignored: this build has no developer tools, as it was built \
without debug assertions. Remove DEVTOOLS_ENABLED from this environment."
);
}
if section.key.is_some() {
tracing::warn!(
"DEVTOOLS_KEY is ignored: this build has no developer tools, as it was built without \
debug assertions. Remove the key from this environment."
);
}
}
#[cfg(debug_assertions)]
mod debug {
use std::fmt;
use laravel::config::Config;
use laravel::config::app::Environment;
use laravel::container::Registrar;
use super::{Arc, DevtoolsConfig, DevtoolsKey, Enabled};
use crate::collector::Collector;
use crate::file_store::FileStore;
use crate::gate::Gate;
use crate::http::Access;
use crate::store::Store;
const KEY_LENGTH: std::ops::RangeInclusive<usize> = 32..=laravel::hash::MAX_PASSWORD_BYTES;
pub(super) fn register(app: &mut Registrar, gate: Option<Gate>, crates: &[String]) {
let config = app.config();
if !runs(config) {
return;
}
let section = config.section::<DevtoolsConfig>();
let store = Arc::new(FileStore::new(config.app.storage_path("devtools")));
let collector = Collector::shared(Arc::clone(&store) as Arc<dyn Store>)
.with_error_text(section.error_text)
.with_crates(crates.iter().cloned());
let access = Access::new(section.key.clone(), section.local, gate);
crate::http::register(app, store, collector.key(), access);
app.logging().layer(collector);
}
pub(super) fn boot(config: &Config) -> laravel::Result<()> {
let environment = &config.app.env;
let section = config.section::<DevtoolsConfig>();
let required = section.enabled == Enabled::Required;
if required && !matches!(environment, Environment::Local | Environment::Testing) {
return Err(EnabledOutsideLocal(environment.clone()).into());
}
let key = section.key.as_ref().map(DevtoolsKey::expose);
if runs(config) && key.is_some_and(|key| !KEY_LENGTH.contains(&key.len())) {
return Err(KeyLength.into());
}
Ok(())
}
pub(super) fn runs(config: &Config) -> bool {
config.app.env.is_local() && enabled(config) != Enabled::Off
}
pub(super) fn asked_in_tests(config: &Config) -> bool {
config.app.env == Environment::Testing && enabled(config) == Enabled::Required
}
fn enabled(config: &Config) -> Enabled {
config
.get::<DevtoolsConfig>()
.map_or(Enabled::Off, |section| section.enabled)
}
#[derive(Debug)]
struct EnabledOutsideLocal(Environment);
impl fmt::Display for EnabledOutsideLocal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"DEVTOOLS_ENABLED=true, but the developer tools only run with APP_ENV=local, and \
this application runs with APP_ENV={}{}. Remove DEVTOOLS_ENABLED or set it to false.",
self.0.as_str(),
if matches!(self.0, Environment::Production) {
" (also what an unset APP_ENV means)"
} else {
""
}
)
}
}
impl std::error::Error for EnabledOutsideLocal {}
#[derive(Debug)]
struct KeyLength;
impl fmt::Display for KeyLength {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"DEVTOOLS_KEY must be between {} and {} bytes long. Generate one with \
`openssl rand -hex 24`.",
KEY_LENGTH.start(),
KEY_LENGTH.end()
)
}
}
impl std::error::Error for KeyLength {}
}