From bbced084b926feefcf1a53c8d3a2a6d9baebd1d8 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:08:45 +0000 Subject: [PATCH 1/5] feat(tomcat): add Web facet discovery, safe deployments and Java debug workflow --- .gitignore | 4 + LICENSE | 202 ++++++++++++++++ README.md | 69 +++++- TEST_RESULTS.md | 20 ++ cmd/tomcat-backend/main.go | 341 +++++++++++++++++++++++++++ cmd/tomcat-backend/main_test.go | 384 +++++++++++++++++++++++++++++++ cmd/tomcat-backend/watch.go | 216 +++++++++++++++++ cmd/tomcat-backend/watch_test.go | 127 ++++++++++ go.mod | 3 + internal/rpc/rpc.go | 368 +++++++++++++++++++++++++++++ internal/rpc/rpc_test.go | 150 ++++++++++++ internal/tomcat/config.go | 256 +++++++++++++++++++++ internal/tomcat/deploy.go | 210 +++++++++++++++++ internal/tomcat/discover.go | 245 ++++++++++++++++++++ internal/tomcat/exploded.go | 243 +++++++++++++++++++ internal/tomcat/server_xml.go | 90 ++++++++ internal/tomcat/state.go | 67 ++++++ internal/tomcat/tomcat_test.go | 263 +++++++++++++++++++++ internal/tomcat/web_test.go | 213 +++++++++++++++++ plugin.json | 62 +++++ scripts/package.py | 94 ++++++++ scripts/test_package.py | 110 +++++++++ scripts/test_ui.py | 86 +++++++ ui/app.js | 60 +++++ ui/index.html | 55 +++++ ui/style.css | 20 ++ 26 files changed, 3956 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 TEST_RESULTS.md create mode 100644 cmd/tomcat-backend/main.go create mode 100644 cmd/tomcat-backend/main_test.go create mode 100644 cmd/tomcat-backend/watch.go create mode 100644 cmd/tomcat-backend/watch_test.go create mode 100644 go.mod create mode 100644 internal/rpc/rpc.go create mode 100644 internal/rpc/rpc_test.go create mode 100644 internal/tomcat/config.go create mode 100644 internal/tomcat/deploy.go create mode 100644 internal/tomcat/discover.go create mode 100644 internal/tomcat/exploded.go create mode 100644 internal/tomcat/server_xml.go create mode 100644 internal/tomcat/state.go create mode 100644 internal/tomcat/tomcat_test.go create mode 100644 internal/tomcat/web_test.go create mode 100644 plugin.json create mode 100644 scripts/package.py create mode 100644 scripts/test_package.py create mode 100644 scripts/test_ui.py create mode 100644 ui/app.js create mode 100644 ui/index.html create mode 100644 ui/style.css diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba66fd2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.dist/ +.artifacts/ +*.zip +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 7f65a1a..8b50e4d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,67 @@ -# lithe-plugin-tomcat -Lithe 的 Tomcat 支持插件 / Tomcat support plugin for Lithe +# Tomcat for Lithe — 0.2.0 (pre-release candidate) + +An **independent, on-demand Tomcat integration** for Lithe-IDEA's Viva desktop. It uses the host-owned Run/Debug service and `java` tool from [Java Support](https://github.com/Lithe-IDEA/lithe-plugin-java); neither Lithe's host nor Core knows about Tomcat-specific paths or settings. + +> This is a community contribution prepared for review. It has passed local protocol, Go race, JVM and browser-mock tests, **but has not been verified against a native Lithe window or an actual Apache Tomcat distribution**. Do not publish it as a stable Store release until those checks pass. + +## Feature coverage + +| Feature | 0.2.0 behavior | +| --- | --- | +| Project/Web Facet discovery | Read-only discovery of Maven/Gradle web layouts, Eclipse WTP `.settings` web facets/component resources and IntelliJ `.iml` Web facets; finds local WAR and exploded output directories in each module. It does **not** rewrite IDE files. | +| Project SDK, classpath, libraries | Remain in the existing **Java Support 4.x Project Structure** page (Sources / Paths / Dependencies, per-module JRE, library scope). Tomcat does not duplicate or override JDT's authoritative classpath. | +| Tomcat installation | Explicit Catalina Home and optional Catalina Base; verifies Bootstrap and JULI JARs, config files, and real application base. Reads `server.xml` Host `appBase`/`autoDeploy` and HTTP connector ports without writing it. | +| Run / Stop | Starts `org.apache.catalina.startup.Bootstrap` with the **JDK selected by Lithe** and host-owned Run lifecycle. No shell or arbitrary scripts, and no bundled Tomcat/JDK. | +| Debug | Runs Tomcat with JDWP bound to `127.0.0.1`, and uses the public `java` debugger adapter alias through Lithe's `run/start.debug` connection target. Needs Java Support installed and the host to expose its Java Debug adapter. | +| WAR artifact deployment | Preview and explicit confirmation before copying to `/.war`. ZIP entry count, expanded size, path traversal and symlinks are checked; source/target digests bind confirmation. | +| Exploded Web artifact deployment | Preview and explicit confirmation before copying a workspace directory to `/`; bounded file count, size and depth, no symlinks or `.git`/`.idea` trees, source/target digests, replacement backup. Conflicting `.war` blocks exploded deployment. | +| Live WAR deployment | **Opt-in** only. First deploy manually and explicitly confirm, then start a Lithe-managed Tomcat with `server.xml` showing `autoDeploy=true`. A bounded watcher detects a stable changed source WAR and atomically redeploys it; an externally modified target disables the watcher instead of overwriting. Explicit manual redeploy while running follows the same gate. | +| Build integration | Existing Maven/Gradle `package`/`war` tasks produce artifacts. This plugin does not execute arbitrary project build scripts or invent its own Java classpath. | + +## Installation prerequisites + +- Current Lithe preview supporting `backend:0`, `ui:0`, `workspace.metadata`, `run.start`, plugin WebBridge and the public Debug adapter registry. The host must advertise `litheLogging:0` and `litheFunctions:0` for the backend. +- The separately installed **Java Support** plugin providing the `java` tool ID and Java Debug adapter. Configure the project JDK in Lithe's toolchains; JDT LS's JDK can be different. +- A local Tomcat Home (Tomcat 9/10 deployment layouts are supported conceptually). A compatible JDK and usable application base are the user's responsibility. **External and already-running Tomcat instances are not managed**. +- A **single local workspace root** (multi-module projects within it are supported for Web facet discovery). Remote workspace roots are unsupported. + +## Walkthrough + +1. Install the platform-matched ZIP from the Release assets or local build. Open a local Java Web workspace and the **Tomcat** tool window. +2. In **Web modules / Facets**, inspect discovered modules and output candidates. Click **Use WAR / Use Web** to populate the artifact. Non-build project Web roots may appear as exploded candidates, but they need compiled `WEB-INF/classes` and libraries to run correctly; building is still your responsibility. +3. Set Tomcat Home, optionally Catalina Base, context path (`/` or `/name`), deployment kind (WAR or exploded) and local JDWP port; save, then inspect the installation. `server.xml` is read-only. The deployment target uses its Host's `appBase` if it is a relative path inside Catalina Base. +4. Produce a WAR using Maven/Gradle. Click **Preview deployment**: verify source, destination, source type and whether an existing target is replaced. **Confirm deployment** only after inspecting the operation. Stop any externally launched Tomcat instances first. +5. Click **Start**, **Debug** or **Stop**. Debug asks Lithe to attach Java Support automatically to the selected port; a missing adapter is a host failure rather than a silently successful debug. +6. To enable opt-in automatic **WAR** redeploy, confirm an initial WAR deployment in the same active plugin session, enable the option **while the server is stopped**, save, and start Tomcat. `server.xml` must have a default Host with `autoDeploy=true`. The source WAR must be rebuilt by the project's build tool; this plugin watches the completed artifact, not source files. On conflict the watcher stops and exposes a message on refresh. Exploded artifacts are deliberately not auto-synchronized while running. + +## Safety and limitations + +- Project files, Tomcat install files, Core and the plugin package are not modified on plugin startup. The only intended writes are the host-provided per-workspace `tomcat.json` state and deployments inside the **explicitly chosen Catalina Base application directory**. +- All deployment paths are restricted to the local workspace for sources and the Catalina application base for targets. Sources and targets are hashed at preview and immediately before replacement. There are bounded file, byte, ZIP-entry and nesting limits. No subprocess shell execution or network connections are used by the plugin backend. The host owns the process and debugger. +- Deploying a new WAR to a running Tomcat may trigger Tomcat's own re-deployment and reset HTTP sessions. Actual live deployment requires Tomcat `autoDeploy=true`; it is not equivalent to Java debugger Hot Code Replace, and Tomcat's behavior depends on `unpackWARs`, Context and Host settings. See [official Tomcat deployment documentation](https://tomcat.apache.org/tomcat-10.1-doc/deployer-howto.html). +- The plugin does **not** implement: automatic WAR compilation, arbitrary Ant targets, JSP/EL source intelligence, JPA/CDI/JSF IDE model, editing IntelliJ `.iml`/Eclipse `.classpath`, Tomcat Manager credentials/API, remote app servers, fully generalized Context Descriptor deployment or importing shared IDE-global libraries. Those capabilities belong in Java/related plugins and require separate integration work. +- Filesystem replacement across hostile external writers cannot provide a fully transactional guarantee on every OS/filesystem. This version rejects observed symlinks, path escapes and changed digest targets, and keeps an on-disk backup until a replacement completes. Test with a **non-production** Catalina Base. + +## Build and test + +Requires Go 1.23+, Python 3.10+ and Node.js. Playwright + Chromium is optional for the isolated UI mock. JDK `java`/`javac`/`jar` is needed for the real JVM argv regression. + +```sh +go vet ./... +go test -race -count=1 ./... +node --check ui/app.js +python3 scripts/package.py --all +python3 -m unittest discover -s scripts -p 'test_*.py' -v +``` + +The package generator cross-compiles Linux x64/ARM64, macOS Intel/Apple Silicon and Windows x64, with deterministic ZIP entry timestamps, executable permissions and SHA-256 checks. Runtime behavior has only been exercised in this Linux container; a cross-compiled archive is **not** native platform verification. + +### Before merge or release + +- Install the archive in the current Lithe preview, verify that both plugin manifests and Java tool resolution are accepted. +- On macOS, Windows and Linux, use a real Tomcat 9/10 instance to start, query `/`, stop, deploy a small servlet WAR and test JDBC/Servlet dependencies. Confirm correct shutdown and no child processes after cancellation. +- Verify Java Debug adapter auto-attach, breakpoints, stack/variables, restart and stop, including an occupied/debug port and a failed Java build. +- Test Web/WTP/IDEA fixtures, WAR vs exploded redeploy, autoDeploy enabled and disabled, spaces/non-ASCII paths, appBase, symlinks and conflict outcomes. +- Check that the plugin package, host installation and selected JDK/Java LS installation files remain unchanged; confirm that no credentials or private project paths are logged. + +License: Apache-2.0. Apache and Tomcat are trademarks of the Apache Software Foundation; this project is not endorsed by ASF. diff --git a/TEST_RESULTS.md b/TEST_RESULTS.md new file mode 100644 index 0000000..d567bba --- /dev/null +++ b/TEST_RESULTS.md @@ -0,0 +1,20 @@ +# Tomcat 0.2.0 verification — 2026-11-17 + +## Executed locally (Linux x64 container) + +- `go vet ./...` — pass. +- `go test -race -count=1 ./...` — pass; includes initial protocol/RPC/Run and real Java 21 Bootstrap stub; new tests for exploded create, replace, source/target digest conflicts, symlink and `.git` rejection, Eclipse WTP and IntelliJ Web facet read-only detection, parsed server.xml custom appBase / autoDeploy, opt-in live WAR watcher with stable artifact change, watcher rollback on externally changed targets, and one-click Run/Debug adapter alias parameters. +- `node --check ui/app.js` — pass. +- `python3 scripts/package.py --all` — builds 5 Go platform targets and ZIP archives. +- `python3 -m unittest discover -s scripts -p 'test_*.py' -v` — checks ZIP layout/permissions/digests, Linux binary initialize/shutdown, reproducibility, mock Chinese UI project/facet/artifact and preview/confirmation workflow. +- Synthetic Lithe host uses exact `lithe/host/workspace/getContext`, `run/start`, `run/stop` and `run/didExit` request/notification shapes. Java 21 executable regression uses a compiled synthetic `org.apache.catalina.startup.Bootstrap` fixture and localhost JDWP; no real Tomcat components are used. +- Tests use isolated temporary roots, do not mutate the source workspace or installed plugin directory and have no external credentials. + +## Not verified / release blockers + +1. **Real Tomcat integration** — not run; this container has no Apache Tomcat installation and external archive download was unsuccessful. No claim of HTTP Servlet requests, real app reload or native Tomcat shutdown passing. +2. **Native Lithe host** — macOS and Windows UI, Java Debug adapter attach, file pickers, workbench Run/Stop, and real Java breakpoint handling are pending. The browser test uses a mocked WebBridge. +3. **Cross-platform runtime** — macOS and Windows ZIPs cross-build but were not executed on native systems. Linux ARM64 also not run natively. +4. **JavaEE extras** — JSP/EL completion, auto WAR build, Maven profile wiring, classpath-global libraries and editing Web Facet declarations are separate future work and are not represented as completed here. + +Run local checks via README. Review GitHub Actions separately after the PR has been created; no CI result is claimed until observed. diff --git a/cmd/tomcat-backend/main.go b/cmd/tomcat-backend/main.go new file mode 100644 index 0000000..bd7b216 --- /dev/null +++ b/cmd/tomcat-backend/main.go @@ -0,0 +1,341 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "net" + "os" + "strconv" + "sync" + "time" + + "github.com/Lithe-IDEA/lithe-plugin-tomcat/internal/rpc" + "github.com/Lithe-IDEA/lithe-plugin-tomcat/internal/tomcat" +) + +type hostContext struct { + ContextID string `json:"contextID"` + Generation int `json:"generation"` + StateDirectory string `json:"stateDirectory"` + Authority struct { + Kind string `json:"kind"` + } `json:"authority"` + Folders []struct { + Path string `json:"path"` + RootID string `json:"rootID"` + } `json:"folders"` +} + +type session struct { + mu sync.Mutex + runs map[string]string // context ID + generation -> owned run ID + starting map[string]bool + stopping map[string]bool + deploying map[string]bool + exited map[string]struct{} // early host exit reported before start ack + approved map[string]deployApproval + watches map[string]context.CancelFunc + watching map[string]bool + watchError map[string]string + watchGeneration map[string]uint64 +} + +func newSession() *session { + return &session{runs: make(map[string]string), starting: make(map[string]bool), stopping: make(map[string]bool), deploying: make(map[string]bool), exited: make(map[string]struct{}), approved: make(map[string]deployApproval), watches: make(map[string]context.CancelFunc), watching: make(map[string]bool), watchError: make(map[string]string), watchGeneration: make(map[string]uint64)} +} +func (s *session) onRunExit(runID string) { + s.mu.Lock() + defer s.mu.Unlock() + if runID == "" { + return + } + found := false + for ctx, id := range s.runs { + if id == runID { + found = true + delete(s.runs, ctx) + delete(s.stopping, ctx) + if cancel := s.watches[ctx]; cancel != nil { + cancel() + } + s.watchGeneration[ctx]++ + delete(s.watches, ctx) + delete(s.watching, ctx) + } + } + if !found && len(s.starting) > 0 && len(s.exited) < 128 { + s.exited[runID] = struct{}{} + } +} +func (s *session) runID(contextID string) string { + s.mu.Lock() + defer s.mu.Unlock() + return s.runs[contextID] +} +func (s *session) reserve(contextID string) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.starting[contextID] || s.deploying[contextID] || s.runs[contextID] != "" { + return false + } + s.starting[contextID] = true + return true +} +func (s *session) finishStart(contextID, runID string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.starting, contextID) + if runID != "" { + if _, alreadyExited := s.exited[runID]; alreadyExited { + delete(s.exited, runID) + } else { + s.runs[contextID] = runID + } + } +} +func (s *session) reserveStop(contextID string) (string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + id := s.runs[contextID] + if id == "" || s.stopping[contextID] { + return "", false + } + s.stopping[contextID] = true + return id, true +} +func (s *session) busy(contextID string) bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.starting[contextID] || s.deploying[contextID] || s.runs[contextID] != "" +} +func (s *session) reserveDeploy(contextID string) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.starting[contextID] || s.deploying[contextID] || s.runs[contextID] != "" { + return false + } + s.deploying[contextID] = true + return true +} +func (s *session) finishDeploy(contextID string) { + s.mu.Lock() + delete(s.deploying, contextID) + s.mu.Unlock() +} +func (s *session) stopFailed(contextID string) { + s.mu.Lock() + delete(s.stopping, contextID) + s.mu.Unlock() +} + +func (s *session) getContext(ctx context.Context, call rpc.Invocation, conn *rpc.Server) (hostContext, string, error) { + var h hostContext + if call.Context == nil { + return h, "", rpc.Failed("tomcat.contextMissing", "No workspace is active") + } + var caps struct { + Services map[string]struct { + Methods []string `json:"methods"` + } `json:"services"` + } + if err := conn.Request(ctx, "lithe/host/getCapabilities", map[string]any{}, &caps); err != nil { + return h, "", rpc.Failed("tomcat.hostUnavailable", err.Error()) + } + supported := false + for _, v := range caps.Services { + for _, m := range v.Methods { + if m == "lithe/host/workspace/getContext" { + supported = true + } + } + } + if !supported { + return h, "", rpc.Failed("tomcat.hostUnavailable", "Host does not expose workspace metadata") + } + if err := conn.Request(ctx, "lithe/host/workspace/getContext", map[string]any{"context": call.Context}, &h); err != nil { + return h, "", rpc.Failed("tomcat.contextUnavailable", err.Error()) + } + if h.ContextID != call.Context.ContextID || h.Generation != call.Context.Generation || h.Authority.Kind != "local" || len(h.Folders) != 1 || h.Folders[0].Path == "" || h.StateDirectory == "" { + return h, "", rpc.Failed("tomcat.workspaceUnsupported", "Tomcat requires exactly one local workspace root") + } + return h, h.Folders[0].Path, nil +} +func (s *session) handle(ctx context.Context, call rpc.Invocation, conn *rpc.Server) (any, error) { + h, root, err := s.getContext(ctx, call, conn) + if err != nil { + return nil, err + } + loaded, err := tomcat.LoadConfig(h.StateDirectory) + if err != nil { + return nil, rpc.Failed("tomcat.configReadFailed", err.Error()) + } + runKey := h.ContextID + ":" + strconv.Itoa(h.Generation) + getRunID := func() string { return s.runID(runKey) } + switch call.FunctionID { + case "tomcat.get": + watching, reason := s.watchStatus(runKey) + return map[string]any{"config": loaded, "running": getRunID() != "", "runID": getRunID(), "workspaceRoot": root, "watching": watching, "watchError": reason}, nil + case "tomcat.discover": + modules, err := tomcat.DiscoverWebModules(root) + if err != nil { + return nil, rpc.Failed("tomcat.discoveryFailed", err.Error()) + } + return map[string]any{"modules": modules}, nil + case "tomcat.save": + if s.busy(runKey) { + return nil, rpc.Failed("tomcat.running", "Wait for Tomcat or deployment to finish before editing configuration") + } + var args struct { + Config tomcat.Config `json:"config"` + } + if err := json.Unmarshal(call.Params, &args); err != nil { + return nil, rpc.Failed("tomcat.invalidConfig", "Invalid config") + } + if err := tomcat.SaveConfig(h.StateDirectory, args.Config); err != nil { + return nil, rpc.Failed("tomcat.invalidConfig", err.Error()) + } + return map[string]any{"saved": true}, nil + case "tomcat.inspect": + checked, err := tomcat.Check(loaded, root, false) + if err != nil { + return nil, rpc.Failed("tomcat.installInvalid", err.Error()) + } + return map[string]any{"home": checked.HomePath, "base": checked.BasePath, "webapps": checked.Webapps, "war": checked.WARPath, "exploded": checked.ExplodedPath, "artifact": checked.Artifact, "context": checked.Context, "debugPort": checked.DebugPort, "server": checked.Server}, nil + case "tomcat.planDeploy", "tomcat.deploy": + checked, err := tomcat.Check(loaded, root, true) + if err != nil { + return nil, rpc.Failed("tomcat.installInvalid", err.Error()) + } + if !s.canDeploy(runKey, loaded, checked) { + return nil, rpc.Failed("tomcat.running", "Stop Tomcat before deploying; live WAR deploy requires opt-in and Tomcat autoDeploy=true") + } + if call.FunctionID == "tomcat.planDeploy" { + plan, err := tomcat.InspectDeploy(checked) + if err != nil { + return nil, rpc.Failed("tomcat.deployInvalid", err.Error()) + } + return plan, nil + } + if !s.reserveDeployFor(runKey, loaded, checked) { + return nil, rpc.Failed("tomcat.deployBusy", "Tomcat started or another deployment is active") + } + defer s.finishDeploy(runKey) + var args struct { + Token string `json:"confirmationToken"` + } + if err := json.Unmarshal(call.Params, &args); err != nil || len(args.Token) != 64 { + return nil, rpc.Failed("tomcat.confirmationRequired", "First inspect deployment and explicitly confirm its preview") + } + plan, err := tomcat.Deploy(checked, args.Token) + if err != nil { + return nil, rpc.Failed("tomcat.deployFailed", err.Error()) + } + s.approval(runKey, plan) + return map[string]any{"deployed": true, "target": plan.Target, "sha256": plan.SourceHash, "action": plan.Action}, nil + case "tomcat.start": + var args struct { + Debug bool `json:"debug"` + } + if err := json.Unmarshal(call.Params, &args); err != nil { + return nil, rpc.Failed("tomcat.invalidParams", err.Error()) + } + if !s.reserve(runKey) { + return nil, rpc.Failed("tomcat.alreadyRunning", "Tomcat is already running or starting") + } + runID := "" + defer func() { s.finishStart(runKey, runID) }() + checked, err := tomcat.Check(loaded, root, false) + if err != nil { + return nil, rpc.Failed("tomcat.installInvalid", err.Error()) + } + if args.Debug { + address := "127.0.0.1:" + strconv.Itoa(checked.DebugPort) + conn, err := net.DialTimeout("tcp", address, 150*time.Millisecond) + if err == nil { + conn.Close() + return nil, rpc.Failed("tomcat.debugPortBusy", "JDWP port is already in use") + } + } + var caps struct { + Services map[string]struct { + Methods []string `json:"methods"` + } `json:"services"` + } + if err := conn.Request(ctx, "lithe/host/getCapabilities", map[string]any{}, &caps); err != nil { + return nil, rpc.Failed("tomcat.hostUnavailable", err.Error()) + } + supported := false + for _, v := range caps.Services { + for _, m := range v.Methods { + if m == "lithe/host/run/start" { + supported = true + } + } + } + if !supported { + return nil, rpc.Failed("tomcat.runUnavailable", "Host does not provide run/start") + } + title := "Tomcat" + if args.Debug { + title = "Tomcat (JDWP " + strconv.Itoa(checked.DebugPort) + ")" + } + var resp struct { + RunID string `json:"runID"` + } + // Once submitted to host, complete the response rather than cancelling + // mid-start; host owns this Run session and its Stop button. + startParams := map[string]any{"context": call.Context, "label": title, "process": checked.Startup(args.Debug)} + if args.Debug { + // The java alias is a public debug-adapter configuration type, not + // a Tomcat-owned adapter. Lithe's Run session waits for this JDWP + // listener, then attaches the Java Support adapter if installed. + startParams["debug"] = map[string]any{"configurationType": "java", "target": map[string]any{"kind": "connection", "port": checked.DebugPort}} + } + err = conn.Request(context.Background(), "lithe/host/run/start", startParams, &resp) + if err != nil { + return nil, rpc.Failed("tomcat.startFailed", err.Error()) + } + if resp.RunID == "" { + return nil, rpc.Failed("tomcat.startFailed", "Host returned no run ID") + } + runID = resp.RunID + // finishStart runs as this handler returns. The watcher validates the + // acknowledged run ID after the host owns the process. + if loaded.WatchChanges { + go func() { + time.Sleep(50 * time.Millisecond) + if reason := s.startWatch(runKey, runID, loaded, root); reason != "" { + s.warnWatch(runKey, reason) + } + }() + } + return map[string]any{"runID": runID, "debug": args.Debug, "debugPort": checked.DebugPort}, nil + case "tomcat.stop": + id, ok := s.reserveStop(runKey) + if !ok { + return nil, rpc.Failed("tomcat.notRunning", "No running Tomcat session to stop") + } + s.cancelWatch(runKey) + if err := conn.Request(context.Background(), "lithe/host/run/stop", map[string]string{"runID": id}, nil); err != nil { + s.stopFailed(runKey) + return nil, rpc.Failed("tomcat.stopFailed", err.Error()) + } + return map[string]any{"stopRequested": true, "runID": id}, nil + default: + return nil, rpc.Failed("tomcat.unknownFunction", "Unknown function") + } +} +func main() { + // The host owns stdout: it must contain only Content-Length JSON-RPC frames. + s := newSession() + backend := rpc.New(os.Stdin, os.Stdout) + backend.OnRunExit(s.onRunExit) + for _, id := range []string{"tomcat.get", "tomcat.save", "tomcat.inspect", "tomcat.discover", "tomcat.planDeploy", "tomcat.deploy", "tomcat.start", "tomcat.stop"} { + backend.Function(id, s.handle) + } + if err := backend.Listen(); err != nil && !errors.Is(err, context.Canceled) { + // Do not print paths, workspace data, or the JSON-RPC stream to stderr. + os.Exit(1) + } +} diff --git a/cmd/tomcat-backend/main_test.go b/cmd/tomcat-backend/main_test.go new file mode 100644 index 0000000..74519f7 --- /dev/null +++ b/cmd/tomcat-backend/main_test.go @@ -0,0 +1,384 @@ +package main + +import ( + "archive/zip" + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Lithe-IDEA/lithe-plugin-tomcat/internal/rpc" + "github.com/Lithe-IDEA/lithe-plugin-tomcat/internal/tomcat" +) + +// This is a protocol-level synthetic host, not a native Lithe UI or Tomcat +// installation test. It exercises the same LSP frames and host RPC contracts. +type syntheticHost struct { + writer *io.PipeWriter + reader *io.PipeReader + mu sync.Mutex + pending map[int]chan map[string]json.RawMessage + serial int + runPlan map[string]json.RawMessage + stopID string + root string + state string +} + +func (h *syntheticHost) send(value any) error { + h.mu.Lock() + defer h.mu.Unlock() + b, err := json.Marshal(value) + if err != nil { + return err + } + if _, err := fmt.Fprintf(h.writer, "Content-Length: %d\r\n\r\n", len(b)); err != nil { + return err + } + _, err = h.writer.Write(b) + return err +} +func (h *syntheticHost) serve(done chan<- error) { + r := bufio.NewReader(h.reader) + for { + length := -1 + for { + line, err := r.ReadString('\n') + if err != nil { + done <- err + return + } + line = strings.TrimSpace(line) + if line == "" { + break + } + if strings.HasPrefix(line, "Content-Length: ") { + length, _ = strconv.Atoi(strings.TrimPrefix(line, "Content-Length: ")) + } + } + if length < 0 || length > 4<<20 { + done <- fmt.Errorf("invalid frame size %d", length) + return + } + b := make([]byte, length) + if _, err := io.ReadFull(r, b); err != nil { + done <- err + return + } + var m map[string]json.RawMessage + if err := json.Unmarshal(b, &m); err != nil { + done <- err + return + } + var id int + _ = json.Unmarshal(m["id"], &id) + if len(m["method"]) == 0 { + h.mu.Lock() + ch := h.pending[id] + delete(h.pending, id) + h.mu.Unlock() + if ch != nil { + ch <- m + } + continue + } + var method string + _ = json.Unmarshal(m["method"], &method) + var result any + switch method { + case "lithe/host/getCapabilities": + result = map[string]any{"services": map[string]any{"workspace": map[string]any{"methods": []string{"lithe/host/workspace/getContext"}}, "run": map[string]any{"methods": []string{"lithe/host/run/start", "lithe/host/run/stop"}}}} + case "lithe/host/workspace/getContext": + result = map[string]any{"contextID": "ctx-one", "generation": 1, "stateDirectory": h.state, "authority": map[string]string{"kind": "local"}, "folders": []any{map[string]string{"path": h.root, "rootID": "r1"}}} + case "lithe/host/run/start": + var p map[string]json.RawMessage + _ = json.Unmarshal(m["params"], &p) + h.mu.Lock() + h.runPlan = p + h.mu.Unlock() + result = map[string]string{"runID": "run-test-1"} + case "lithe/host/run/stop": + var p map[string]string + _ = json.Unmarshal(m["params"], &p) + h.mu.Lock() + h.stopID = p["runID"] + h.mu.Unlock() + result = nil + default: + done <- fmt.Errorf("unexpected host method: %s", method) + return + } + if err := h.send(map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(m["id"]), "result": result}); err != nil { + done <- err + return + } + } +} +func (h *syntheticHost) call(t *testing.T, method string, params any) (map[string]json.RawMessage, error) { + t.Helper() + h.mu.Lock() + h.serial++ + id := h.serial + ch := make(chan map[string]json.RawMessage, 1) + h.pending[id] = ch + h.mu.Unlock() + if err := h.send(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}); err != nil { + return nil, err + } + select { + case got := <-ch: + if len(got["error"]) > 0 { + return got, fmt.Errorf("%s", got["error"]) + } + return got, nil + case <-time.After(7 * time.Second): + return nil, fmt.Errorf("timed out calling %s", method) + } +} +func (h *syntheticHost) invoke(t *testing.T, fn string, params any) (map[string]json.RawMessage, error) { + return h.call(t, "lithe/function/invoke", map[string]any{"functionID": fn, "operationID": "op-test-1", "context": map[string]any{"contextID": "ctx-one", "generation": 1}, "params": params}) +} +func makeWAR(t *testing.T, path string) { + t.Helper() + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + z := zip.NewWriter(f) + w, err := z.Create("WEB-INF/web.xml") + if err != nil { + t.Fatal(err) + } + if _, err = w.Write([]byte("")); err != nil { + t.Fatal(err) + } + if err := z.Close(); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } +} +func fakeTomcat(t *testing.T) (tomcat.Config, string, string) { + t.Helper() + root := t.TempDir() + home := filepath.Join(root, "Tomcat with space") + work := filepath.Join(root, "Example project") + for _, dir := range []string{"bin", "lib", "conf", "webapps", "temp"} { + if err := os.MkdirAll(filepath.Join(home, dir), 0755); err != nil { + t.Fatal(err) + } + } + for _, p := range []string{"bin/bootstrap.jar", "bin/tomcat-juli.jar", "lib/catalina.jar", "conf/server.xml", "conf/catalina.properties"} { + if err := os.WriteFile(filepath.Join(home, filepath.FromSlash(p)), []byte("test"), 0644); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(filepath.Join(work, "target"), 0755); err != nil { + t.Fatal(err) + } + makeWAR(t, filepath.Join(work, "target", "app.war")) + return tomcat.Config{Home: home, Context: "/app", WAR: "target/app.war", DebugPort: 5566}, work, home +} +func TestBackendWorkspaceRunDeployProtocol(t *testing.T) { + config, root, home := fakeTomcat(t) + toBackendR, toBackendW := io.Pipe() + fromBackendR, fromBackendW := io.Pipe() + defer toBackendR.Close() + defer toBackendW.Close() + defer fromBackendR.Close() + defer fromBackendW.Close() + h := &syntheticHost{reader: fromBackendR, writer: toBackendW, pending: map[int]chan map[string]json.RawMessage{}, root: root, state: filepath.Join(t.TempDir(), "private")} + backend := rpc.New(toBackendR, fromBackendW) + s := newSession() + backend.OnRunExit(s.onRunExit) + for _, fn := range []string{"tomcat.get", "tomcat.save", "tomcat.inspect", "tomcat.discover", "tomcat.planDeploy", "tomcat.deploy", "tomcat.start", "tomcat.stop"} { + backend.Function(fn, s.handle) + } + go func() { _ = backend.Listen() }() + done := make(chan error, 1) + go h.serve(done) + if _, err := h.call(t, "initialize", map[string]any{"capabilities": map[string]any{"experimental": map[string]any{"litheFunctions": map[string]any{"versions": []int{0}}, "litheLogging": map[string]any{"versions": []int{0}}}}}); err != nil { + t.Fatal(err) + } + if _, err := h.invoke(t, "tomcat.save", map[string]any{"config": config}); err != nil { + t.Fatal(err) + } + if result, err := h.invoke(t, "tomcat.inspect", map[string]any{}); err != nil || !bytes.Contains(result["result"], []byte("webapps")) { + t.Fatalf("inspect: %v %s", err, result["result"]) + } + planMsg, err := h.invoke(t, "tomcat.planDeploy", map[string]any{}) + if err != nil { + t.Fatal(err) + } + var plan tomcat.DeployPlan + if err := json.Unmarshal(planMsg["result"], &plan); err != nil { + t.Fatal(err) + } + if plan.Action != "create" || plan.Token == "" { + t.Fatalf("invalid plan: %+v", plan) + } + if _, err := os.Stat(plan.Target); !os.IsNotExist(err) { + t.Fatal("preview wrote target") + } + if _, err := h.invoke(t, "tomcat.deploy", map[string]any{"confirmationToken": "!" + plan.Token[1:]}); err == nil { + t.Fatal("accepted unconfirmed deployment") + } + if _, err := h.invoke(t, "tomcat.deploy", map[string]any{"confirmationToken": plan.Token}); err != nil { + t.Fatal(err) + } + if st, err := os.Stat(plan.Target); err != nil || st.Size() == 0 { + t.Fatal("deployed WAR missing", err) + } + started, err := h.invoke(t, "tomcat.start", map[string]any{"debug": true}) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(started["result"], []byte("run-test-1")) { + t.Fatal("no run id", started) + } + h.mu.Lock() + rp := h.runPlan + h.mu.Unlock() + if len(rp) == 0 || !bytes.Contains(rp["process"], []byte("127.0.0.1:5566")) || !bytes.Contains(rp["process"], []byte(`"tool":"java"`)) || !bytes.Contains(rp["debug"], []byte(`"configurationType":"java"`)) || !bytes.Contains(rp["debug"], []byte(`"kind":"connection"`)) { + t.Fatalf("bad host run/start plan: %s", rp["process"]) + } + if _, err := h.invoke(t, "tomcat.start", map[string]any{"debug": false}); err == nil { + t.Fatal("duplicate start was allowed") + } + if _, err := h.invoke(t, "tomcat.stop", map[string]any{}); err != nil { + t.Fatal(err) + } + h.mu.Lock() + stopped := h.stopID + h.mu.Unlock() + if stopped != "run-test-1" { + t.Fatalf("wrong stopped run: %s", stopped) + } + if err := h.send(map[string]any{"jsonrpc": "2.0", "method": "lithe/host/run/didExit", "params": map[string]any{"runID": "run-test-1", "exitCode": 0}}); err != nil { + t.Fatal(err) + } + // Wait for the notification to be applied rather than assuming synchronous delivery. + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if s.runID("ctx-one:1") == "" { + break + } + time.Sleep(10 * time.Millisecond) + } + if s.runID("ctx-one:1") != "" { + t.Fatal("run exit did not clear session") + } + if _, err := h.invoke(t, "tomcat.save", map[string]any{"config": config}); err != nil { + t.Fatal("save after exit", err) + } + if saved, err := tomcat.LoadConfig(h.state); err != nil || saved.Home != home { + t.Fatal("workspace state not saved", saved, err) + } + if _, err := h.call(t, "shutdown", map[string]any{}); err != nil { + t.Fatal(err) + } + if err := h.send(map[string]any{"jsonrpc": "2.0", "method": "exit"}); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil && err != io.EOF && err != io.ErrClosedPipe { + t.Logf("synthetic host closing: %v", err) + } + default: + } +} +func TestRunSessionFastExitAndGeneration(t *testing.T) { + s := newSession() + if !s.reserve("ctx:1") { + t.Fatal("cannot reserve") + } + s.onRunExit("short-run") + s.finishStart("ctx:1", "short-run") + if s.runID("ctx:1") != "" { + t.Fatal("fast exit recorded as running") + } + if !s.reserve("ctx:2") { + t.Fatal("new generation should have independent run") + } + s.finishStart("ctx:2", "new-run") + if s.runID("ctx:2") != "new-run" { + t.Fatal("new generation lost") + } + s.onRunExit("new-run") + if s.runID("ctx:2") != "" { + t.Fatal("didExit did not clear new generation") + } +} +func TestRunPlanJavaArgsFixture(t *testing.T) { + if _, err := exec.LookPath("javac"); err != nil { + t.Skip("javac not installed") + } + if _, err := exec.LookPath("jar"); err != nil { + t.Skip("jar not installed") + } + if _, err := exec.LookPath("java"); err != nil { + t.Skip("java not installed") + } + c, workspace, home := fakeTomcat(t) + srcDir := filepath.Join(t.TempDir(), "source", "org", "apache", "catalina", "startup") + classesDir := filepath.Join(t.TempDir(), "classes") + if err := os.MkdirAll(srcDir, 0755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(classesDir, 0755); err != nil { + t.Fatal(err) + } + source := `package org.apache.catalina.startup; +public final class Bootstrap { + public static void main(String[] args) { + System.out.println("START_OK HOME="+System.getProperty("catalina.home") + " BASE="+System.getProperty("catalina.base")+" ACTION="+args[0]); + } +}` + src := filepath.Join(srcDir, "Bootstrap.java") + if err := os.WriteFile(src, []byte(source), 0644); err != nil { + t.Fatal(err) + } + if out, err := exec.Command("javac", "-d", classesDir, src).CombinedOutput(); err != nil { + t.Fatalf("javac %s: %s", err, out) + } + jarPath := filepath.Join(home, "bin", "bootstrap.jar") + if out, err := exec.Command("jar", "--create", "--file", jarPath, "-C", classesDir, ".").CombinedOutput(); err != nil { + t.Fatalf("jar %s: %s", err, out) + } + // Do not collide with anyone else's local JDWP listener. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + c.DebugPort = ln.Addr().(*net.TCPAddr).Port + _ = ln.Close() + checked, err := tomcat.Check(c, workspace, false) + if err != nil { + t.Fatal(err) + } + for _, debug := range []bool{false, true} { + plan := checked.Startup(debug) + command := exec.Command("java", plan.Arguments...) + command.Dir = workspace + command.Env = append(os.Environ(), "CATALINA_HOME="+home, "CATALINA_BASE="+home) + out, err := command.CombinedOutput() + if err != nil { + t.Fatalf("debug=%t java failed: %v\n%s", debug, err, out) + } + if !bytes.Contains(out, []byte("START_OK HOME="+home)) || !bytes.Contains(out, []byte("ACTION=start")) { + t.Fatalf("debug=%t java argv boundary mismatch: %s", debug, out) + } + } +} diff --git a/cmd/tomcat-backend/watch.go b/cmd/tomcat-backend/watch.go new file mode 100644 index 0000000..e1559c4 --- /dev/null +++ b/cmd/tomcat-backend/watch.go @@ -0,0 +1,216 @@ +package main + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/Lithe-IDEA/lithe-plugin-tomcat/internal/tomcat" +) + +type deployApproval struct { + source string + target string + artifact string + deployedHash string +} + +var watchPollInterval = 2 * time.Second + +// A watcher is private to a successfully started and approved local session. +// The opt-in setting is not sufficient: the user must first deploy manually +// and approve the exact destination. No watcher starts on plugin startup. +func (s *session) approval(runKey string, p *tomcat.DeployPlan) { + s.mu.Lock() + defer s.mu.Unlock() + s.approved[runKey] = deployApproval{source: p.Source, target: p.Target, artifact: p.Artifact, deployedHash: p.SourceHash} +} +func (s *session) watchStatus(runKey string) (bool, string) { + s.mu.Lock() + defer s.mu.Unlock() + return s.watching[runKey], s.watchError[runKey] +} +func (s *session) warnWatch(runKey, message string) { + s.mu.Lock() + defer s.mu.Unlock() + s.watchError[runKey] = message +} +func (s *session) cancelWatch(runKey string) { + s.mu.Lock() + cancel := s.watches[runKey] + s.watchGeneration[runKey]++ + delete(s.watches, runKey) + delete(s.watching, runKey) + s.mu.Unlock() + if cancel != nil { + cancel() + } +} +func (s *session) canDeploy(runKey string, c tomcat.Config, checked *tomcat.Checked) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.starting[runKey] || s.deploying[runKey] || s.stopping[runKey] { + return false + } + if s.runs[runKey] == "" { + return true + } + return c.WatchChanges && c.Artifact == "war" && checked != nil && checked.Server.XMLValid && checked.Server.AutoDeploy +} +func (s *session) reserveDeployFor(runKey string, c tomcat.Config, checked *tomcat.Checked) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.starting[runKey] || s.deploying[runKey] || s.stopping[runKey] { + return false + } + if s.runs[runKey] != "" && !(c.WatchChanges && c.Artifact == "war" && checked.Server.XMLValid && checked.Server.AutoDeploy) { + return false + } + s.deploying[runKey] = true + return true +} +func (s *session) reserveAuto(runKey, runID string) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.runs[runKey] != runID || s.stopping[runKey] || s.deploying[runKey] || s.starting[runKey] { + return false + } + s.deploying[runKey] = true + return true +} + +func (s *session) startWatch(runKey, runID string, c tomcat.Config, root string) string { + if !c.WatchChanges { + return "" + } + validated, err := tomcat.ValidateConfig(c) + if err != nil { + return err.Error() + } + c = validated + if c.Artifact != "war" { + return "Automatic deployment supports WAR files only." + } + checked, err := tomcat.Check(c, root, true) + if err != nil { + return err.Error() + } + if !checked.Server.XMLValid || !checked.Server.AutoDeploy { + return "Tomcat server.xml must declare a default Host with autoDeploy enabled before live deployment." + } + s.mu.Lock() + approved, known := s.approved[runKey] + s.mu.Unlock() + if !known || approved.source != checked.WARPath || approved.target != checked.TargetPath || approved.artifact != "war" { + return "Confirm and deploy this WAR once before enabling automatic redeployment." + } + plan, err := tomcat.InspectDeploy(checked) + if err != nil { + return err.Error() + } + if plan.ExistingHash != approved.deployedHash { + return "Installed WAR changed outside Lithe. Redeploy manually before enabling the watcher." + } + ctx, cancel := context.WithCancel(context.Background()) + s.mu.Lock() + if s.runs[runKey] != runID || s.stopping[runKey] { + s.mu.Unlock() + cancel() + return "Tomcat session ended before the watcher started." + } + previous := s.watches[runKey] + s.watches[runKey] = cancel + s.watching[runKey] = true + s.watchGeneration[runKey]++ + sequence := s.watchGeneration[runKey] + delete(s.watchError, runKey) + s.mu.Unlock() + if previous != nil { + previous() + } + go s.watchChanges(ctx, runKey, runID, c, root, plan.SourceHash, sequence) + return "" +} + +// Background sync is gated by a managed run, explicit opt-in, successful +// initial deployment, autoDeploy=true, stable source metadata, and an exact +// digest match for the last installed artifact. A conflict disables the +// watcher rather than overwriting external changes. +func (s *session) watchChanges(ctx context.Context, runKey, runID string, c tomcat.Config, root string, lastHash string, sequence uint64) { + defer func() { + s.mu.Lock() + if s.watchGeneration[runKey] == sequence { + delete(s.watches, runKey) + delete(s.watching, runKey) + } + s.mu.Unlock() + }() + interval := watchPollInterval + ticker := time.NewTicker(interval) + defer ticker.Stop() + var lastSize int64 = -1 + var lastMod time.Time + stable := 0 + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + checked, err := tomcat.Check(c, root, true) + if err != nil { + s.warnWatch(runKey, fmt.Sprintf("Automatic deployment disabled: %s", err)) + return + } + if !checked.Server.XMLValid || !checked.Server.AutoDeploy { + s.warnWatch(runKey, "Tomcat autoDeploy was disabled; automatic deployment stopped.") + return + } + fi, err := os.Stat(checked.WARPath) + if err != nil { + s.warnWatch(runKey, err.Error()) + return + } + if fi.Size() != lastSize || !fi.ModTime().Equal(lastMod) { + lastSize, lastMod = fi.Size(), fi.ModTime() + stable = 0 + continue + } + stable++ + if stable < 1 { + continue + } + // Hash only after the size and timestamp have stopped changing; + // avoid re-reading hundreds of MiB every polling interval. + plan, err := tomcat.InspectDeploy(checked) + if err != nil { + s.warnWatch(runKey, err.Error()) + return + } + if plan.SourceHash == lastHash { + continue + } + if !s.reserveAuto(runKey, runID) { + return + } + s.mu.Lock() + approved := s.approved[runKey] + s.mu.Unlock() + if approved.source != plan.Source || approved.target != plan.Target || approved.deployedHash != plan.ExistingHash { + s.finishDeploy(runKey) + s.warnWatch(runKey, "Installed deployment changed externally; automatic deployment stopped.") + return + } + deployed, err := tomcat.Deploy(checked, plan.Token) + if err == nil { + s.approval(runKey, deployed) + lastHash = deployed.SourceHash + } + s.finishDeploy(runKey) + if err != nil { + s.warnWatch(runKey, fmt.Sprintf("Automatic deployment failed: %s", err)) + return + } + } +} diff --git a/cmd/tomcat-backend/watch_test.go b/cmd/tomcat-backend/watch_test.go new file mode 100644 index 0000000..8b9389e --- /dev/null +++ b/cmd/tomcat-backend/watch_test.go @@ -0,0 +1,127 @@ +package main + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Lithe-IDEA/lithe-plugin-tomcat/internal/tomcat" +) + +func modifyWAR(t *testing.T, p, content string) { + t.Helper() + var buf bytes.Buffer + writer := zip.NewWriter(&buf) + f, err := writer.Create("WEB-INF/web.xml") + if err != nil { + t.Fatal(err) + } + if _, err = f.Write([]byte("" + content + "")); err != nil { + t.Fatal(err) + } + if err = writer.Close(); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(p, buf.Bytes(), 0644); err != nil { + t.Fatal(err) + } +} +func TestLiveWARWatchRequiresApprovalAndStopsOnExternalMutation(t *testing.T) { + c, root, home := fakeTomcat(t) + c.WatchChanges = true + c.Artifact = "war" + if err := os.WriteFile(filepath.Join(home, "conf", "server.xml"), []byte(``), 0644); err != nil { + t.Fatal(err) + } + s := newSession() + key := "ctx:1" + s.reserve(key) + s.finishStart(key, "r-1") + if got := s.startWatch(key, "r-1", c, root); !strings.Contains(got, "Confirm") { + t.Fatalf("expected approval required, got %q", got) + } + checked, err := tomcat.Check(c, root, true) + if err != nil { + t.Fatal(err) + } + p, err := tomcat.InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + deployed, err := tomcat.Deploy(checked, p.Token) + if err != nil { + t.Fatal(err) + } + s.approval(key, deployed) + before := watchPollInterval + watchPollInterval = 120 * time.Millisecond + defer func() { s.cancelWatch(key); time.Sleep(100 * time.Millisecond); watchPollInterval = before }() + if got := s.startWatch(key, "r-1", c, root); got != "" { + t.Fatal(got) + } + modifyWAR(t, checked.WARPath, "new") + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + data, e := os.ReadFile(deployed.Target) + source, _ := os.ReadFile(checked.WARPath) + if e == nil && bytes.Equal(data, source) { + break + } + time.Sleep(45 * time.Millisecond) + } + data, err := os.ReadFile(deployed.Target) + source, _ := os.ReadFile(checked.WARPath) + if err != nil || !bytes.Equal(data, source) { + t.Fatalf("automatic update did not deploy WAR: %s (%v)", data, err) + } + // A third party changing the deployed file is not overwritten. + if err := os.WriteFile(deployed.Target, []byte("external changes"), 0644); err != nil { + t.Fatal(err) + } + modifyWAR(t, checked.WARPath, "newer") + deadline = time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + watching, reason := s.watchStatus(key) + if !watching && strings.Contains(reason, "externally") { + break + } + time.Sleep(45 * time.Millisecond) + } + _, reason := s.watchStatus(key) + if !strings.Contains(reason, "externally") { + t.Fatalf("watcher didn't detect conflict: %q", reason) + } + content, err := os.ReadFile(deployed.Target) + if err != nil || string(content) != "external changes" { + t.Fatalf("external changes lost: %q (%v)", content, err) + } + s.onRunExit("r-1") + if s.runID(key) != "" { + t.Fatal("run not cleared") + } +} +func TestLiveWARIsRejectedWhenTomcatAutoDeployDisabled(t *testing.T) { + c, root, home := fakeTomcat(t) + c.WatchChanges = true + c.Artifact = "war" + if err := os.WriteFile(filepath.Join(home, "conf", "server.xml"), []byte(``), 0644); err != nil { + t.Fatal(err) + } + checked, err := tomcat.Check(c, root, true) + if err != nil { + t.Fatal(err) + } + s := newSession() + s.reserve("ctx:1") + s.finishStart("ctx:1", "r-1") + if s.canDeploy("ctx:1", c, checked) { + t.Fatal("enabled live deploy when Tomcat explicitly disables it") + } + if got := s.startWatch("ctx:1", "r-1", c, root); !strings.Contains(got, "autoDeploy") { + t.Fatalf("missing diagnosed prerequisite: %s", got) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6e3f6ef --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/Lithe-IDEA/lithe-plugin-tomcat + +go 1.23 diff --git a/internal/rpc/rpc.go b/internal/rpc/rpc.go new file mode 100644 index 0000000..c1ff773 --- /dev/null +++ b/internal/rpc/rpc.go @@ -0,0 +1,368 @@ +// Package rpc implements the minimal LSP-framed Lithe backend protocol for +// a packaged Go plugin. It does not speak to the network or run arbitrary RPCs. +package rpc + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +const MaxFrameBytes = 64 << 20 +const MaxHeaderBytes = 8192 + +type RPCError struct { + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data,omitempty"` +} + +func (e *RPCError) Error() string { return e.Message } +func Failed(code, message string) error { + return &RPCError{Code: -32000, Message: message, Data: map[string]string{"code": code}} +} + +type Ref struct { + ContextID string `json:"contextID"` + Generation int `json:"generation"` +} +type Invocation struct { + FunctionID string `json:"functionID"` + OperationID string `json:"operationID"` + Context *Ref `json:"context"` + Params json.RawMessage `json:"params"` +} +type Handler func(context.Context, Invocation, *Server) (any, error) + +type frame struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method,omitempty"` + Params json.RawMessage `json:"params,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Error *RPCError `json:"error,omitempty"` +} + +type Server struct { + r *bufio.Reader + w io.Writer + outputMu sync.Mutex + stateMu sync.Mutex + initialized bool + shuttingDown bool + incoming map[string]context.CancelFunc + pending map[string]chan frame + nextID atomic.Int64 + handlers map[string]Handler + onExit func(runID string) +} + +func New(r io.Reader, w io.Writer) *Server { + return &Server{r: bufio.NewReader(r), w: w, incoming: make(map[string]context.CancelFunc), pending: make(map[string]chan frame), handlers: make(map[string]Handler)} +} +func (s *Server) Function(id string, h Handler) { s.handlers[id] = h } +func (s *Server) OnRunExit(h func(string)) { s.onExit = h } + +func readFrame(r *bufio.Reader) (frame, error) { + var m frame + nhead := 0 + length := -1 + for { + line, err := r.ReadString('\n') + if err != nil { + return m, err + } + nhead += len(line) + if nhead > MaxHeaderBytes { + return m, errors.New("header exceeds limit") + } + line = strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r") + if line == "" { + break + } + before, after, ok := strings.Cut(line, ":") + if !ok || !strings.EqualFold(strings.TrimSpace(before), "Content-Length") { + continue + } + if length != -1 { + return m, errors.New("duplicate Content-Length") + } + after = strings.TrimSpace(after) + if after == "" { + return m, errors.New("empty Content-Length") + } + for _, c := range after { + if c < '0' || c > '9' { + return m, errors.New("invalid Content-Length") + } + } + parsed, err := strconv.Atoi(after) + if err != nil || parsed > MaxFrameBytes || parsed < 0 { + return m, errors.New("frame exceeds limit") + } + length = parsed + } + if length < 0 { + return m, errors.New("missing Content-Length") + } + raw := make([]byte, length) + if _, err := io.ReadFull(r, raw); err != nil { + return m, err + } + if err := json.Unmarshal(raw, &m); err != nil { + return m, err + } + return m, nil +} +func writeFrame(w io.Writer, v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + header := []byte(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(data))) + if _, err = w.Write(header); err != nil { + return err + } + _, err = w.Write(data) + return err +} +func (s *Server) send(v any) error { + s.outputMu.Lock() + defer s.outputMu.Unlock() + return writeFrame(s.w, v) +} +func (s *Server) reply(id json.RawMessage, value any, reqErr error) { + if reqErr != nil { + var e *RPCError + if !errors.As(reqErr, &e) { + e = &RPCError{Code: -32000, Message: reqErr.Error(), Data: map[string]string{"code": "tomcat.failed"}} + } + if len(e.Message) > 1024 { + e.Message = e.Message[:1024] + } + _ = s.send(map[string]any{"jsonrpc": "2.0", "id": id, "error": e}) + return + } + if value == nil { + value = json.RawMessage("null") + } + _ = s.send(map[string]any{"jsonrpc": "2.0", "id": id, "result": value}) +} +func validObject(raw json.RawMessage) bool { + if len(raw) == 0 { + return true + } + b := bytes.TrimSpace(raw) + return len(b) > 1 && b[0] == '{' && b[len(b)-1] == '}' +} +func rawKey(v json.RawMessage) string { return string(bytes.TrimSpace(v)) } +func (s *Server) handle(m frame) { + if m.Method == "" && len(m.ID) > 0 { + key := rawKey(m.ID) + s.stateMu.Lock() + ch := s.pending[key] + delete(s.pending, key) + s.stateMu.Unlock() + if ch != nil { + select { + case ch <- m: + default: + } + } + return + } + if m.Method == "$/cancelRequest" { + var p struct { + ID json.RawMessage `json:"id"` + } + _ = json.Unmarshal(m.Params, &p) + s.stateMu.Lock() + fn := s.incoming[rawKey(p.ID)] + s.stateMu.Unlock() + if fn != nil { + fn() + } + return + } + if m.Method == "exit" { + return + } + if m.Method == "lithe/host/run/didExit" { + var p struct { + RunID string `json:"runID"` + } + if json.Unmarshal(m.Params, &p) == nil && s.onExit != nil { + s.onExit(p.RunID) + } + return + } + if len(m.ID) == 0 { + return + } + switch m.Method { + case "initialize": + s.stateMu.Lock() + ready := s.initialized || s.shuttingDown + s.stateMu.Unlock() + if ready { + s.reply(m.ID, nil, &RPCError{Code: -32600, Message: "initialize already received"}) + return + } + var params struct { + Capabilities struct { + Experimental struct { + Functions struct { + Versions []int `json:"versions"` + } `json:"litheFunctions"` + Logging struct { + Versions []int `json:"versions"` + } `json:"litheLogging"` + } `json:"experimental"` + } `json:"capabilities"` + } + if err := json.Unmarshal(m.Params, ¶ms); err != nil { + s.reply(m.ID, nil, &RPCError{Code: -32602, Message: "invalid initialization"}) + return + } + offered := func(list []int) bool { + for _, v := range list { + if v == 0 { + return true + } + } + return false + } + if !offered(params.Capabilities.Experimental.Logging.Versions) || !offered(params.Capabilities.Experimental.Functions.Versions) { + s.reply(m.ID, nil, &RPCError{Code: -32600, Message: "backend requires litheLogging 0 and litheFunctions 0"}) + return + } + funcs := make([]map[string]string, 0, len(s.handlers)) + for id := range s.handlers { + funcs = append(funcs, map[string]string{"id": id}) + } + // Order is deterministic for feature snapshots. + for i := 0; i < len(funcs); i++ { + for j := i + 1; j < len(funcs); j++ { + if funcs[j]["id"] < funcs[i]["id"] { + funcs[j], funcs[i] = funcs[i], funcs[j] + } + } + } + s.stateMu.Lock() + s.initialized = true + s.stateMu.Unlock() + s.reply(m.ID, map[string]any{ + "serverInfo": map[string]string{"name": "lithe-tomcat-backend", "version": "0.2.0"}, + "capabilities": map[string]any{"experimental": map[string]any{"litheLogging": map[string]int{"version": 0}, "litheFunctions": map[string]any{"version": 0, "functions": funcs}}}, + }, nil) + case "shutdown": + s.stateMu.Lock() + s.shuttingDown = true + for _, cancel := range s.incoming { + cancel() + } + s.stateMu.Unlock() + s.reply(m.ID, nil, nil) + case "lithe/function/invoke": + s.stateMu.Lock() + ready := s.initialized && !s.shuttingDown + s.stateMu.Unlock() + if !ready { + s.reply(m.ID, nil, &RPCError{Code: -32002, Message: "backend not initialized"}) + return + } + var inv Invocation + if !validObject(m.Params) || json.Unmarshal(m.Params, &inv) != nil || inv.Context == nil || inv.Context.ContextID == "" || inv.Context.Generation < 1 || !validObject(inv.Params) { + s.reply(m.ID, nil, &RPCError{Code: -32602, Message: "invalid function params"}) + return + } + handler := s.handlers[inv.FunctionID] + if handler == nil { + s.reply(m.ID, nil, &RPCError{Code: -32601, Message: "unknown function"}) + return + } + ctx, cancel := context.WithCancel(context.Background()) + key := rawKey(m.ID) + s.stateMu.Lock() + s.incoming[key] = cancel + s.stateMu.Unlock() + go func() { + defer cancel() + defer func() { s.stateMu.Lock(); delete(s.incoming, key); s.stateMu.Unlock() }() + value, err := handler(ctx, inv, s) + if ctx.Err() != nil { + err = &RPCError{Code: -32800, Message: "request cancelled"} + } + s.reply(m.ID, value, err) + }() + default: + s.reply(m.ID, nil, &RPCError{Code: -32601, Message: "unsupported method"}) + } +} + +// Request calls a host service through the existing Lithe backend connection. +// It never sends the user's project data to any external service. +func (s *Server) Request(ctx context.Context, method string, params any, out any) error { + s.stateMu.Lock() + ready := s.initialized && !s.shuttingDown + s.stateMu.Unlock() + if !ready { + return errors.New("backend not ready") + } + id := "tomcat-" + strconv.FormatInt(s.nextID.Add(1), 10) + key := strconv.Quote(id) + ch := make(chan frame, 1) + s.stateMu.Lock() + s.pending[key] = ch + s.stateMu.Unlock() + defer func() { s.stateMu.Lock(); delete(s.pending, key); s.stateMu.Unlock() }() + if err := s.send(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}); err != nil { + return err + } + bounded, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + select { + case m := <-ch: + if m.Error != nil { + return m.Error + } + if out != nil { + return json.Unmarshal(m.Result, out) + } + return nil + case <-bounded.Done(): + return bounded.Err() + } +} + +// Listen blocks until the host ends the connection. Each invocation is async +// so host replies can be processed while a handler awaits a host request. +func (s *Server) Listen() error { + for { + m, err := readFrame(s.r) + if err != nil { + s.stateMu.Lock() + for _, cancel := range s.incoming { + cancel() + } + s.stateMu.Unlock() + if errors.Is(err, io.EOF) { + return nil + } + return err + } + if m.Method == "exit" { + return nil + } + s.handle(m) + } +} diff --git a/internal/rpc/rpc_test.go b/internal/rpc/rpc_test.go new file mode 100644 index 0000000..95ca0cb --- /dev/null +++ b/internal/rpc/rpc_test.go @@ -0,0 +1,150 @@ +package rpc + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "io" + "strings" + "testing" + "time" +) + +func TestFrameWithUnicodeAndMultipleMessages(t *testing.T) { + var buf bytes.Buffer + values := []any{map[string]any{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]string{"label": "中文 Tomcat"}}, map[string]any{"jsonrpc": "2.0", "method": "initialized"}} + for _, v := range values { + if err := writeFrame(&buf, v); err != nil { + t.Fatal(err) + } + } + r := bufio.NewReader(&buf) + one, err := readFrame(r) + if err != nil || one.Method != "initialize" { + t.Fatal(one, err) + } + if !bytes.Contains(one.Params, []byte("中文 Tomcat")) { + t.Fatal("unicode damaged") + } + two, err := readFrame(r) + if err != nil || two.Method != "initialized" { + t.Fatal(two, err) + } +} +func TestFrameRejectsInvalidHeaders(t *testing.T) { + for _, raw := range []string{"Content-Length: -1\r\n\r\n", "Content-Length: 9999999999\r\n\r\n", "Content-Type: text/plain\r\n\r\n", "Content-Length: 10\r\nContent-Length: 20\r\n\r\n", strings.Repeat("X", MaxHeaderBytes) + "\r\n\r\n"} { + if _, err := readFrame(bufio.NewReader(strings.NewReader(raw))); err == nil { + t.Fatalf("accepted bad frame header: %q", raw[:min(40, len(raw))]) + } + } +} +func rpcPair(t *testing.T) (*Server, *bufio.Reader, io.WriteCloser, func()) { + t.Helper() + hostToBackend, hostWriter := io.Pipe() + hostReader, backendWriter := io.Pipe() + server := New(hostToBackend, backendWriter) + stop := func() { hostWriter.Close(); backendWriter.Close(); hostToBackend.Close(); hostReader.Close() } + return server, bufio.NewReader(hostReader), hostWriter, stop +} +func sendHost(t *testing.T, w io.Writer, obj any) { + t.Helper() + if err := writeFrame(w, obj); err != nil { + t.Fatal(err) + } +} +func initHost(t *testing.T, server *Server, reader *bufio.Reader, writer io.Writer) { + t.Helper() + sendHost(t, writer, map[string]any{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{"capabilities": map[string]any{"experimental": map[string]any{"litheLogging": map[string]any{"versions": []int{0}}, "litheFunctions": map[string]any{"versions": []int{0}}}}}}) + frame, err := readFrame(reader) + if err != nil { + t.Fatal(err) + } + if frame.Error != nil { + t.Fatal(frame.Error) + } + if !bytes.Contains(frame.Result, []byte("litheFunctions")) { + t.Fatal("not negotiated") + } +} +func TestFunctionHostRequestAndCancellation(t *testing.T) { + server, reader, writer, stop := rpcPair(t) + defer stop() + server.Function("tomcat.probe", func(ctx context.Context, call Invocation, server *Server) (any, error) { + var reply struct { + Value string `json:"value"` + } + err := server.Request(ctx, "lithe/host/getCapabilities", map[string]any{}, &reply) + if err != nil { + return nil, err + } + return map[string]string{"echo": reply.Value}, nil + }) + server.Function("tomcat.cancel", func(ctx context.Context, call Invocation, server *Server) (any, error) { + <-ctx.Done() + return nil, ctx.Err() + }) + done := make(chan error, 1) + go func() { done <- server.Listen() }() + initHost(t, server, reader, writer) + call := map[string]any{"jsonrpc": "2.0", "id": 2, "method": "lithe/function/invoke", "params": map[string]any{"functionID": "tomcat.probe", "operationID": "call-1", "context": map[string]any{"contextID": "workspace-1", "generation": 1}, "params": map[string]any{}}} + sendHost(t, writer, call) + requested, err := readFrame(reader) + if err != nil { + t.Fatal(err) + } + if requested.Method != "lithe/host/getCapabilities" { + t.Fatalf("expected host request: %#v", requested) + } + sendHost(t, writer, map[string]any{"jsonrpc": "2.0", "id": requested.ID, "result": map[string]string{"value": "host-ready"}}) + response, err := readFrame(reader) + if err != nil { + t.Fatal(err) + } + if response.Error != nil { + t.Fatal(response.Error) + } + if !bytes.Contains(response.Result, []byte("host-ready")) { + t.Fatalf("unexpected response: %s", response.Result) + } + sendHost(t, writer, map[string]any{"jsonrpc": "2.0", "id": 3, "method": "lithe/function/invoke", "params": map[string]any{"functionID": "tomcat.cancel", "operationID": "call-2", "context": map[string]any{"contextID": "workspace-1", "generation": 1}, "params": map[string]any{}}}) + sendHost(t, writer, map[string]any{"jsonrpc": "2.0", "method": "$/cancelRequest", "params": map[string]any{"id": 3}}) + // The reader serializes notifications, but a cancel may arrive before an + // asynchronous function has started: both must still be cancelled. + response, err = readFrame(reader) + if err != nil { + t.Fatal(err) + } + if response.Error == nil || response.Error.Code != -32800 { + t.Fatalf("expected cancellation: %#v", response) + } + sendHost(t, writer, map[string]any{"jsonrpc": "2.0", "id": 4, "method": "shutdown"}) + last, err := readFrame(reader) + if err != nil || last.Error != nil { + t.Fatal(last, err) + } + stop() + select { + case err := <-done: + if err != nil && !errors.Is(err, io.ErrClosedPipe) { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("backend failed to exit") + } +} +func TestInitializationRequiresLogging(t *testing.T) { + server, reader, writer, stop := rpcPair(t) + defer stop() + go server.Listen() + sendHost(t, writer, map[string]any{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{"capabilities": map[string]any{"experimental": map[string]any{"litheFunctions": map[string]any{"versions": []int{0}}}}}}) + msg, err := readFrame(reader) + if err != nil || msg.Error == nil { + t.Fatal(msg, err) + } + b, _ := json.Marshal(msg.Error) + if !bytes.Contains(b, []byte("litheLogging")) { + t.Fatal(string(b)) + } +} diff --git a/internal/tomcat/config.go b/internal/tomcat/config.go new file mode 100644 index 0000000..db2f931 --- /dev/null +++ b/internal/tomcat/config.go @@ -0,0 +1,256 @@ +// Package tomcat implements local Tomcat run and deploy planning. It never +// starts a process or mutates the source project as a side effect of planning. +package tomcat + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" +) + +const MaxWARSize int64 = 512 << 20 + +var contextName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$`) + +// Config is stored only under the host's per-workspace plugin state directory. +// War is workspace-relative; host-provided workspace roots are authoritative. +type Config struct { + Home string `json:"home"` + Base string `json:"base"` + WAR string `json:"war"` + Exploded string `json:"exploded"` + Artifact string `json:"artifact"` + Context string `json:"context"` + DebugPort int `json:"debugPort"` + WatchChanges bool `json:"watchChanges"` +} + +type Checked struct { + Config + HomePath string + BasePath string + Webapps string + Server ServerInfo + WARPath string + ExplodedPath string + TargetPath string +} + +func ValidateConfig(c Config) (Config, error) { + c.Home = strings.TrimSpace(c.Home) + c.Base = strings.TrimSpace(c.Base) + c.WAR = strings.TrimSpace(c.WAR) + c.Exploded = strings.TrimSpace(c.Exploded) + c.Artifact = strings.TrimSpace(c.Artifact) + c.Context = strings.TrimSpace(c.Context) + if c.Artifact == "" { + c.Artifact = "war" + } + if c.Artifact != "war" && c.Artifact != "exploded" { + return c, errors.New("artifact must be war or exploded") + } + if c.WatchChanges && c.Artifact != "war" { + return c, errors.New("automatic redeploy currently supports WAR artifacts only") + } + if c.Home == "" || !filepath.IsAbs(c.Home) { + return c, errors.New("Tomcat home must be an absolute directory") + } + if c.Base != "" && !filepath.IsAbs(c.Base) { + return c, errors.New("Catalina base must be an absolute directory or empty") + } + if c.Context == "" { + c.Context = "/" + } + if c.Context != "/" && (!strings.HasPrefix(c.Context, "/") || !contextName.MatchString(c.Context[1:]) || strings.EqualFold(c.Context, "/ROOT")) { + return c, errors.New("context must be / or a single /name segment (letters, digits, _ or -)") + } + if c.DebugPort == 0 { + c.DebugPort = 5005 + } + if c.DebugPort < 1024 || c.DebugPort > 65535 { + return c, errors.New("debug port must be 1024–65535") + } + for _, p := range []struct{ name, value string }{{"WAR", c.WAR}, {"exploded folder", c.Exploded}} { + if p.value == "" { + continue + } + clean := filepath.Clean(p.value) + if filepath.IsAbs(p.value) || clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || (runtime.GOOS != "windows" && strings.Contains(p.value, "\\")) || strings.Contains(p.value, ":") { + return c, fmt.Errorf("%s must be a workspace-relative path", p.name) + } + } + if c.WAR != "" && !strings.EqualFold(filepath.Ext(c.WAR), ".war") { + return c, errors.New("WAR must have a .war extension") + } + return c, nil +} + +func realDirectory(name, p string) (string, error) { + if p == "" { + return "", fmt.Errorf("%s path is empty", name) + } + r, err := filepath.EvalSymlinks(p) + if err != nil { + return "", fmt.Errorf("%s: %w", name, err) + } + r, err = filepath.Abs(r) + if err != nil { + return "", err + } + st, err := os.Stat(r) + if err != nil || !st.IsDir() { + return "", fmt.Errorf("%s is not a directory", name) + } + return r, nil +} + +func regularFile(path string) error { + st, err := os.Lstat(path) + if err != nil { + return err + } + if !st.Mode().IsRegular() { + return errors.New("not a regular file (symlinks are not allowed)") + } + return nil +} + +func Check(c Config, workspaceRoot string, requireWAR bool) (*Checked, error) { + c, err := ValidateConfig(c) + if err != nil { + return nil, err + } + home, err := realDirectory("Tomcat home", c.Home) + if err != nil { + return nil, err + } + base := home + if c.Base != "" { + base, err = realDirectory("Catalina base", c.Base) + if err != nil { + return nil, err + } + } + for _, item := range []string{"bin/bootstrap.jar", "bin/tomcat-juli.jar", "lib/catalina.jar"} { + p := filepath.Join(home, filepath.FromSlash(item)) + if err := regularFile(p); err != nil { + return nil, fmt.Errorf("Tomcat installation missing %s: %w", item, err) + } + } + for _, item := range []string{"conf/server.xml", "conf/catalina.properties"} { + if err := regularFile(filepath.Join(base, filepath.FromSlash(item))); err != nil { + return nil, fmt.Errorf("Catalina base missing %s: %w", item, err) + } + } + server := inspectServerXML(base) + webapps, err := checkedAppBase(base, server) + if err != nil { + return nil, err + } + // Explicitly refuse a redirected webapps folder; it is the mutation boundary. + if st, err := os.Lstat(webapps); err != nil || !st.IsDir() || st.Mode()&os.ModeSymlink != 0 { + return nil, errors.New("Catalina base webapps must be a real directory, not a symlink") + } + c.Home, c.Base = home, base + checked := &Checked{Config: c, HomePath: home, BasePath: base, Webapps: webapps, Server: server} + name := "ROOT" + if c.Context != "/" { + name = c.Context[1:] + } + if c.Artifact == "exploded" { + checked.TargetPath = filepath.Join(webapps, name) + } else { + checked.TargetPath = filepath.Join(webapps, name+".war") + } + if !requireWAR { + return checked, nil + } + chosen := c.WAR + if c.Artifact == "exploded" { + chosen = c.Exploded + } + if chosen == "" { + return nil, fmt.Errorf("select a workspace-relative %s before deploying", c.Artifact) + } + root, err := realDirectory("Workspace", workspaceRoot) + if err != nil { + return nil, err + } + // Require the declared path to stay inside this workspace, even through symlinks. + candidate := filepath.Join(root, chosen) + st, err := os.Lstat(candidate) + if err != nil || st.Mode()&os.ModeSymlink != 0 { + return nil, errors.New("artifact must exist and must not be a symlink") + } + if c.Artifact == "war" && !st.Mode().IsRegular() { + return nil, errors.New("WAR must be a regular file") + } + if c.Artifact == "exploded" && !st.IsDir() { + return nil, errors.New("exploded artifact must be a directory") + } + real, err := filepath.EvalSymlinks(candidate) + if err != nil { + return nil, err + } + rel, err := filepath.Rel(root, real) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return nil, errors.New("artifact escapes the workspace") + } + st, err = os.Stat(real) + if err != nil { + return nil, err + } + if c.Artifact == "exploded" { + checked.ExplodedPath = real + return checked, nil + } + if !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() > MaxWARSize { + return nil, errors.New("WAR must be a nonempty regular file no larger than 512 MiB") + } + checked.WARPath = real + return checked, nil +} + +type RunPlan struct { + Executable map[string]string `json:"executable"` + Arguments []string `json:"arguments"` + WorkingDirectory string `json:"workingDirectory"` + Environment map[string]string `json:"environment"` +} + +// Startup runs Tomcat Bootstrap in the JVM selected by Lithe's Java tool. +// No shell, catalina.sh, cmd.exe, or user-supplied JVM argument is interpolated. +func (c *Checked) Startup(debug bool) RunPlan { + sep := ":" + if runtime.GOOS == "windows" { + sep = ";" + } + classpath := filepath.Join(c.HomePath, "bin", "bootstrap.jar") + sep + filepath.Join(c.HomePath, "bin", "tomcat-juli.jar") + args := []string{ + "-Dcatalina.home=" + c.HomePath, + "-Dcatalina.base=" + c.BasePath, + "-Djava.io.tmpdir=" + filepath.Join(c.BasePath, "temp"), + "-Djava.util.logging.config.file=" + filepath.Join(c.BasePath, "conf", "logging.properties"), + "-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager", + } + if debug { + args = append(args, "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:"+strconv.Itoa(c.DebugPort)) + } + args = append(args, "-classpath", classpath, "org.apache.catalina.startup.Bootstrap", "start") + return RunPlan{Executable: map[string]string{"kind": "tool", "tool": "java"}, Arguments: args, WorkingDirectory: ".", Environment: map[string]string{"CATALINA_HOME": c.HomePath, "CATALINA_BASE": c.BasePath}} +} + +func HashToken(parts ...string) string { + h := sha256.New() + for _, s := range parts { + _, _ = h.Write([]byte(strconv.Itoa(len(s)) + ":" + s)) + } + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/internal/tomcat/deploy.go b/internal/tomcat/deploy.go new file mode 100644 index 0000000..f356511 --- /dev/null +++ b/internal/tomcat/deploy.go @@ -0,0 +1,210 @@ +package tomcat + +import ( + "archive/zip" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" + "unicode/utf8" +) + +type DeployPlan struct { + Artifact string `json:"artifact"` + Context string `json:"context"` + Source string `json:"source"` + Target string `json:"target"` + SourceHash string `json:"sourceSha256"` + ExistingHash string `json:"existingSha256,omitempty"` + Action string `json:"action"` + Files int `json:"files,omitempty"` + Bytes int64 `json:"bytes,omitempty"` + Token string `json:"confirmationToken"` + Warning string `json:"warning"` +} + +func shaFile(p string) (string, error) { + f, err := os.Open(p) + if err != nil { + return "", err + } + defer f.Close() + h := sha256.New() + if _, err = io.Copy(h, io.LimitReader(f, MaxWARSize+1)); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +// InspectDeploy performs no writes. The token binds the user's confirmation to +// the exact source bytes and destination state observed at preview time. +func InspectDeploy(checked *Checked) (*DeployPlan, error) { + if checked.Artifact == "exploded" { + return inspectExploded(checked) + } + if checked.WARPath == "" { + return nil, errors.New("WAR not selected") + } + f, err := os.Open(checked.WARPath) + if err != nil { + return nil, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return nil, err + } + zr, err := zip.NewReader(f, st.Size()) + if err != nil { + return nil, fmt.Errorf("not a valid WAR ZIP: %w", err) + } + if len(zr.File) == 0 || len(zr.File) > 20_000 { + return nil, errors.New("WAR archive has an invalid entry count") + } + // Tomcat may unpack WAR entries after deployment. Reject traversal, + // links, and unbounded expanded content before handing it to Tomcat. + var expanded uint64 + for _, entry := range zr.File { + name := entry.Name + clean := path.Clean(name) + if name == "" || !utf8.ValidString(name) || strings.ContainsAny(name, "\\\x00") || + strings.HasPrefix(name, "/") || strings.Contains(name, ":") || + clean == ".." || strings.HasPrefix(clean, "../") || + entry.FileInfo().Mode()&os.ModeSymlink != 0 { + return nil, errors.New("WAR contains an unsafe archive entry") + } + expanded += entry.UncompressedSize64 + if expanded > 2<<30 { + return nil, errors.New("WAR expanded size exceeds the 2 GiB limit") + } + } + srcHash, err := shaFile(checked.WARPath) + if err != nil { + return nil, err + } + plan := &DeployPlan{Artifact: "war", Context: checked.Context, Source: checked.WARPath, Target: checked.TargetPath, SourceHash: srcHash, Action: "create", Warning: "Deploy while Tomcat is stopped. An existing exploded deployment may be recreated by Tomcat on start."} + st, err = os.Lstat(checked.TargetPath) + if err == nil { + if !st.Mode().IsRegular() { + return nil, errors.New("existing deployment target is not a regular file") + } + if st.Size() > MaxWARSize { + return nil, errors.New("existing deployment target is too large") + } + old, err := shaFile(checked.TargetPath) + if err != nil { + return nil, err + } + plan.ExistingHash = old + plan.Action = "replace" + } else if !os.IsNotExist(err) { + return nil, err + } + plan.Token = HashToken(plan.Artifact, plan.Source, plan.Target, plan.SourceHash, plan.ExistingHash, plan.Action) + return plan, nil +} + +// Deploy atomically creates a new WAR, or replaces one only after an explicit +// preview token. External changes after preview are rejected. This never +// removes an exploded directory or deploys an arbitrary filesystem path. +func Deploy(checked *Checked, confirmationToken string) (*DeployPlan, error) { + if checked.Artifact == "exploded" { + return deployExploded(checked, confirmationToken) + } + plan, err := InspectDeploy(checked) + if err != nil { + return nil, err + } + if len(confirmationToken) != len(plan.Token) || subtle.ConstantTimeCompare([]byte(confirmationToken), []byte(plan.Token)) != 1 { + return nil, errors.New("deployment changed since preview; inspect and confirm again") + } + dir := checked.Webapps + stage, err := os.CreateTemp(dir, ".lithe-tomcat-stage-*.war") + if err != nil { + return nil, err + } + stagePath := stage.Name() + defer os.Remove(stagePath) + if err := stage.Chmod(0644); err != nil { + stage.Close() + return nil, err + } + src, err := os.Open(checked.WARPath) + if err != nil { + stage.Close() + return nil, err + } + copied, err := io.Copy(stage, io.LimitReader(src, MaxWARSize+1)) + closeErr := src.Close() + if err == nil { + err = closeErr + } + if err == nil && copied > MaxWARSize { + err = errors.New("WAR exceeded the size limit") + } + if err == nil { + err = stage.Sync() + } + if e := stage.Close(); err == nil { + err = e + } + if err != nil { + return nil, err + } + newHash, err := shaFile(stagePath) + if err != nil || newHash != plan.SourceHash { + return nil, errors.New("source WAR changed during deployment; retry") + } + // Recheck target just before the write (including symlinks). Never overwrite + // other files without a preview that includes their exact content digest. + latest, err := InspectDeploy(checked) + if err != nil { + return nil, err + } + if latest.Token != plan.Token { + return nil, errors.New("deployment target changed since preview; retry") + } + if plan.Action == "create" { + // Atomic no-clobber creation on the same volume; os.Rename alone would + // silently replace a new file created between inspect and commit. + if err := os.Link(stagePath, plan.Target); err != nil { + return nil, fmt.Errorf("cannot create WAR without overwriting: %w", err) + } + return plan, nil + } + if !strings.EqualFold(filepath.Ext(plan.Target), ".war") { + return nil, errors.New("target is not a WAR") + } + backup, err := os.CreateTemp(dir, ".lithe-tomcat-backup-*.war") + if err != nil { + return nil, err + } + backupPath := backup.Name() + if err := backup.Close(); err != nil { + os.Remove(backupPath) + return nil, err + } + if err := os.Remove(backupPath); err != nil { + return nil, err + } + if err := os.Rename(plan.Target, backupPath); err != nil { + return nil, err + } + if err := os.Rename(stagePath, plan.Target); err != nil { + restoreErr := os.Rename(backupPath, plan.Target) + if restoreErr != nil { + return nil, fmt.Errorf("WAR install failed: %v; restoration failed: %w; backup at %s", err, restoreErr, backupPath) + } + return nil, err + } + if err := os.Remove(backupPath); err != nil { + return nil, fmt.Errorf("WAR installed, but old backup could not be removed at %s: %w", backupPath, err) + } + return plan, nil +} diff --git a/internal/tomcat/discover.go b/internal/tomcat/discover.go new file mode 100644 index 0000000..bf15e18 --- /dev/null +++ b/internal/tomcat/discover.go @@ -0,0 +1,245 @@ +package tomcat + +import ( + "encoding/xml" + "io" + "os" + "path/filepath" + "sort" + "strings" +) + +// WebModule is a bounded, read-only projection of a Java Web Facet and the +// build artifact candidates. The Java plugin remains the authority for JDKs, +// project libraries, classpaths and Maven/Gradle imports. +type WebModule struct { + Name string `json:"name"` + Path string `json:"path"` + Model string `json:"model"` + Facet string `json:"facet"` + WebRoot string `json:"webRoot"` + Descriptor string `json:"descriptor,omitempty"` + WARCandidates []string `json:"warCandidates"` + ExplodedCandidates []string `json:"explodedCandidates"` +} + +func smallXML(path string, value any) bool { + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 { + return false + } + f, err := os.Open(path) + if err != nil { + return false + } + defer f.Close() + decoder := xml.NewDecoder(io.LimitReader(f, 1<<20)) + return decoder.Decode(value) == nil +} + +func existsDir(path string) bool { + s, e := os.Lstat(path) + return e == nil && s.IsDir() && s.Mode()&os.ModeSymlink == 0 +} +func existsFile(path string) bool { + s, e := os.Lstat(path) + return e == nil && s.Mode().IsRegular() +} +func workspaceRelative(root, p string) string { + rel, err := filepath.Rel(root, p) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return "" + } + return filepath.ToSlash(rel) +} + +// DiscoverWebModules visits only the workspace root and its immediate child +// folders, and inspects known web/IDE layout paths. It never recursively walks +// a project or evaluates IDE-specified absolute URLs. +func DiscoverWebModules(root string) ([]WebModule, error) { + root, err := realDirectory("Workspace", root) + if err != nil { + return nil, err + } + candidates := []string{root} + children, err := os.ReadDir(root) + if err != nil { + return nil, err + } + if len(children) > 20000 { + return nil, os.ErrInvalid + } + for _, child := range children { + if len(candidates) >= 65 { + break + } + if child.IsDir() && !strings.HasPrefix(child.Name(), ".") && child.Name() != "target" && child.Name() != "build" && child.Name() != "node_modules" { + if existsDir(filepath.Join(root, child.Name())) { + candidates = append(candidates, filepath.Join(root, child.Name())) + } + } + } + modules := make([]WebModule, 0) + for _, dir := range candidates { + name := filepath.Base(dir) + m := WebModule{Name: name, Path: workspaceRelative(root, dir), Model: "legacy", WARCandidates: []string{}, ExplodedCandidates: []string{}} + if existsFile(filepath.Join(dir, "pom.xml")) { + m.Model = "maven" + } else if existsFile(filepath.Join(dir, "build.gradle")) || existsFile(filepath.Join(dir, "build.gradle.kts")) { + m.Model = "gradle" + } else if existsFile(filepath.Join(dir, ".project")) { + m.Model = "eclipse" + } + roots := []string{"src/main/webapp", "WebContent", "WebRoot", "webapp", "src/webapp"} + for _, rp := range roots { + full := filepath.Join(dir, filepath.FromSlash(rp)) + if existsDir(full) { + m.WebRoot = workspaceRelative(root, full) + descriptor := filepath.Join(full, "WEB-INF", "web.xml") + if existsFile(descriptor) { + m.Descriptor = workspaceRelative(root, descriptor) + } + break + } + } + var facet struct { + XMLName xml.Name `xml:"faceted-project"` + Installed []struct { + Facet string `xml:"facet,attr"` + Version string `xml:"version,attr"` + } `xml:"installed"` + } + if smallXML(filepath.Join(dir, ".settings", "org.eclipse.wst.common.project.facet.core.xml"), &facet) { + for _, item := range facet.Installed { + if item.Facet == "jst.web" { + m.Facet = "Eclipse WTP Web " + item.Version + break + } + } + } + var comp struct { + Modules []struct { + Resources []struct { + Path string `xml:"source-path,attr"` + Deploy string `xml:"deploy-path,attr"` + } `xml:"wb-resource"` + } `xml:"wb-module"` + } + if smallXML(filepath.Join(dir, ".settings", "org.eclipse.wst.common.component"), &comp) { + if m.Facet == "" { + m.Facet = "Eclipse WTP" + } + if m.WebRoot == "" { + for _, mod := range comp.Modules { + for _, r := range mod.Resources { + if r.Deploy != "/" { + continue + } + relative := strings.TrimPrefix(r.Path, "/") + candidate := filepath.Join(dir, filepath.FromSlash(relative)) + if existsDir(candidate) && workspaceRelative(root, candidate) != "" { + m.WebRoot = workspaceRelative(root, candidate) + break + } + } + } + } + } + // IDEA Web facets are recorded in module .iml files. Read known + // local .iml names only; never expand IDE global path macros. + imls := []string{filepath.Join(dir, name+".iml")} + if entry, err := os.ReadDir(dir); err == nil && len(entry) < 5000 { + for _, e := range entry { + if len(imls) >= 17 { + break + } + if !e.IsDir() && strings.HasSuffix(strings.ToLower(e.Name()), ".iml") { + p := filepath.Join(dir, e.Name()) + if p != imls[0] { + imls = append(imls, p) + } + } + } + } + for _, iml := range imls { + var module struct { + Components []struct { + Facets []struct { + Type string `xml:"type,attr"` + Configuration struct { + WebRoots []struct { + URL string `xml:"url,attr"` + } `xml:"webroots>root"` + Descriptors []struct { + URL string `xml:"url,attr"` + } `xml:"descriptors>deploymentDescriptor"` + } `xml:"configuration"` + } `xml:"facet"` + } `xml:"component"` + } + if !smallXML(iml, &module) { + continue + } + for _, comp := range module.Components { + for _, f := range comp.Facets { + if f.Type != "web" { + continue + } + m.Facet = "IntelliJ Web" + if m.Model == "legacy" { + m.Model = "idea" + } + for _, rootURL := range f.Configuration.WebRoots { + const prefix = "file://$MODULE_DIR$/" + if !strings.HasPrefix(rootURL.URL, prefix) { + continue + } + p := filepath.Join(filepath.Dir(iml), filepath.FromSlash(strings.TrimPrefix(rootURL.URL, prefix))) + if existsDir(p) { + if rel := workspaceRelative(root, p); rel != "" { + m.WebRoot = rel + break + } + } + } + for _, d := range f.Configuration.Descriptors { + const prefix = "file://$MODULE_DIR$/" + if !strings.HasPrefix(d.URL, prefix) { + continue + } + p := filepath.Join(filepath.Dir(iml), filepath.FromSlash(strings.TrimPrefix(d.URL, prefix))) + if existsFile(p) { + m.Descriptor = workspaceRelative(root, p) + break + } + } + } + } + } + for _, artifactDir := range []string{"target", "build/libs", "build/distributions"} { + base := filepath.Join(dir, filepath.FromSlash(artifactDir)) + entries, err := os.ReadDir(base) + if err != nil || len(entries) > 3000 { + continue + } + for _, e := range entries { + if len(m.WARCandidates) >= 16 && len(m.ExplodedCandidates) >= 16 { + break + } + p := filepath.Join(base, e.Name()) + if !e.IsDir() && strings.EqualFold(filepath.Ext(e.Name()), ".war") && existsFile(p) && len(m.WARCandidates) < 16 { + m.WARCandidates = append(m.WARCandidates, workspaceRelative(root, p)) + } + if e.IsDir() && len(m.ExplodedCandidates) < 16 && existsDir(p) && existsDir(filepath.Join(p, "WEB-INF")) { + m.ExplodedCandidates = append(m.ExplodedCandidates, workspaceRelative(root, p)) + } + } + } + if m.WebRoot == "" && m.Facet == "" && len(m.WARCandidates) == 0 && len(m.ExplodedCandidates) == 0 { + continue + } + modules = append(modules, m) + } + sort.Slice(modules, func(i, j int) bool { return modules[i].Path < modules[j].Path }) + return modules, nil +} diff --git a/internal/tomcat/exploded.go b/internal/tomcat/exploded.go new file mode 100644 index 0000000..020915f --- /dev/null +++ b/internal/tomcat/exploded.go @@ -0,0 +1,243 @@ +package tomcat + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" +) + +const maxExplodedFiles = 20_000 +const maxExplodedDepth = 24 + +// treeDigest hashes both relative names and every regular file's bytes. It +// never follows links, including links that appear in a nested directory. +// The same bound applies to sources, deployed destinations and staged copies. +func treeDigest(root string) (string, int, int64, error) { + st, err := os.Lstat(root) + if err != nil { + return "", 0, 0, err + } + if !st.IsDir() || st.Mode()&os.ModeSymlink != 0 { + return "", 0, 0, errors.New("exploded artifact must be a real directory") + } + h := sha256.New() + files := 0 + var bytes int64 + err = filepath.WalkDir(root, func(p string, e os.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(root, p) + if err != nil { + return err + } + if rel == "." { + return nil + } + if len(rel) > 1024 || strings.Count(rel, string(filepath.Separator)) >= maxExplodedDepth { + return errors.New("exploded artifact path or depth exceeds limit") + } + info, err := os.Lstat(p) + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("exploded artifact contains symbolic link: %s", rel) + } + if strings.HasPrefix(rel, ".git"+string(filepath.Separator)) || rel == ".git" || strings.HasPrefix(rel, ".idea"+string(filepath.Separator)) || rel == ".idea" { + return errors.New("exploded web root includes IDE or Git metadata") + } + normalized := filepath.ToSlash(rel) + if e.IsDir() { + _, _ = io.WriteString(h, "D:"+strconv.Itoa(len(normalized))+":"+normalized+"\n") + return nil + } + if !info.Mode().IsRegular() { + return fmt.Errorf("exploded artifact has special file: %s", rel) + } + files++ + if files > maxExplodedFiles || info.Size() > MaxWARSize || bytes > MaxWARSize-info.Size() { + return errors.New("exploded artifact exceeds file count or 512 MiB size limit") + } + bytes += info.Size() + _, _ = io.WriteString(h, "F:"+strconv.Itoa(len(normalized))+":"+normalized+":"+strconv.FormatInt(info.Size(), 10)+"\n") + file, err := os.Open(p) + if err != nil { + return err + } + copied, copyErr := io.Copy(h, io.LimitReader(file, info.Size()+1)) + closeErr := file.Close() + if copyErr != nil { + return copyErr + } + if closeErr != nil { + return closeErr + } + if copied != info.Size() { + return errors.New("exploded source changed during hash") + } + return nil + }) + if err != nil { + return "", 0, 0, err + } + if files == 0 { + return "", 0, 0, errors.New("exploded artifact has no files") + } + return hex.EncodeToString(h.Sum(nil)), files, bytes, nil +} + +func inspectExploded(c *Checked) (*DeployPlan, error) { + if c.ExplodedPath == "" { + return nil, errors.New("exploded artifact was not selected") + } + if equalOrWithin(c.ExplodedPath, c.TargetPath) || equalOrWithin(c.TargetPath, c.ExplodedPath) { + return nil, errors.New("exploded source overlaps the deployment destination") + } + if _, err := os.Lstat(strings.TrimSuffix(c.TargetPath, string(filepath.Separator)) + ".war"); err == nil { + return nil, errors.New("a WAR with the same context exists; remove the conflict manually before exploded deployment") + } else if !os.IsNotExist(err) { + return nil, err + } + srcHash, files, bytes, err := treeDigest(c.ExplodedPath) + if err != nil { + return nil, err + } + plan := &DeployPlan{Context: c.Context, Artifact: "exploded", Source: c.ExplodedPath, Target: c.TargetPath, SourceHash: srcHash, Action: "create", Files: files, Bytes: bytes, Warning: "Do not deploy into production. A deployed directory with the same name will be replaced only after reviewing this preview."} + if _, err := os.Lstat(c.TargetPath); err == nil { + oldHash, _, _, err := treeDigest(c.TargetPath) + if err != nil { + return nil, fmt.Errorf("existing deployment: %w", err) + } + plan.Action = "replace" + plan.ExistingHash = oldHash + } else if !os.IsNotExist(err) { + return nil, err + } + plan.Token = HashToken(plan.Artifact, plan.Source, plan.Target, plan.SourceHash, plan.ExistingHash, plan.Action) + return plan, nil +} + +func equalOrWithin(root, candidate string) bool { + rel, err := filepath.Rel(root, candidate) + return err == nil && (rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel))) +} + +func copyExploded(root, dest string) error { + return filepath.WalkDir(root, func(p string, e os.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(root, p) + if err != nil { + return err + } + if rel == "." { + return nil + } + info, err := os.Lstat(p) + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 { + return errors.New("artifact changed: symlink appeared") + } + q := filepath.Join(dest, rel) + if e.IsDir() { + return os.Mkdir(q, 0755) + } + if !info.Mode().IsRegular() { + return errors.New("artifact changed: non-regular file appeared") + } + in, err := os.Open(p) + if err != nil { + return err + } + out, err := os.OpenFile(q, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) + if err != nil { + in.Close() + return err + } + n, copyErr := io.Copy(out, io.LimitReader(in, MaxWARSize+1)) + if copyErr == nil && n > MaxWARSize { + copyErr = errors.New("source file exceeds limit") + } + if copyErr == nil { + copyErr = out.Sync() + } + if err := out.Close(); copyErr == nil { + copyErr = err + } + if err := in.Close(); copyErr == nil { + copyErr = err + } + return copyErr + }) +} + +func deployExploded(c *Checked, token string) (*DeployPlan, error) { + plan, err := inspectExploded(c) + if err != nil { + return nil, err + } + if len(token) != len(plan.Token) || subtle.ConstantTimeCompare([]byte(token), []byte(plan.Token)) != 1 { + return nil, errors.New("deployment changed since preview; inspect and confirm again") + } + stage, err := os.MkdirTemp(c.Webapps, ".lithe-stage-") + if err != nil { + return nil, err + } + defer os.RemoveAll(stage) + if err := copyExploded(c.ExplodedPath, stage); err != nil { + return nil, err + } + digest, files, bytes, err := treeDigest(stage) + if err != nil || digest != plan.SourceHash || files != plan.Files || bytes != plan.Bytes { + return nil, errors.New("exploded source changed during staging; retry") + } + latest, err := inspectExploded(c) + if err != nil { + return nil, err + } + if latest.Token != plan.Token { + return nil, errors.New("exploded target changed since preview; retry") + } + if plan.Action == "create" { + // Only the verified stage is moved. We reject an already-present + // target; the same-volume rename is atomic when that path is absent. + if _, err := os.Lstat(plan.Target); err == nil { + return nil, errors.New("deployment target appeared since preview") + } + if err := os.Rename(stage, plan.Target); err != nil { + return nil, err + } + return plan, nil + } + backup, err := os.MkdirTemp(c.Webapps, ".lithe-backup-") + if err != nil { + return nil, err + } + if err := os.Remove(backup); err != nil { + return nil, err + } + if err := os.Rename(plan.Target, backup); err != nil { + return nil, err + } + if err := os.Rename(stage, plan.Target); err != nil { + if restoreErr := os.Rename(backup, plan.Target); restoreErr != nil { + return nil, fmt.Errorf("deployment failed: %v; restore failed: %w; backup is %s", err, restoreErr, backup) + } + return nil, err + } + if err := os.RemoveAll(backup); err != nil { + return nil, fmt.Errorf("deployment succeeded, but backup cleanup failed at %s: %w", backup, err) + } + return plan, nil +} diff --git a/internal/tomcat/server_xml.go b/internal/tomcat/server_xml.go new file mode 100644 index 0000000..ad4a37c --- /dev/null +++ b/internal/tomcat/server_xml.go @@ -0,0 +1,90 @@ +package tomcat + +import ( + "encoding/xml" + "errors" + "os" + "path/filepath" + "strconv" + "strings" +) + +type ServerInfo struct { + XMLValid bool `json:"xmlValid"` + AppBase string `json:"appBase"` + AutoDeploy bool `json:"autoDeploy"` + DeployOnStartup bool `json:"deployOnStartup"` + HTTPPorts []int `json:"httpPorts"` +} + +type serverXML struct { + Services []struct { + Connectors []struct { + Port string `xml:"port,attr"` + Protocol string `xml:"protocol,attr"` + } `xml:"Connector"` + Engine struct { + Hosts []struct { + Name string `xml:"name,attr"` + AppBase string `xml:"appBase,attr"` + AutoDeploy string `xml:"autoDeploy,attr"` + DeployOnStartup string `xml:"deployOnStartup,attr"` + } `xml:"Host"` + } `xml:"Engine"` + } `xml:"Service"` +} + +// inspectServerXML does not expand entities or external schemas. Unknown or +// malformed server.xml disables online deployment rather than assuming it is +// enabled. Ordinary offline Run/Deploy still works with a standard appBase. +func inspectServerXML(base string) ServerInfo { + result := ServerInfo{AppBase: "webapps"} + p := filepath.Join(base, "conf", "server.xml") + raw, err := os.ReadFile(p) + if err != nil || len(raw) > 2<<20 { + return result + } + var v serverXML + if xml.Unmarshal(raw, &v) != nil { + return result + } + result.XMLValid = true + for _, svc := range v.Services { + for _, c := range svc.Connectors { + if strings.Contains(strings.ToUpper(c.Protocol), "AJP") { + continue + } + port, e := strconv.Atoi(c.Port) + if e == nil && port > 0 && port <= 65535 && len(result.HTTPPorts) < 16 { + result.HTTPPorts = append(result.HTTPPorts, port) + } + } + } + for _, svc := range v.Services { + for _, h := range svc.Engine.Hosts { + if h.Name != "" && h.Name != "localhost" { + continue + } + if h.AppBase != "" { + result.AppBase = h.AppBase + } + result.AutoDeploy = h.AutoDeploy != "false" + result.DeployOnStartup = h.DeployOnStartup != "false" + return result + } + } + // Cannot identify a Host; online deploy requires explicit evidence. + result.XMLValid = false + return result +} + +func checkedAppBase(base string, i ServerInfo) (string, error) { + if filepath.IsAbs(i.AppBase) || i.AppBase == "" || strings.HasPrefix(i.AppBase, "..") || strings.ContainsAny(i.AppBase, ":\\") { + return "", errors.New("custom absolute or parent Tomcat Host appBase is unsupported; use a Catalina base with a local appBase") + } + full := filepath.Join(base, filepath.Clean(i.AppBase)) + if !equalOrWithin(base, full) { + return "", errors.New("Tomcat Host appBase escapes Catalina base") + } + return full, nil +} diff --git a/internal/tomcat/state.go b/internal/tomcat/state.go new file mode 100644 index 0000000..82d20cd --- /dev/null +++ b/internal/tomcat/state.go @@ -0,0 +1,67 @@ +package tomcat + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" +) + +func LoadConfig(stateDir string) (Config, error) { + var c Config + if stateDir == "" { + return c, errors.New("workspace state is unavailable") + } + raw, err := os.ReadFile(filepath.Join(stateDir, "tomcat.json")) + if os.IsNotExist(err) { + return Config{Context: "/", DebugPort: 5005}, nil + } + if err != nil { + return c, err + } + if len(raw) > 16*1024 { + return c, errors.New("Tomcat config is too large") + } + if err := json.Unmarshal(raw, &c); err != nil { + return c, err + } + return c, nil +} +func SaveConfig(stateDir string, c Config) error { + if stateDir == "" { + return errors.New("workspace state is unavailable") + } + checked, err := ValidateConfig(c) + if err != nil { + return err + } + if err := os.MkdirAll(stateDir, 0700); err != nil { + return err + } + raw, err := json.MarshalIndent(checked, "", " ") + if err != nil { + return err + } + f, err := os.CreateTemp(stateDir, ".tomcat-config-*.tmp") + if err != nil { + return err + } + tmp := f.Name() + defer os.Remove(tmp) + if err := f.Chmod(0600); err != nil { + f.Close() + return err + } + if _, err := f.Write(raw); err != nil { + f.Close() + return err + } + if err := f.Sync(); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, filepath.Join(stateDir, "tomcat.json")) +} diff --git a/internal/tomcat/tomcat_test.go b/internal/tomcat/tomcat_test.go new file mode 100644 index 0000000..3e7bc4a --- /dev/null +++ b/internal/tomcat/tomcat_test.go @@ -0,0 +1,263 @@ +package tomcat + +import ( + "archive/zip" + "bytes" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func fixture(t *testing.T) (Config, string, string) { + t.Helper() + root := t.TempDir() + home := filepath.Join(root, "Tomcat with spaces") + workspace := filepath.Join(root, "Workspace") + for _, dir := range []string{"bin", "lib", "conf", "webapps", "temp"} { + if err := os.MkdirAll(filepath.Join(home, dir), 0755); err != nil { + t.Fatal(err) + } + } + for _, f := range []string{"bin/bootstrap.jar", "bin/tomcat-juli.jar", "lib/catalina.jar", "conf/server.xml", "conf/catalina.properties"} { + if err := os.WriteFile(filepath.Join(home, filepath.FromSlash(f)), []byte("fixture"), 0600); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(filepath.Join(workspace, "target"), 0755); err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + w := zip.NewWriter(&buf) + f, err := w.Create("WEB-INF/web.xml") + if err != nil { + t.Fatal(err) + } + if _, err = f.Write([]byte("")); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "target", "demo.war"), buf.Bytes(), 0644); err != nil { + t.Fatal(err) + } + return Config{Home: home, WAR: "target/demo.war", Context: "/demo", DebugPort: 5005}, workspace, home +} +func TestValidationAndJavaLaunch(t *testing.T) { + c, root, home := fixture(t) + check, err := Check(c, root, true) + if err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(check.TargetPath, filepath.Join("webapps", "demo.war")) { + t.Fatal(check.TargetPath) + } + args := check.Startup(true).Arguments + if !strings.Contains(strings.Join(args, " "), "127.0.0.1:5005") { + t.Fatalf("no localhost JDWP: %v", args) + } + if !strings.Contains(strings.Join(args, " "), "Tomcat with spaces") { + t.Fatalf("argument split/space lost: %v", args) + } + if check.Startup(false).WorkingDirectory != "." { + t.Fatal("wrong workspace working directory") + } + for _, bad := range []string{"../outside.war", "/etc/passwd", "../../evil.war", "target/not-a-war.exe", "target/../../demo.war"} { + c.WAR = bad + if _, err = Check(c, root, true); err == nil { + t.Fatalf("accepted unsafe path: %s", bad) + } + } + c.WAR = "target/demo.war" + c.Context = "/a/b" + if _, err = Check(c, root, false); err == nil { + t.Fatal("accepted nested context path") + } + c.Context = "/../x" + if _, err = Check(c, root, false); err == nil { + t.Fatal("accepted traversal context") + } + c.Context = "/demo" + c.DebugPort = 80 + if _, err = Check(c, root, false); err == nil { + t.Fatal("accepted privileged debug port") + } + // Starting Tomcat must not require an already-packaged WAR. + c.DebugPort = 5005 + c.WAR = "target/unbuilt.war" + if _, err := Check(c, root, false); err != nil { + t.Fatalf("blocked startup before build: %v", err) + } + if _, err := os.Lstat(home); err != nil { + t.Fatal(err) + } +} +func TestDeployPreviewIntegrityAndOverwrite(t *testing.T) { + c, root, home := fixture(t) + checked, err := Check(c, root, true) + if err != nil { + t.Fatal(err) + } + sourceBefore, err := os.ReadFile(checked.WARPath) + if err != nil { + t.Fatal(err) + } + preview, err := InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(preview.Target); !os.IsNotExist(err) { + t.Fatal("preview wrote file") + } + if _, err := Deploy(checked, "no-token"); err == nil { + t.Fatal("deployed without confirmation") + } + if _, err := Deploy(checked, preview.Token); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(preview.Target) + if err != nil || !bytes.Equal(got, sourceBefore) { + t.Fatal("WAR changed during deploy", err) + } + if _, err := Deploy(checked, preview.Token); err == nil { + t.Fatal("replayed stale preview") + } + replace, err := InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + if replace.Action != "replace" { + t.Fatal(replace.Action) + } + if _, err := Deploy(checked, replace.Token); err != nil { + t.Fatal(err) + } + // External mutation after preview must invalidate consent. + stale, err := InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(stale.Target, []byte("changed by external process"), 0644); err != nil { + t.Fatal(err) + } + if _, err := Deploy(checked, stale.Token); err == nil { + t.Fatal("overwrote external changes") + } + if err := os.Remove(stale.Target); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(home, "conf", "server.xml"), stale.Target); err == nil { + if _, err := InspectDeploy(checked); err == nil { + t.Fatal("accepted linked target") + } + if err := os.Remove(stale.Target); err != nil { + t.Fatal(err) + } + } + srcAfter, err := os.ReadFile(checked.WARPath) + if err != nil || !bytes.Equal(sourceBefore, srcAfter) { + t.Fatal("source modified") + } + entries, err := os.ReadDir(checked.Webapps) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("left deployment staging or backup files: %v", entries) + } +} +func TestRejectSymlinkAndCorruptWAR(t *testing.T) { + c, root, home := fixture(t) + outside := filepath.Join(t.TempDir(), "elsewhere.war") + data, err := os.ReadFile(filepath.Join(root, c.WAR)) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(outside, data, 0644); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(root, "target", "linked.war")); err == nil { + c.WAR = "target/linked.war" + if _, err := Check(c, root, true); err == nil { + t.Fatal("accepted symlinked source") + } + } + c.WAR = "target/demo.war" + if err := os.WriteFile(filepath.Join(root, c.WAR), []byte("not actually a WAR"), 0600); err != nil { + t.Fatal(err) + } + check, err := Check(c, root, true) + if err != nil { + t.Fatal(err) + } + if _, err := InspectDeploy(check); err == nil { + t.Fatal("accepted non-zip WAR") + } + if err := os.RemoveAll(filepath.Join(home, "webapps")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(root, filepath.Join(home, "webapps")); err == nil { + if _, err := Check(c, root, false); err == nil { + t.Fatal("accepted redirected webapps") + } + } +} +func TestWorkspaceStateOnly(t *testing.T) { + state := filepath.Join(t.TempDir(), "private-state") + got, err := LoadConfig(state) + if err != nil || got.DebugPort != 5005 { + t.Fatal(got, err) + } + c := Config{Home: filepath.Join(t.TempDir(), "not inspected yet"), Context: "/test", WAR: "target/out.war", DebugPort: 5656} + if err := SaveConfig(state, c); err != nil { + t.Fatal(err) + } + saved, err := LoadConfig(state) + if err != nil || saved.Context != "/test" { + t.Fatal(saved, err) + } + f, err := os.Open(filepath.Join(state, "tomcat.json")) + if err != nil { + t.Fatal(err) + } + defer f.Close() + stat, err := f.Stat() + if err != nil { + t.Fatal(err) + } + if stat.Size() > 16<<10 { + t.Fatal("state too large") + } + if _, err := io.ReadAll(f); err != nil { + t.Fatal(err) + } +} + +func TestRejectArchiveTraversalAndOversizedContents(t *testing.T) { + c, root, _ := fixture(t) + path := filepath.Join(root, c.WAR) + for _, name := range []string{"../escape.txt", "x/../../escape", "/absolute.txt", "C:/windows.txt", "dir\\tricky"} { + var data bytes.Buffer + w := zip.NewWriter(&data) + f, err := w.Create(name) + if err != nil { + t.Fatal(err) + } + _, _ = f.Write([]byte("invalid")) + if err := w.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data.Bytes(), 0644); err != nil { + t.Fatal(err) + } + checked, err := Check(c, root, true) + if err != nil { + t.Fatal(err) + } + if _, err := InspectDeploy(checked); err == nil { + t.Fatalf("accepted unsafe ZIP name %q", name) + } + } +} diff --git a/internal/tomcat/web_test.go b/internal/tomcat/web_test.go new file mode 100644 index 0000000..541d231 --- /dev/null +++ b/internal/tomcat/web_test.go @@ -0,0 +1,213 @@ +package tomcat + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestExplodedDeploymentAndConflicts(t *testing.T) { + cfg, root, home := fixture(t) + cfg.Artifact = "exploded" + cfg.Exploded = "target/app" + web := filepath.Join(root, "target", "app") + for _, dir := range []string{"WEB-INF/classes/demo", "assets"} { + if err := os.MkdirAll(filepath.Join(web, filepath.FromSlash(dir)), 0755); err != nil { + t.Fatal(err) + } + } + write := func(name, data string) { + t.Helper() + if err := os.WriteFile(filepath.Join(web, filepath.FromSlash(name)), []byte(data), 0644); err != nil { + t.Fatal(err) + } + } + write("WEB-INF/web.xml", "") + write("WEB-INF/classes/demo/App.class", "fake-class") + write("assets/style.css", "body{margin:0}") + checked, err := Check(cfg, root, true) + if err != nil { + t.Fatal(err) + } + plan, err := InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + if plan.Artifact != "exploded" || plan.Files != 3 || plan.Action != "create" { + t.Fatalf("plan=%+v", plan) + } + if _, err := os.Lstat(plan.Target); !os.IsNotExist(err) { + t.Fatal("preview modified destination") + } + if _, err := Deploy(checked, "invalid"); err == nil { + t.Fatal("deployed without confirmation") + } + if _, err := Deploy(checked, plan.Token); err != nil { + t.Fatal(err) + } + deployed, err := os.ReadFile(filepath.Join(plan.Target, "WEB-INF/classes/demo/App.class")) + if err != nil || string(deployed) != "fake-class" { + t.Fatal(err, string(deployed)) + } + if _, err := Deploy(checked, plan.Token); err == nil { + t.Fatal("reused stale preview token") + } + replacement, err := InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + write("assets/style.css", "body{background:black}") + if _, err := Deploy(checked, replacement.Token); err == nil { + t.Fatal("accepted source mutation") + } + replacement, err = InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + if replacement.Action != "replace" { + t.Fatal(replacement) + } + if _, err := Deploy(checked, replacement.Token); err != nil { + t.Fatal(err) + } + newFile, err := os.ReadFile(filepath.Join(plan.Target, "assets/style.css")) + if err != nil || !bytes.Equal(newFile, []byte("body{background:black}")) { + t.Fatal(err) + } + stale, err := InspectDeploy(checked) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(plan.Target, "assets/style.css"), []byte("external"), 0644); err != nil { + t.Fatal(err) + } + if _, err := Deploy(checked, stale.Token); err == nil { + t.Fatal("overwrote externally changed deployed directory") + } + // Never replace an exploded deployment while a WAR of the same context exists. + if err := os.WriteFile(filepath.Join(home, "webapps", "demo.war"), []byte("conflict"), 0644); err != nil { + t.Fatal(err) + } + if _, err := InspectDeploy(checked); err == nil { + t.Fatal("accepted conflicting WAR and exploded deployment") + } +} + +func TestExplodedSymlinkAndMetadataRejection(t *testing.T) { + cfg, root, _ := fixture(t) + cfg.Artifact = "exploded" + cfg.Exploded = "target/app" + web := filepath.Join(root, "target", "app") + if err := os.MkdirAll(filepath.Join(web, "WEB-INF"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(web, "WEB-INF", "web.xml"), []byte(""), 0644); err != nil { + t.Fatal(err) + } + checked, err := Check(cfg, root, true) + if err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(root, "target", "demo.war"), filepath.Join(web, "linked.war")); err == nil { + if _, err := InspectDeploy(checked); err == nil { + t.Fatal("accepted source symlink") + } + if err := os.Remove(filepath.Join(web, "linked.war")); err != nil { + t.Fatal(err) + } + } + if err := os.Mkdir(filepath.Join(web, ".git"), 0755); err != nil { + t.Fatal(err) + } + if _, err := InspectDeploy(checked); err == nil { + t.Fatal("accepted .git metadata in deployment") + } + if err := os.Remove(filepath.Join(web, ".git")); err != nil { + t.Fatal(err) + } + cfg.Exploded = "../escape" + if _, err := Check(cfg, root, true); err == nil { + t.Fatal("accepted exploded path traversal") + } + cfg.Exploded = "target/app" + cfg.WatchChanges = true + if _, err := ValidateConfig(cfg); err == nil { + t.Fatal("accepted exploded auto redeployment") + } +} + +func TestDetectWebFacetsAndArtifacts(t *testing.T) { + _, root, _ := fixture(t) + eclipse := filepath.Join(root, "old-web") + idea := filepath.Join(root, "idea-web") + for _, dir := range []string{ + "old-web/WebContent/WEB-INF", "old-web/.settings", "old-web/target", + "idea-web/custom/web/WEB-INF", "idea-web/target/myweb/WEB-INF", + } { + if err := os.MkdirAll(filepath.Join(root, filepath.FromSlash(dir)), 0755); err != nil { + t.Fatal(err) + } + } + for name, contents := range map[string]string{ + "old-web/.project": "old-web", + "old-web/.settings/org.eclipse.wst.common.project.facet.core.xml": "", + "old-web/.settings/org.eclipse.wst.common.component": "", + "old-web/WebContent/WEB-INF/web.xml": "", + "idea-web/idea-web.iml": "", + "idea-web/custom/web/WEB-INF/web.xml": "", + "idea-web/target/myweb/WEB-INF/web.xml": "", + } { + if err := os.WriteFile(filepath.Join(root, filepath.FromSlash(name)), []byte(contents), 0644); err != nil { + t.Fatal(err) + } + } + _ = eclipse + _ = idea + if err := os.WriteFile(filepath.Join(root, "old-web/target/old-web.war"), []byte("fake"), 0644); err != nil { + t.Fatal(err) + } + found, err := DiscoverWebModules(root) + if err != nil { + t.Fatal(err) + } + if len(found) != 3 { + t.Fatalf("found %d: %+v", len(found), found) + } + byName := map[string]WebModule{} + for _, m := range found { + byName[m.Name] = m + } + if !strings.Contains(byName["old-web"].Facet, "Eclipse") || byName["old-web"].WebRoot != "old-web/WebContent" || len(byName["old-web"].WARCandidates) != 1 { + t.Fatalf("eclipse: %+v", byName["old-web"]) + } + if !strings.Contains(byName["idea-web"].Facet, "IntelliJ") || byName["idea-web"].WebRoot != "idea-web/custom/web" || len(byName["idea-web"].ExplodedCandidates) != 1 { + t.Fatalf("idea: %+v", byName["idea-web"]) + } +} + +func TestServerAutoDeployAndCustomAppBase(t *testing.T) { + cfg, root, home := fixture(t) + xml := `` + if err := os.WriteFile(filepath.Join(home, "conf/server.xml"), []byte(xml), 0644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(home, "apps"), 0755); err != nil { + t.Fatal(err) + } + checked, err := Check(cfg, root, false) + if err != nil { + t.Fatal(err) + } + if checked.Server.AutoDeploy || !checked.Server.XMLValid || checked.Server.HTTPPorts[0] != 8090 || !strings.HasSuffix(checked.TargetPath, filepath.Join("apps", "demo.war")) { + t.Fatalf("server=%+v target=%s", checked.Server, checked.TargetPath) + } + xml = strings.ReplaceAll(xml, "appBase=\"apps\"", "appBase=\"../../other\"") + if err := os.WriteFile(filepath.Join(home, "conf/server.xml"), []byte(xml), 0644); err != nil { + t.Fatal(err) + } + if _, err := Check(cfg, root, false); err == nil { + t.Fatal("accepted escaping appBase") + } +} diff --git a/plugin.json b/plugin.json new file mode 100644 index 0000000..6d81724 --- /dev/null +++ b/plugin.json @@ -0,0 +1,62 @@ +{ + "schemaVersion": 0, + "id": "io.github.lithe-idea.tomcat", + "displayName": "Tomcat", + "version": "0.2.0", + "pluginAPIVersion": 0, + "requires": { + "backend": 0, + "ui": 0 + }, + "requiresTools": [ + "java" + ], + "vendor": { + "id": "io.github.lithe-idea", + "displayName": "Lithe Community", + "signatureRequirement": "none" + }, + "permissions": [ + "backend.launch", + "ui.contribute", + "ui.web", + "workspace.metadata", + "run.start" + ], + "activationEvents": [ + "onView:io.github.lithe-idea.tomcat.panel" + ], + "languages": [], + "ui": { + "toolWindows": [ + { + "id": "io.github.lithe-idea.tomcat.panel", + "title": "Tomcat", + "placement": "bottom", + "icon": { + "host": "services" + }, + "web": { + "entry": "ui/index.html" + } + } + ], + "commands": [ + { + "id": "io.github.lithe-idea.tomcat.open", + "title": "Open Tomcat", + "toolWindowID": "io.github.lithe-idea.tomcat.panel", + "placements": [ + "commandPalette", + "menu" + ] + } + ] + }, + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/lithe-tomcat-backend" + } + } +} diff --git a/scripts/package.py b/scripts/package.py new file mode 100644 index 0000000..486f8a0 --- /dev/null +++ b/scripts/package.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Cross-package one immutable Lithe Tomcat plugin per Go target. + +Only source files and the freshly compiled backend are included. The backend +binary is built for the selected target, never copied from a previous package. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import zipfile + +ROOT = Path(__file__).resolve().parent.parent +PLUGIN_ID = 'io.github.lithe-idea.tomcat' +TARGETS = { + 'linux-amd64': ('linux', 'amd64'), + 'linux-arm64': ('linux', 'arm64'), + 'darwin-amd64': ('darwin', 'amd64'), + 'darwin-arm64': ('darwin', 'arm64'), + 'windows-amd64': ('windows', 'amd64'), +} + + +def build_one(target): + goos, goarch = TARGETS[target] + out = ROOT / '.dist' + out.mkdir(exist_ok=True) + exe = 'lithe-tomcat-backend.exe' if goos == 'windows' else 'lithe-tomcat-backend' + binary = out / 'bin' / target / exe + binary.parent.mkdir(parents=True, exist_ok=True) + env = {**os.environ, 'GOOS': goos, 'GOARCH': goarch, 'CGO_ENABLED': '0'} + subprocess.run(['go', 'build', '-trimpath', '-ldflags=-s -w', '-o', str(binary), './cmd/tomcat-backend'], cwd=ROOT, env=env, check=True) + + manifest = json.loads((ROOT / 'plugin.json').read_text(encoding='utf-8')) + assert manifest['id'] == PLUGIN_ID + assert manifest['backend']['launch']['kind'] == 'packaged' + manifest['backend']['launch']['path'] = 'bin/' + exe + contents = { + 'plugin.json': (json.dumps(manifest, ensure_ascii=False, indent=2) + '\n').encode('utf-8'), + 'LICENSE': (ROOT / 'LICENSE').read_bytes(), + 'README.md': (ROOT / 'README.md').read_bytes(), + 'ui/index.html': (ROOT / 'ui/index.html').read_bytes(), + 'ui/style.css': (ROOT / 'ui/style.css').read_bytes(), + 'ui/app.js': (ROOT / 'ui/app.js').read_bytes(), + 'bin/' + exe: binary.read_bytes(), + } + archive = out / f'lithe-plugin-tomcat-{manifest["version"]}-{target}.zip' + # Archive paths include the plugin directory (the installer expects it). + with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as z: + for rel, content in sorted(contents.items()): + name = PLUGIN_ID + '/' + rel + entry = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + entry.compress_type = zipfile.ZIP_DEFLATED + entry.external_attr = (0o100755 if rel.startswith('bin/') else 0o100644) << 16 + z.writestr(entry, content, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9) + check_archive(archive) + digest = hashlib.sha256(archive.read_bytes()).hexdigest() + archive.with_suffix(archive.suffix + '.sha256').write_text(digest + ' ' + archive.name + '\n', encoding='utf-8') + print(f'{archive} {digest}') + return archive + + +def check_archive(archive): + with zipfile.ZipFile(archive) as z: + names = z.namelist() + assert len(names) == 7 and len(names) == len(set(names)) + assert all(n.startswith(PLUGIN_ID + '/') and '/..' not in n for n in names) + assert not any((m.external_attr >> 16) & 0o170000 == 0o120000 for m in z.infolist()) + manifest = json.loads(z.read(PLUGIN_ID + '/plugin.json')) + backend = PLUGIN_ID + '/' + manifest['backend']['launch']['path'] + assert backend in names + exe = z.read(backend) + assert len(exe) > 100 * 1024 + assert (exe[:2] == b'MZ') if archive.name.endswith('windows-amd64.zip') else (exe[:4] in {b'\x7fELF', b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf', b'\xca\xfe\xba\xbe'}) + html = z.read(PLUGIN_ID + '/ui/index.html') + assert b'app.js' in html and b'style.css' in html + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--target', choices=TARGETS) + parser.add_argument('--all', action='store_true') + args = parser.parse_args() + if args.all == bool(args.target): + parser.error('specify exactly one of --target or --all') + for target in TARGETS if args.all else [args.target]: + build_one(target) + + +if __name__ == '__main__': + main() diff --git a/scripts/test_package.py b/scripts/test_package.py new file mode 100644 index 0000000..4b90f54 --- /dev/null +++ b/scripts/test_package.py @@ -0,0 +1,110 @@ +"""Archive layout and compiled-binary protocol smoke tests. + +This is deliberately not a native Lithe or real Apache Tomcat e2e test. +""" +import hashlib +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +import zipfile + +ROOT = Path(__file__).resolve().parent.parent +DIST = ROOT / '.dist' +ID = 'io.github.lithe-idea.tomcat' +TARGETS = ('linux-amd64', 'linux-arm64', 'darwin-amd64', 'darwin-arm64', 'windows-amd64') + + +class PluginArchiveTests(unittest.TestCase): + def test_all_platform_archives_are_structurally_valid(self): + for target in TARGETS: + with self.subTest(target=target): + archive = DIST / f'lithe-plugin-tomcat-0.2.0-{target}.zip' + self.assertTrue(archive.is_file(), archive) + with zipfile.ZipFile(archive) as z: + self.assertEqual(len(z.namelist()), 7) + prefix = ID + '/' + self.assertTrue(all(n.startswith(prefix) for n in z.namelist())) + manifest = json.loads(z.read(prefix + 'plugin.json')) + self.assertEqual(manifest['id'], ID) + self.assertEqual(manifest['requires'], {'backend': 0, 'ui': 0}) + self.assertEqual(manifest['requiresTools'], ['java']) + self.assertEqual(set(manifest['activationEvents']), {f'onView:{ID}.panel'}) + self.assertEqual(manifest['permissions'], ['backend.launch', 'ui.contribute', 'ui.web', 'workspace.metadata', 'run.start']) + exe = 'bin/lithe-tomcat-backend.exe' if target.startswith('windows') else 'bin/lithe-tomcat-backend' + self.assertEqual(manifest['backend']['launch']['path'], exe) + self.assertIn(prefix + exe, z.namelist()) + self.assertIn(b'', '') + page.set_content(html) + page.evaluate(BRIDGE_STUB) + page.add_style_tag(content=(ROOT/'ui/style.css').read_text(encoding='utf-8')) + page.add_script_tag(content=(ROOT/'ui/app.js').read_text(encoding='utf-8')) + page.wait_for_function("document.querySelector('#home').value === '/opt/apache-tomcat'") + self.assertTrue(page.get_by_text('服务器配置', exact=True).is_visible()) + page.wait_for_function("document.querySelector('#modules').textContent.includes('Eclipse WTP')") + self.assertTrue(page.get_by_text('Web 模块 / Facet', exact=True).is_visible()) + page.locator('#previewDeploy').click() + self.assertTrue(page.locator('#confirmBox').is_visible()) + self.assertIn('demo.war', page.locator('#planTarget').inner_text()) + out = ROOT/'.artifacts'/'panel-preview.png' + out.parent.mkdir(exist_ok=True) + page.screenshot(path=str(out), full_page=True) + page.locator('#confirmDeploy').click() + page.wait_for_function("document.querySelector('#notice').textContent.includes('部署完成')") + self.assertFalse(page.locator('#confirmBox').is_visible()) + self.assertEqual(errors, []) + finally: + browser.close() + + def test_facet_selects_exploded_and_disables_auto_watcher(self): + with sync_playwright() as p: + browser = p.chromium.launch(executable_path='/usr/bin/chromium', headless=True, args=['--no-sandbox']) + try: + page = browser.new_page(viewport={'width': 1050, 'height': 860}) + errors = [] + page.on('pageerror', lambda e: errors.append(str(e))) + html = (ROOT / 'ui/index.html').read_text(encoding='utf-8').replace('', '') + page.set_content(html) + page.evaluate(BRIDGE_STUB) + page.add_style_tag(content=(ROOT / 'ui/style.css').read_text(encoding='utf-8')) + page.add_script_tag(content=(ROOT / 'ui/app.js').read_text(encoding='utf-8')) + page.wait_for_function("document.querySelector('#modules').textContent.includes('Eclipse WTP')") + page.locator('#watchChanges').check() + page.locator('#artifact').select_option('exploded') + self.assertTrue(page.locator('#explodedRow').is_visible()) + self.assertFalse(page.locator('#warRow').is_visible()) + self.assertFalse(page.locator('#watchChanges').is_checked()) + self.assertTrue(page.locator('#watchChanges').is_disabled()) + self.assertEqual(errors, []) + finally: + browser.close() diff --git a/ui/app.js b/ui/app.js new file mode 100644 index 0000000..d6d127a --- /dev/null +++ b/ui/app.js @@ -0,0 +1,60 @@ +'use strict'; +// All UI belongs to this plugin; do not interpolate project-controlled data +// into HTML. The host owns the window, file picker and Run/Debug sessions. +const bridge=window.lithe; +const zh=String(bridge?.context?.locale||navigator.language).toLowerCase().startsWith('zh'); +const words={ + subtitle:['Local Servlet container','本机 Servlet 容器'],webModules:['Web modules / Facets','Web 模块 / Facet'],rescan:['Rescan','重新扫描'], + webHelp:['The Java plugin owns SDKs, classpaths and libraries. This view discovers deployable Web facets and artifacts.','SDK、类路径和库由 Java 插件管理。本页仅识别可部署的 Web Facet 与产物。'], + configuration:['Configuration','服务器配置'],home:['Tomcat installation directory *','Tomcat 安装目录 *'],base:['Catalina base (optional)','Catalina Base(可选)'], + artifact:['Artifact type','部署产物类型'],kindWar:['WAR archive','WAR 压缩包'],kindExploded:['Exploded web application','Exploded WAR(展开目录)'], + war:['WAR file (relative to workspace)','WAR 文件(相对工作区)'],exploded:['Exploded web directory (relative to workspace)','Web 展开目录(相对工作区)'], + browse:['Browse','浏览'],context:['Context path','应用访问路径'],port:['Local JDWP port','本地 JDWP 端口'], + save:['Save configuration','保存配置'],inspect:['Inspect installation','检查安装'],server:['Server','服务器'], + start:['Start','启动'],debug:['Debug (Java attach)','调试(自动附加 Java)'],stop:['Stop','停止'], + debugHelp:['Lithe starts a localhost-only JDWP listener and attaches the Java Support debugger. The Java plugin must be installed.','Lithe 将启动仅监听本机的 JDWP 并附加 Java Support 调试器;需要安装 Java 插件。'], + watchChanges:['Auto-redeploy updated WAR (opt-in)','WAR 变化后自动重部署(需主动启用)'],watchHelp:['Requires a first confirmed deployment, a managed Tomcat run, and autoDeploy=true in server.xml. Conflicts disable monitoring.','需先确认部署一次、由 Lithe 启动 Tomcat,并在 server.xml 中启用 autoDeploy;出现文件冲突会停止监控。'], + deployment:['Web deployment','Web 应用部署'], + deployHelp:['Stop Tomcat first. WAR and exploded artifacts must be in this workspace; review the destination before replacing.','请先停止 Tomcat。WAR 或展开目录必须位于当前工作区;替换前请检查目标位置。'], + previewDeploy:['Preview deployment','预览部署'],source:['Source','源文件'],destination:['Destination','目标位置'],operation:['Operation','操作'],confirmDeploy:['Confirm deployment','确认部署'],cancel:['Cancel','取消'],refresh:['Refresh','刷新'] +}; +const tr=(en,cn)=>zh?cn:en; +const $=id=>document.getElementById(id); +for(const e of document.querySelectorAll('[data-i18n]')){const pair=words[e.dataset.i18n];if(pair)e.textContent=pair[Number(zh)]} +document.documentElement.lang=zh?'zh-CN':'en'; +let workspaceRoot='',saved=null,plan=null,busy=false,running=false; +function info(message,isError=false){$('notice').textContent=String(message||'');$('notice').classList.toggle('error',isError)} +function toggleArtifact(){const exploded=$('artifact').value==='exploded';$('explodedRow').hidden=!exploded;$('warRow').hidden=exploded;$('watchChanges').disabled=exploded||running;if(exploded)$('watchChanges').checked=false;closePlan()} +function setBusy(v){busy=v;for(const id of ['refresh','discover','save','inspect','start','debug','stop','previewDeploy','confirmDeploy','pick']){$(id).disabled=busy || (id==='stop'&&!running) || (['start','debug'].includes(id)&&running) || (['previewDeploy','confirmDeploy'].includes(id)&&running&&!saved?.watchChanges) || (id==='save'&&running)}for(const id of ['home','base','war','exploded','artifact','context','port','watchChanges']){$(id).disabled=busy||running||(id==='watchChanges'&&$('artifact').value==='exploded')}} +function collect(){const n=Number($('port').value);return {home:$('home').value,base:$('base').value,artifact:$('artifact').value,war:$('war').value,exploded:$('exploded').value,context:$('context').value,debugPort:Number.isInteger(n)?n:0,watchChanges:$('watchChanges').checked}} +function render(c){for(const id of ['home','base','war','exploded','context'])$(id).value=c?.[id]||(id==='context'?'/':'');$('port').value=c?.debugPort||5005;$('artifact').value=c?.artifact||'war';$('watchChanges').checked=!!c?.watchChanges;toggleArtifact()} +function closePlan(){plan=null;$('confirmBox').hidden=true} +async function invoke(id,params={}){if(!bridge?.request)throw Error(tr('Lithe WebBridge is missing.','Lithe 网页桥不可用。'));const reply=await bridge.request('functions.invoke',{function:id,params});return reply.value} +async function task(fn){if(busy)return;setBusy(true);info('');try{const result=await fn();if(result)info(result)}catch(err){info(err?.message||String(err),true)}finally{setBusy(false)}} +async function refresh(){const r=await invoke('tomcat.get');workspaceRoot=r.workspaceRoot||'';saved=r.config||{};render(saved);running=!!r.running;$('runStatus').textContent=(running?tr('Running in Lithe: ','Lithe 运行中:')+r.runID:tr('No managed Tomcat session','没有由当前插件启动的 Tomcat 会话'))+(r.watching?tr(' · auto redeploy enabled',' · 已开启自动重部署'):'')+(r.watchError?'\n'+r.watchError:'');closePlan()} +async function save(){closePlan();await invoke('tomcat.save',{config:collect()});saved=collect();return tr('Configuration saved.','配置已保存。')} +function elt(tag,cls,body){const e=document.createElement(tag);if(cls)e.className=cls;if(body)e.textContent=body;return e} +async function discover(){const out=await invoke('tomcat.discover');const panel=$('modules');panel.replaceChildren();if(!out.modules?.length){panel.append(elt('p','muted',tr('No local Web facets or artifacts found.','没有发现本地 Web Facet 或部署产物。')));return ''} + for(const m of out.modules){const card=elt('article','module');card.append(elt('h3','',m.name+' · '+m.model));card.append(elt('p','',tr('Module: ','模块:')+(m.path||'.'))); + if(m.facet)card.append(elt('p','',tr('Facet: ','Facet:')+m.facet)); + if(m.webRoot)card.append(elt('p','',tr('Web root: ','Web 根目录:')+m.webRoot)); + if(m.descriptor)card.append(elt('p','', 'web.xml: '+m.descriptor)); + const actions=elt('div','actions'); + const choices=[...(m.warCandidates||[]).map(p=>['war',p]),...(m.explodedCandidates||[]).map(p=>['exploded',p])]; + if(m.webRoot)choices.push(['exploded',m.webRoot]); + for(const [kind,path] of choices.slice(0,8)){const btn=elt('button','secondary',tr('Use ','使用 ')+(kind==='war'?'WAR: ':'Web: ')+path.split('/').slice(-1)[0]);btn.type='button';btn.disabled=running;btn.addEventListener('click',()=>{ $('artifact').value=kind;toggleArtifact();$(kind).value=path;if($('context').value==='/')$('context').value='/'+m.name.replace(/[^A-Za-z0-9_-]/g,'').slice(0,79);closePlan();info(tr('Selected artifact; inspect and save before deploying.','已选择部署产物;请先检查并保存配置。'));});actions.append(btn)} + card.append(actions);panel.append(card)}return ''} +$('artifact').addEventListener('change',toggleArtifact); +for(const id of ['home','base','war','exploded','context','port','watchChanges'])$(id).addEventListener('input',closePlan); +$('refresh').addEventListener('click',()=>task(async()=>{await refresh();return tr('Refreshed.','已刷新。')})); +$('discover').addEventListener('click',()=>task(async()=>{await discover();return tr('Web modules scanned.','Web 模块扫描完成。')})); +$('save').addEventListener('click',()=>task(save)); +$('inspect').addEventListener('click',()=>task(async()=>{await save();const x=await invoke('tomcat.inspect');return tr('Tomcat installation valid: ','Tomcat 检查通过:')+x.home+'\nBase: '+x.base+'\nWebapps: '+x.webapps+'\nautoDeploy: '+(x.server?.xmlValid?x.server?.autoDeploy:'unknown')+'\nHTTP ports: '+(x.server?.httpPorts||[]).join(', ')})); +$('start').addEventListener('click',()=>task(async()=>{await save();const x=await invoke('tomcat.start',{debug:false});running=true;$('runStatus').textContent=tr('Running in Lithe','Lithe 已启动');return 'Run ID: '+x.runID})); +$('debug').addEventListener('click',()=>task(async()=>{await save();const x=await invoke('tomcat.start',{debug:true});running=true;$('runStatus').textContent=tr('Debugging','调试中');return tr('Started and requested Java attach on 127.0.0.1:','已启动并请求 Java 调试器附加 127.0.0.1:')+x.debugPort})); +$('stop').addEventListener('click',()=>task(async()=>{const x=await invoke('tomcat.stop');return tr('Stop requested: ','已请求停止:')+x.runID})); +$('previewDeploy').addEventListener('click',()=>task(async()=>{if(!running)await save();plan=await invoke('tomcat.planDeploy');$('planSource').textContent=plan.source;$('planTarget').textContent=plan.target;$('planArtifact').textContent=plan.artifact+(plan.files?' ('+plan.files+' files)':'');$('planAction').textContent=plan.action==='replace'?tr('Replace existing deployment','替换现有部署'):tr('New deployment','新建部署');$('planWarning').textContent=plan.warning;$('confirmBox').hidden=false;return tr('Review target and confirm.','请检查目标位置后明确确认。')})); +$('confirmDeploy').addEventListener('click',()=>task(async()=>{if(!plan)throw Error(tr('Preview first.','请先预览。'));const token=plan.confirmationToken;closePlan();const r=await invoke('tomcat.deploy',{confirmationToken:token});return tr('Deployed: ','部署完成:')+r.target})); +$('cancelDeploy').addEventListener('click',closePlan); +$('pick').addEventListener('click',()=>task(async()=>{const r=await bridge.request('dialog.openFile',{title:tr('Select WAR from workspace','从工作区选择 WAR'),extensions:['war']});if(!r?.path)return '';const root=workspaceRoot.replace(/\\/g,'/').replace(/\/$/,'');const full=r.path.replace(/\\/g,'/');const fold=bridge?.context?.platform==='windows';const a=fold?root.toLowerCase():root,b=fold?full.toLowerCase():full;if(!root||!b.startsWith(a+'/'))throw Error(tr('The WAR must be inside the workspace.','WAR 文件必须位于当前工作区。'));$('war').value=full.slice(root.length+1);closePlan();return ''})); +setBusy(false);task(async()=>{await refresh();await discover();return ''}); diff --git a/ui/index.html b/ui/index.html new file mode 100644 index 0000000..78b6382 --- /dev/null +++ b/ui/index.html @@ -0,0 +1,55 @@ + + + + + + Tomcat + + + + +
+
+

Tomcat

Local servlet container

+ +
+
+
+

Web modules / Facets

+

The Java plugin owns project libraries, SDKs and source paths. This view detects deployable Web facets and their artifacts.

+
+
+
+

Configuration

+
+ + + + + + + + +
+
+
+
+

Server

+

Not running in this Lithe session

+
+

Debug starts a loopback-only JDWP listener and asks Lithe to attach the Java Support debugger automatically.

+

Auto redeploy requires a first confirmed deployment, a Lithe-managed run and Tomcat Host autoDeploy=true. External file changes stop the watcher.

+
+
+

Web deployment

+

Stop Tomcat before deploying. WAR and exploded folders must be inside this workspace. Always review the exact target before replacing it.

+
+ +
+
+ + diff --git a/ui/style.css b/ui/style.css new file mode 100644 index 0000000..b097663 --- /dev/null +++ b/ui/style.css @@ -0,0 +1,20 @@ +:root{font-family:var(--lithe-font-family,system-ui,sans-serif);font-size:13px;color:var(--lithe-text,#dedee3);background:var(--lithe-background,#202124);color-scheme:light dark} +*{box-sizing:border-box}body{margin:0}main{max-width:910px;padding:16px 20px 32px;margin:auto} +header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:14px}h1{font-size:19px;letter-spacing:-.3px;font-weight:650;margin:0}h2{font-size:14px;margin:0 0 14px;font-weight:650}header p{color:var(--lithe-text-secondary,#999);margin:4px 0 0;font-size:12px} +section{border-top:1px solid var(--lithe-border,#444);padding:19px 0 22px} +.form{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 20px}.form label{display:flex;flex-direction:column;gap:7px;min-width:0}.form label span{font-size:12px;color:var(--lithe-text-secondary,#aaa)}.war-field{grid-column:span 2} +input{height:32px;background:var(--lithe-input-background,transparent);border:1px solid var(--lithe-border,#666);border-radius:6px;color:inherit;font:inherit;padding:6px 9px;outline:none;min-width:0;width:100%}input:focus{border-color:var(--lithe-accent,#5a96df)} +.inline{display:flex;gap:8px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:17px}button{border:1px solid transparent;border-radius:6px;background:var(--lithe-accent,#427fcb);color:#fff;padding:7px 13px;font:inherit;cursor:pointer;white-space:nowrap}button.secondary{background:var(--lithe-surface,#36383e);border-color:var(--lithe-border,#555);color:inherit}button:disabled{opacity:.45;cursor:default} +.muted,.footnote{color:var(--lithe-text-secondary,#aaa);line-height:1.5;margin:4px 0;font-size:12px}.footnote{margin-top:12px}.notice{min-height:0;white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.5}.notice:not(:empty){padding:10px 12px;border:1px solid var(--lithe-border,#777);border-radius:6px;margin:4px 0 14px}.notice.error{border-color:#b65f5f;color:var(--lithe-text,#e8b3b3)} +#confirmBox{margin-top:14px;border:1px solid var(--lithe-border,#777);padding:15px;border-radius:8px}#confirmBox[hidden]{display:none}dl{margin:0}dl div{display:grid;grid-template-columns:105px minmax(0,1fr);gap:10px;margin-bottom:8px}dt{color:var(--lithe-text-secondary,#aaa)}dd{margin:0;overflow-wrap:anywhere}.warning{line-height:1.5;font-size:12px;color:var(--lithe-text-secondary,#baa);margin:10px 0 0} +@media(max-width:620px){main{padding:12px}.form{grid-template-columns:1fr}.war-field{grid-column:auto}dl div{grid-template-columns:1fr;gap:2px}} +/* Web-facet discovery complements the Java plugin's native project-structure page. */ +.section-head{display:flex;gap:12px;align-items:center;justify-content:space-between;margin-bottom:10px}.section-head h2{margin:0} +.modules{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,290px),1fr));gap:10px;margin-top:13px} +.module{border:1px solid var(--lithe-border,#555);border-radius:8px;padding:12px 14px;min-width:0;background:var(--lithe-surface,#27292e)} +.module h3{font-size:13px;margin:0 0 6px;font-weight:600}.module p{color:var(--lithe-text-secondary,#aaa);font-size:12px;white-space:normal;overflow-wrap:anywhere;margin:4px 0} +.module .actions{margin-top:9px}.module button{font-size:12px;padding:5px 9px} +select{height:32px;background:var(--lithe-input-background,#282a30);border:1px solid var(--lithe-border,#666);color:inherit;padding:4px 8px;border-radius:6px;min-width:0;width:100%} +#explodedRow[hidden],#warRow[hidden]{display:none} + +.watch-line{display:flex!important;flex-direction:row!important;align-items:center;gap:10px;line-height:1.5}.watch-line input{width:16px;height:16px;flex:none}.watch-line span{font-size:12px} From 9706e397223e9350350f4b9b66f64a1fb48dfb2b Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:10:38 +0000 Subject: [PATCH 2/5] test(ui): show real deployment artifact and refresh fixture screenshot --- scripts/test_ui.py | 2 +- ui/app.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/test_ui.py b/scripts/test_ui.py index b3fc111..ed41eff 100644 --- a/scripts/test_ui.py +++ b/scripts/test_ui.py @@ -19,7 +19,7 @@ if(p.function==='tomcat.save') return {value:{saved:true}}; if(p.function==='tomcat.discover') return {value:{modules:[{name:'old-web',path:'old-web',model:'eclipse',facet:'Eclipse WTP Web 3.1',webRoot:'old-web/WebContent',descriptor:'old-web/WebContent/WEB-INF/web.xml',warCandidates:['old-web/target/old-web.war'],explodedCandidates:['old-web/target/exploded']} ]}}; if(p.function==='tomcat.planDeploy') return {value:{source:'/workspace/target/demo.war', - target:'/opt/apache-tomcat/webapps/demo.war',action:'create', + target:'/opt/apache-tomcat/webapps/demo.war',action:'create',artifact:'war', warning:'Stop Tomcat before deployment.',confirmationToken:'a'.repeat(64)}}; if(p.function==='tomcat.deploy') return {value:{deployed:true,target:'/opt/apache-tomcat/webapps/demo.war'}}; throw Error('Unsupported function '+p.function); diff --git a/ui/app.js b/ui/app.js index d6d127a..bdc3b31 100644 --- a/ui/app.js +++ b/ui/app.js @@ -53,7 +53,7 @@ $('inspect').addEventListener('click',()=>task(async()=>{await save();const x=aw $('start').addEventListener('click',()=>task(async()=>{await save();const x=await invoke('tomcat.start',{debug:false});running=true;$('runStatus').textContent=tr('Running in Lithe','Lithe 已启动');return 'Run ID: '+x.runID})); $('debug').addEventListener('click',()=>task(async()=>{await save();const x=await invoke('tomcat.start',{debug:true});running=true;$('runStatus').textContent=tr('Debugging','调试中');return tr('Started and requested Java attach on 127.0.0.1:','已启动并请求 Java 调试器附加 127.0.0.1:')+x.debugPort})); $('stop').addEventListener('click',()=>task(async()=>{const x=await invoke('tomcat.stop');return tr('Stop requested: ','已请求停止:')+x.runID})); -$('previewDeploy').addEventListener('click',()=>task(async()=>{if(!running)await save();plan=await invoke('tomcat.planDeploy');$('planSource').textContent=plan.source;$('planTarget').textContent=plan.target;$('planArtifact').textContent=plan.artifact+(plan.files?' ('+plan.files+' files)':'');$('planAction').textContent=plan.action==='replace'?tr('Replace existing deployment','替换现有部署'):tr('New deployment','新建部署');$('planWarning').textContent=plan.warning;$('confirmBox').hidden=false;return tr('Review target and confirm.','请检查目标位置后明确确认。')})); +$('previewDeploy').addEventListener('click',()=>task(async()=>{if(!running)await save();plan=await invoke('tomcat.planDeploy');$('planSource').textContent=plan.source;$('planTarget').textContent=plan.target;$('planArtifact').textContent=(plan.artifact||'war')+(plan.files?' ('+plan.files+' files)':'');$('planAction').textContent=plan.action==='replace'?tr('Replace existing deployment','替换现有部署'):tr('New deployment','新建部署');$('planWarning').textContent=plan.warning;$('confirmBox').hidden=false;return tr('Review target and confirm.','请检查目标位置后明确确认。')})); $('confirmDeploy').addEventListener('click',()=>task(async()=>{if(!plan)throw Error(tr('Preview first.','请先预览。'));const token=plan.confirmationToken;closePlan();const r=await invoke('tomcat.deploy',{confirmationToken:token});return tr('Deployed: ','部署完成:')+r.target})); $('cancelDeploy').addEventListener('click',closePlan); $('pick').addEventListener('click',()=>task(async()=>{const r=await bridge.request('dialog.openFile',{title:tr('Select WAR from workspace','从工作区选择 WAR'),extensions:['war']});if(!r?.path)return '';const root=workspaceRoot.replace(/\\/g,'/').replace(/\/$/,'');const full=r.path.replace(/\\/g,'/');const fold=bridge?.context?.platform==='windows';const a=fold?root.toLowerCase():root,b=fold?full.toLowerCase():full;if(!root||!b.startsWith(a+'/'))throw Error(tr('The WAR must be inside the workspace.','WAR 文件必须位于当前工作区。'));$('war').value=full.slice(root.length+1);closePlan();return ''})); From 775ac00b99a0c9e696bacb28e4b81273a81e39a7 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:14:09 +0000 Subject: [PATCH 3/5] perf(tomcat): avoid rehashing unchanged WAR on idle watcher ticks --- cmd/tomcat-backend/watch.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/cmd/tomcat-backend/watch.go b/cmd/tomcat-backend/watch.go index e1559c4..d188646 100644 --- a/cmd/tomcat-backend/watch.go +++ b/cmd/tomcat-backend/watch.go @@ -151,7 +151,7 @@ func (s *session) watchChanges(ctx context.Context, runKey, runID string, c tomc defer ticker.Stop() var lastSize int64 = -1 var lastMod time.Time - stable := 0 + dirty := false for { select { case <-ctx.Done(): @@ -174,13 +174,15 @@ func (s *session) watchChanges(ctx context.Context, runKey, runID string, c tomc } if fi.Size() != lastSize || !fi.ModTime().Equal(lastMod) { lastSize, lastMod = fi.Size(), fi.ModTime() - stable = 0 + dirty = true continue } - stable++ - if stable < 1 { + // A size/mtime transition must remain stable for one full poll + // interval. Do not re-hash a large WAR on every idle tick. + if !dirty { continue } + dirty = false // Hash only after the size and timestamp have stopped changing; // avoid re-reading hundreds of MiB every polling interval. plan, err := tomcat.InspectDeploy(checked) From 774c7da378b7e8be38bb8b265b702b25d367c746 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:31:27 +0000 Subject: [PATCH 4/5] fix(tomcat): discover bounded nested Maven and Gradle Web modules --- internal/tomcat/discover.go | 60 +++++++++++++++++++++++++++---------- internal/tomcat/web_test.go | 49 ++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 16 deletions(-) diff --git a/internal/tomcat/discover.go b/internal/tomcat/discover.go index bf15e18..44c4aa3 100644 --- a/internal/tomcat/discover.go +++ b/internal/tomcat/discover.go @@ -53,32 +53,60 @@ func workspaceRelative(root, p string) string { return filepath.ToSlash(rel) } -// DiscoverWebModules visits only the workspace root and its immediate child -// folders, and inspects known web/IDE layout paths. It never recursively walks -// a project or evaluates IDE-specified absolute URLs. +// DiscoverWebModules uses a bounded breadth-first walk (at most three folder +// levels below the workspace). A Maven/Gradle aggregator may nest Web modules +// deeper than one level; deployment sources still must pass Check's stronger +// workspace/real-path validation before they can be used. func DiscoverWebModules(root string) ([]WebModule, error) { root, err := realDirectory("Workspace", root) if err != nil { return nil, err } + const maxDirectories = 256 + const maxDepth = 3 + const maxEntries = 20000 candidates := []string{root} - children, err := os.ReadDir(root) - if err != nil { - return nil, err - } - if len(children) > 20000 { - return nil, os.ErrInvalid - } - for _, child := range children { - if len(candidates) >= 65 { - break + depths := []int{0} + remaining := maxEntries + for index := 0; index < len(candidates) && len(candidates) < maxDirectories; index++ { + if depths[index] >= maxDepth { + continue } - if child.IsDir() && !strings.HasPrefix(child.Name(), ".") && child.Name() != "target" && child.Name() != "build" && child.Name() != "node_modules" { - if existsDir(filepath.Join(root, child.Name())) { - candidates = append(candidates, filepath.Join(root, child.Name())) + children, err := os.ReadDir(candidates[index]) + if err != nil { + if index == 0 { + return nil, err + } + continue + } + if len(children) > remaining { + if index == 0 { + return nil, os.ErrInvalid + } + break // Return candidates seen so far; never scan unbounded trees. + } + remaining -= len(children) + for _, child := range children { + if len(candidates) >= maxDirectories { + break + } + if !child.IsDir() || strings.HasPrefix(child.Name(), ".") { + continue + } + // Build outputs, dependencies and source/resource trees cannot + // contain an independent workspace module at this scope. + switch child.Name() { + case "target", "build", "node_modules", "vendor", "out", "bin", "dist", "src": + continue + } + nested := filepath.Join(candidates[index], child.Name()) + if existsDir(nested) { + candidates = append(candidates, nested) + depths = append(depths, depths[index]+1) } } } + modules := make([]WebModule, 0) for _, dir := range candidates { name := filepath.Base(dir) diff --git a/internal/tomcat/web_test.go b/internal/tomcat/web_test.go index 541d231..1e48c67 100644 --- a/internal/tomcat/web_test.go +++ b/internal/tomcat/web_test.go @@ -211,3 +211,52 @@ func TestServerAutoDeployAndCustomAppBase(t *testing.T) { t.Fatal("accepted escaping appBase") } } + +func TestDiscoverNestedWebModulesWithoutWalkingBuildDirectories(t *testing.T) { + _, root, _ := fixture(t) + for _, entry := range []string{ + "apps/services/booking/src/main/webapp/WEB-INF", + "apps/services/booking/target", + "apps/libs/site/build/libs", + "node_modules/fake/src/main/webapp/WEB-INF", + "target/generated/src/main/webapp/WEB-INF", + } { + if err := os.MkdirAll(filepath.Join(root, filepath.FromSlash(entry)), 0755); err != nil { + t.Fatal(err) + } + } + for name, data := range map[string]string{ + "apps/services/booking/pom.xml": "", + "apps/services/booking/src/main/webapp/WEB-INF/web.xml": "", + "apps/services/booking/target/booking.war": "placeholder", + "apps/libs/site/build.gradle": "plugins { id 'war' }", + "apps/libs/site/build/libs/site.war": "placeholder", + "node_modules/fake/src/main/webapp/WEB-INF/web.xml": "", + "target/generated/src/main/webapp/WEB-INF/web.xml": "", + } { + if err := os.WriteFile(filepath.Join(root, filepath.FromSlash(name)), []byte(data), 0644); err != nil { + t.Fatal(err) + } + } + found, err := DiscoverWebModules(root) + if err != nil { + t.Fatal(err) + } + byPath := make(map[string]WebModule) + for _, item := range found { + if strings.HasPrefix(item.Path, "node_modules/") || strings.HasPrefix(item.Path, "target/") { + t.Fatalf("scanned excluded build/dependency directory: %+v", item) + } + byPath[item.Path] = item + } + booking, ok := byPath["apps/services/booking"] + if !ok || booking.Model != "maven" || booking.WebRoot != "apps/services/booking/src/main/webapp" || + len(booking.WARCandidates) != 1 || booking.WARCandidates[0] != "apps/services/booking/target/booking.war" { + t.Fatalf("nested Maven web module: %+v (present=%v)", booking, ok) + } + site, ok := byPath["apps/libs/site"] + if !ok || site.Model != "gradle" || len(site.WARCandidates) != 1 || + site.WARCandidates[0] != "apps/libs/site/build/libs/site.war" { + t.Fatalf("nested Gradle WAR module: %+v (present=%v)", site, ok) + } +} From 55938481c36692573e565604d54ec70de91bfced Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:33:32 +0000 Subject: [PATCH 5/5] docs(tomcat): describe bounded nested Web module discovery and pending validation --- README.md | 2 +- TEST_RESULTS.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b50e4d..61b8ba4 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ An **independent, on-demand Tomcat integration** for Lithe-IDEA's Viva desktop. | Feature | 0.2.0 behavior | | --- | --- | -| Project/Web Facet discovery | Read-only discovery of Maven/Gradle web layouts, Eclipse WTP `.settings` web facets/component resources and IntelliJ `.iml` Web facets; finds local WAR and exploded output directories in each module. It does **not** rewrite IDE files. | +| Project/Web Facet discovery | Read-only bounded discovery of Maven/Gradle web layouts (up to three nested module-directory levels), Eclipse WTP `.settings` web facets/component resources and IntelliJ `.iml` Web facets; finds WAR and exploded outputs. It skips build/source/dependency trees (256 directory / 20,000 entry scan budget) and **never** rewrites IDE files. | | Project SDK, classpath, libraries | Remain in the existing **Java Support 4.x Project Structure** page (Sources / Paths / Dependencies, per-module JRE, library scope). Tomcat does not duplicate or override JDT's authoritative classpath. | | Tomcat installation | Explicit Catalina Home and optional Catalina Base; verifies Bootstrap and JULI JARs, config files, and real application base. Reads `server.xml` Host `appBase`/`autoDeploy` and HTTP connector ports without writing it. | | Run / Stop | Starts `org.apache.catalina.startup.Bootstrap` with the **JDK selected by Lithe** and host-owned Run lifecycle. No shell or arbitrary scripts, and no bundled Tomcat/JDK. | diff --git a/TEST_RESULTS.md b/TEST_RESULTS.md index d567bba..cf0418a 100644 --- a/TEST_RESULTS.md +++ b/TEST_RESULTS.md @@ -18,3 +18,7 @@ 4. **JavaEE extras** — JSP/EL completion, auto WAR build, Maven profile wiring, classpath-global libraries and editing Web Facet declarations are separate future work and are not represented as completed here. Run local checks via README. Review GitHub Actions separately after the PR has been created; no CI result is claimed until observed. + +## Additional unverified change (Tomcat PR #1) + +- Bounded nested module discovery now includes Maven and Gradle Web modules up to three directory levels below the workspace; it skips `target`, `build`, `src`, `node_modules`, `vendor` and other generated trees. `TestDiscoverNestedWebModulesWithoutWalkingBuildDirectories` was added. **This new test has not been run on the updated branch in the current environment.** Keep the PR in Draft until CI or a local Go test run verifies the new commit and native Lithe/Tomcat acceptance follows.