Skip to main content

brep_plm/api/
scripts.rs

1//! The administrator's script editor: list, read, write and delete the files
2//! in the scripts directory, and test-run a function.
3//!
4//! Every route needs the admin group. The directory stays the source of truth
5//! — these routes read and write those same files, so an
6//! edit here shows up in `git status` and a `git pull` shows up here.
7//!
8//! # A test run is a real run
9//!
10//! `POST /api/scripts/run` calls the function with the server's full host
11//! bindings, as the signed-in admin. Nothing is sandboxed: a test run of an
12//! `afterRelease` that posts to the ERP really posts to the ERP, and a
13//! `plm.updatePart` really updates the part. The page says so beside the
14//! button.
15
16use axum::extract::{Path, State};
17use axum::http::HeaderMap;
18use axum::response::Response;
19use axum::Json;
20use serde::{Deserialize, Serialize};
21use serde_json::Value;
22
23use super::{blocking, ok_seq, require_admin, Shared};
24use crate::scripting::{self, HookDoc, HookResult, ScriptFile, HOOKS};
25use crate::Error;
26
27#[derive(Debug, Serialize)]
28pub struct Listing {
29    /// Where the files are, so an admin knows what to put under git.
30    pub dir: String,
31    pub files: Vec<ScriptFile>,
32    pub hooks: &'static [HookDoc],
33}
34
35pub async fn list(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Listing>, Error> {
36    require_admin(&db, &headers)?;
37    Ok(Json(Listing {
38        dir: db.scripts().dir().display().to_string(),
39        files: db.scripts().list(),
40        hooks: HOOKS,
41    }))
42}
43
44#[derive(Debug, Serialize)]
45pub struct FileText {
46    pub path: String,
47    pub text: String,
48}
49
50pub async fn read(
51    State(db): State<Shared>,
52    headers: HeaderMap,
53    Path(path): Path<String>,
54) -> Result<Json<FileText>, Error> {
55    require_admin(&db, &headers)?;
56    let text = db
57        .scripts()
58        .source(&path)?
59        .ok_or_else(|| Error::not_found("script"))?;
60    Ok(Json(FileText { path, text: text.to_string() }))
61}
62
63/// Write a script. The body is the file's text, verbatim.
64pub async fn write(
65    State(db): State<Shared>,
66    headers: HeaderMap,
67    Path(path): Path<String>,
68    body: String,
69) -> Result<Response, Error> {
70    require_admin(&db, &headers)?;
71    editor_allowed(&db)?;
72    db.scripts().write(&path, &body)?;
73    db.record("script-write", script_entity(&path), format!("{} bytes", body.len()));
74    Ok(ok_seq(&db))
75}
76
77pub async fn remove(
78    State(db): State<Shared>,
79    headers: HeaderMap,
80    Path(path): Path<String>,
81) -> Result<Response, Error> {
82    require_admin(&db, &headers)?;
83    editor_allowed(&db)?;
84    db.scripts().delete(&path)?;
85    db.record("script-delete", script_entity(&path), "");
86    Ok(ok_seq(&db))
87}
88
89#[derive(Debug, Deserialize)]
90pub struct RunRequest {
91    /// The file to run, and the name its messages use.
92    pub path: String,
93    /// Run this text instead of the saved file — the editor's unsaved buffer.
94    #[serde(default)]
95    pub source: Option<String>,
96    pub function: String,
97    #[serde(default)]
98    pub input: Value,
99}
100
101#[derive(Debug, Serialize)]
102pub struct RunResult {
103    /// The function returned.
104    pub ok: bool,
105    pub value: Value,
106    /// Why it refused, when it did — the message a user would see.
107    pub error: Option<String>,
108    pub logs: Vec<String>,
109    pub millis: u128,
110}
111
112pub async fn run(
113    State(db): State<Shared>,
114    headers: HeaderMap,
115    Json(request): Json<RunRequest>,
116) -> Result<Json<RunResult>, Error> {
117    let user = require_admin(&db, &headers)?;
118    editor_allowed(&db)?;
119    let function = request.function.trim().to_string();
120    if function.is_empty() || !function.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') {
121        return Err(Error::bad_request("name the function to run"));
122    }
123    // A test run is a real run with the full host API, so it is on the record
124    // before it starts — even one that never returns.
125    db.record(
126        "script-run",
127        script_entity(&request.path),
128        format!(
129            "{}() {}",
130            function,
131            if request.source.is_some() { "from the editor's text" } else { "from the saved file" }
132        ),
133    );
134    let result = blocking(move || {
135        let started = std::time::Instant::now();
136        let outcome = match request.source {
137            Some(source) => {
138                db.scripts().resolve(&request.path)?;
139                scripting::run_source(&db, &user, &source, &request.path, &function, &request.input)
140            }
141            None => scripting::run(&db, &user, &request.path, &function, &request.input)?,
142        };
143        let millis = started.elapsed().as_millis();
144        Ok(match outcome {
145            HookResult::Absent => {
146                return Err(Error::not_found(format!("script '{}'", request.path)));
147            }
148            HookResult::Returned(success) => RunResult {
149                ok: true,
150                value: success.value,
151                error: None,
152                logs: success.logs,
153                millis,
154            },
155            HookResult::Refused(failure) => RunResult {
156                ok: false,
157                value: Value::Null,
158                error: Some(failure.message),
159                logs: failure.logs,
160                millis,
161            },
162        })
163    })
164    .await?;
165    Ok(Json(result))
166}
167
168/// Refuse an edit or a test run while the in-browser editor is off
169/// ([`crate::model::Settings::script_editor_enabled`], or the server's
170/// `--lock-script-editor`). Listing and reading stay open: the scripts are
171/// still live, and an admin can see what runs.
172fn editor_allowed(db: &crate::db::Db) -> Result<(), Error> {
173    if db.script_editor_allowed() {
174        return Ok(());
175    }
176    Err(Error::forbidden(if db.security().config.lock_script_editor {
177        "the in-browser script editor is locked off on this server — edit the scripts directory on the host"
178    } else {
179        "the in-browser script editor is turned off in Settings — edit the scripts directory on the host, or turn it back on"
180    }))
181}
182
183fn script_entity(path: &str) -> crate::model::EntityRef {
184    crate::model::EntityRef { kind: "script".into(), id: path.to_string(), label: path.to_string(), part_id: String::new() }
185}