You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/09/02 22:19:14 UTC

(groovy) 02/02: GROOVY-12334: groovysh: say what -f GROOVY on a URL actually grants, and show it

This is an automated email from the ASF dual-hosted git repository.

paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit 9141e9067a240c405b39af6cc0e4937a17335aa8
Author: Paul King <pa...@asert.com.au>
AuthorDate: Wed Sep 2 22:28:53 2026 +1000

    GROOVY-12334: groovysh: say what -f GROOVY on a URL actually grants, and show it
    
    Constraining AUTO left the impression that evaluating remote content was
    now the safe path rather than the authorised one. It is not safer. Asking
    for -f GROOVY against a URL runs whatever that server returns with the
    user's privileges; the only thing that changed is who chose it, the user
    rather than the payload. The guide now says that plainly instead of
    implying remoteness was what made the old sniffing wrong.
    
    Consent to run a URL's content is also weaker than it looks, because
    redirects are followed: the address typed need not be where the code came
    from. /slurp therefore prints the URL it was actually served from before
    evaluating, naming both when a redirect moved it. That changes no policy -
    the decision remains the user's - it just makes the decision visible at
    the point it is taken.
    
    The notice, the extension mapping, and the URL-path extension parsing are
    package-private so they can be tested without a terminal or a server;
    serving over HTTP is not something the test suite should need to do.
---
 .../groovy/groovysh/jline/GroovyCommands.groovy    | 54 +++++++++++++-
 .../groovy-groovysh/src/spec/doc/groovysh.adoc     | 13 +++-
 .../groovysh/jline/GroovyCommandsSlurpTest.groovy  | 87 ++++++++++++++++++++++
 3 files changed, 149 insertions(+), 5 deletions(-)

diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy
index ef4e67ea26..aaea8f7d49 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy
@@ -45,6 +45,8 @@ import org.jline.terminal.Terminal
 import org.jline.terminal.impl.TerminalGraphics
 import org.jline.terminal.impl.TerminalGraphicsManager
 import org.jline.utils.AttributedString
+import org.jline.utils.AttributedStringBuilder
+import org.jline.utils.AttributedStyle
 
 import javax.imageio.ImageIO
 import javax.swing.ImageIcon
@@ -691,7 +693,11 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
                     // -f GROOVY rather than inferred from the address.
                     format = formatForExtension(extensionOf(url.path), false)
                 }
-                source = new InputStreamReader(url.openStream(), encoding)
+                URLConnection connection = url.openConnection()
+                source = new InputStreamReader(connection.inputStream, encoding)
+                if (format == 'GROOVY') {
+                    noteEvaluatingRemoteContent(input, url, connection)
+                }
             }
             if (source) {
                 if (format == 'TEXT') {
@@ -729,6 +735,46 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
         out
     }
 
+    /**
+     * Reports that content fetched over the network is about to be evaluated, naming where it was
+     * actually served from.
+     * <p>
+     * Asking for {@code -f GROOVY} grants the server code execution in this session, and redirects
+     * are followed, so the address typed is not necessarily the source the code came from. The
+     * decision is the user's to make, but it should be made visible at the point it is taken.
+     *
+     * @param input the command input, for terminal access
+     * @param requested the URL the user named
+     * @param connection the open connection, whose URL reflects any redirects followed
+     */
+    private static void noteEvaluatingRemoteContent(CommandInput input, URL requested, URLConnection connection) {
+        String message = remoteEvaluationNotice(requested, connection.URL)
+        def writer = input.terminal()?.writer()
+        if (writer) {
+            writer.println(new AttributedStringBuilder()
+                .style(AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW))
+                .append("/slurp: $message")
+                .style(AttributedStyle.DEFAULT)
+                .toAnsi(input.terminal()))
+            writer.flush()
+        }
+    }
+
+    /**
+     * The notice shown before remote content is evaluated, naming the URL actually served from and,
+     * when redirects moved it, the one that was asked for.
+     *
+     * @param requested the URL the user named
+     * @param served the URL the content came from, or {@code null} if unknown
+     * @return the message to display
+     */
+    // package-private for testing
+    static String remoteEvaluationNotice(URL requested, URL served) {
+        served && served.toString() != requested.toString()
+            ? "evaluating Groovy fetched from $served (redirected from $requested)"
+            : "evaluating Groovy fetched from $requested"
+    }
+
     /**
      * Maps a file extension onto a slurp format, or {@code null} when nothing matches (leaving the
      * caller to fall back on AUTO, which parses but never evaluates).
@@ -738,7 +784,8 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
      *                  local file the user named, false for content fetched over the network
      * @return the format name, or {@code null}
      */
-    private static String formatForExtension(String ext, boolean allowCode) {
+    // package-private for testing
+    static String formatForExtension(String ext, boolean allowCode) {
         if (!ext) return null
         switch (ext.toLowerCase(Locale.ROOT)) {
             case 'json': return 'JSON'
@@ -760,7 +807,8 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
      * @param path the URL path
      * @return the extension without the dot, or {@code null} when the last segment has none
      */
-    private static String extensionOf(String path) {
+    // package-private for testing
+    static String extensionOf(String path) {
         if (!path) return null
         int slash = path.lastIndexOf('/')
         String name = slash < 0 ? path : path.substring(slash + 1)
diff --git a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
index 23fed24bca..a115e96e98 100644
--- a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
+++ b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
@@ -1203,8 +1203,17 @@ request: pass `-f GROOVY`, or name a local `.groovy` file.
 For a URL, the extension of the URL path selects the format in the same way
 as a filename does, but only ever a data format &#8212; `GROOVY` is not inferred
 from an address, because the extension is part of the URL you typed while the
-bytes are whatever the server chooses to return. Use `-f GROOVY` if you really
-do want to evaluate what a URL serves.
+bytes are whatever the server chooses to return.
+
+WARNING: `-f GROOVY` against a URL runs whatever that server returns, with your
+privileges, in this session. It is not a safer way to evaluate remote content
+than the old content sniffing was &#8212; it is the *authorised* way, and the
+difference is only that you chose it rather than the payload choosing for you.
+Redirects are followed, so the address you typed is not necessarily where the
+code came from; `/slurp` prints the URL it was actually served from before
+evaluating it. Treat it as you would piping a download straight into a shell, and prefer
+fetching the content first (without `-f`) so you can read it before deciding
+to run it.
 
 Although the details of the exact object returned are an implementation
 detail which may change in the future, the current behavior is as follows:
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyCommandsSlurpTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyCommandsSlurpTest.groovy
new file mode 100644
index 0000000000..1763cda8fd
--- /dev/null
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyCommandsSlurpTest.groovy
@@ -0,0 +1,87 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.
+ */
+package org.apache.groovy.groovysh.jline
+
+import org.junit.jupiter.api.Test
+
+/**
+ * Format selection and the remote-evaluation notice for {@code /slurp}. Lives in the same package so
+ * the helpers can be exercised without standing up a terminal or an HTTP server.
+ */
+class GroovyCommandsSlurpTest {
+
+    // GROOVY-12334
+    @Test
+    void extensionSelectsADataFormat() {
+        assert GroovyCommands.formatForExtension('json', false) == 'JSON'
+        assert GroovyCommands.formatForExtension('YML', false) == 'YAML'
+        assert GroovyCommands.formatForExtension('markdown', false) == 'MARKDOWN'
+        assert GroovyCommands.formatForExtension('csv', true) == 'CSV'
+    }
+
+    // GROOVY-12334
+    @Test
+    void groovyIsSelectableForALocalFileButNeverForAUrl() {
+        assert GroovyCommands.formatForExtension('groovy', true) == 'GROOVY'
+        assert GroovyCommands.formatForExtension('groovy', false) == null
+    }
+
+    // GROOVY-12334
+    @Test
+    void unknownOrAbsentExtensionSelectsNothing() {
+        // null means "fall back to AUTO", which parses but never evaluates
+        assert GroovyCommands.formatForExtension('dat', true) == null
+        assert GroovyCommands.formatForExtension('', true) == null
+        assert GroovyCommands.formatForExtension(null, true) == null
+    }
+
+    // GROOVY-12334
+    @Test
+    void urlPathExtensionIsTakenFromTheLastSegmentOnly() {
+        assert GroovyCommands.extensionOf('/data/feed.json') == 'json'
+        assert GroovyCommands.extensionOf('/a.b.c/feed.yaml') == 'yaml'
+        assert GroovyCommands.extensionOf('/no/extension/here') == null
+        assert GroovyCommands.extensionOf('/trailing/slash/') == null
+        assert GroovyCommands.extensionOf('') == null
+        assert GroovyCommands.extensionOf(null) == null
+        // a dotfile has no extension to speak of
+        assert GroovyCommands.extensionOf('/dir/.hidden') == null
+    }
+
+    // GROOVY-12334
+    @Test
+    void noticeNamesTheUrlEvaluatedFrom() {
+        def url = new URL('http://example.test/x.groovy')
+        assert GroovyCommands.remoteEvaluationNotice(url, url) ==
+                'evaluating Groovy fetched from http://example.test/x.groovy'
+        assert GroovyCommands.remoteEvaluationNotice(url, null) ==
+                'evaluating Groovy fetched from http://example.test/x.groovy'
+    }
+
+    // GROOVY-12334
+    @Test
+    void noticeReportsBothUrlsWhenARedirectMovedTheContent() {
+        // the address typed is not necessarily where the code came from
+        def asked = new URL('http://example.test/x.groovy')
+        def served = new URL('http://elsewhere.test/payload.groovy')
+        assert GroovyCommands.remoteEvaluationNotice(asked, served) ==
+                'evaluating Groovy fetched from http://elsewhere.test/payload.groovy' +
+                ' (redirected from http://example.test/x.groovy)'
+    }
+}