eppleton commented on code in PR #9712: URL: https://github.com/apache/netbeans/pull/9712#discussion_r4726219816
########## agentic/acp.api/src/org/netbeans/modules/acp/api/AcpConnection.java: ########## @@ -0,0 +1,1251 @@ +/* + * 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.netbeans.modules.acp.api; + +import org.netbeans.modules.acp.spi.AcpMcpServerProvider; + +import com.agentclientprotocol.sdk.client.AcpClient; +import com.agentclientprotocol.sdk.client.AcpSyncClient; +import com.agentclientprotocol.sdk.client.transport.AgentParameters; +import com.agentclientprotocol.sdk.client.transport.StdioAcpClientTransport; +import com.agentclientprotocol.sdk.client.transport.WebSocketAcpClientTransport; +import com.agentclientprotocol.sdk.error.AcpCapabilityException; +import com.agentclientprotocol.sdk.error.AcpErrorCodes; +import com.agentclientprotocol.sdk.error.AcpProtocolException; +import com.agentclientprotocol.sdk.spec.AcpSchema; +import com.agentclientprotocol.sdk.spec.AcpSchema.AgentMessageChunk; +import com.agentclientprotocol.sdk.spec.AcpSchema.AgentThoughtChunk; +import com.agentclientprotocol.sdk.spec.AcpSchema.ContentBlock; +import com.agentclientprotocol.sdk.spec.AcpSchema.Plan; +import com.agentclientprotocol.sdk.spec.AcpSchema.SessionNotification; +import com.agentclientprotocol.sdk.spec.AcpSchema.SessionUpdate; +import com.agentclientprotocol.sdk.spec.AcpSchema.TextContent; +import com.agentclientprotocol.sdk.spec.AcpSchema.ToolCallUpdateNotification; +import com.agentclientprotocol.sdk.spec.AcpSchema.AvailableCommandsUpdate; +import com.agentclientprotocol.sdk.spec.AcpSchema.SessionInfoUpdate; +import com.agentclientprotocol.sdk.spec.AcpSchema.UsageUpdate; +import java.io.IOException; +import java.net.URI; +import java.nio.file.AccessDeniedException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import org.openide.filesystems.FileUtil; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * A connection to an ACP agent, over stdio or WebSocket. Handles the + * handshake, session creation, prompting and cancellation, and notifies + * registered {@link AcpSessionListener}s of agent updates. + * <p> + * Methods that talk to the agent ({@link #connect()}, {@link #newSession}, + * {@link #sendPrompt}, {@link #cancel}) block and must not be called from the + * event dispatch thread. + */ +public final class AcpConnection { + + private static final Logger LOG = Logger.getLogger(AcpConnection.class.getName()); + private static final String BEARER_PREFIX = "Bearer "; // NOI18N + private static final String AUTHORIZATION_HEADER = "Authorization"; // NOI18N + + private final AcpAgentDescriptor descriptor; + private final List<AcpSessionListener> listeners = new CopyOnWriteArrayList<>(); + + private final Map<String, List<Path>> trustedDirectories = new ConcurrentHashMap<>(); + private final Map<String, Set<String>> sessionAllowedTools = new ConcurrentHashMap<>(); + private final Map<String, Map<String, String>> fileSnapshots = new ConcurrentHashMap<>(); + private final Map<String, List<AcpSchema.ToolCallLocation>> storedLocations = new ConcurrentHashMap<>(); + private final AcpTerminalHandler terminalHandler = new AcpTerminalHandler(); + private final Object sessionLock = new Object(); + // A pending request owns its tokens until it fails or transfers them to its session ID. + private final Map<Object, Set<String>> mcpTokensByOwner = new HashMap<>(); + + private volatile AcpSyncClient client; + private volatile boolean connected; + private volatile List<AcpSchema.AuthMethod> authenticationMethods = List.of(); + private volatile Predicate<AcpSchema.CreateTerminalRequest> terminalAuthorizer; + private volatile java.util.function.Function<AcpSchema.RequestPermissionRequest, + AcpSchema.RequestPermissionResponse> permissionHandler; + private volatile java.util.function.Function<AcpSchema.CreateElicitationRequest, + AcpSchema.CreateElicitationResponse> elicitationHandler; + private volatile List<AcpModeInfo> availableModes = List.of(); + private volatile String currentModeId; + + /** + * @param descriptor the agent configuration, must not be {@code null} + */ + public AcpConnection(AcpAgentDescriptor descriptor) { + this.descriptor = Objects.requireNonNull(descriptor, "descriptor must not be null"); // NOI18N + } + + /** + * @return the agent descriptor used to create this connection + */ + public AcpAgentDescriptor getDescriptor() { + return descriptor; + } + + /** + * Establishes the transport (stdio or WebSocket) and performs the + * ACP handshake. Must not be called from the EDT. + * + * @throws IOException if the connection cannot be established + * @throws IllegalStateException if already connected + */ + public synchronized void connect() throws IOException { + if (connected) { + throw new IllegalStateException("Already connected to agent: " + descriptor.getName()); // NOI18N + } + + try { + AcpClient.SyncSpec spec; + + switch (descriptor.getTransportType()) { + case STDIO -> { + List<String> cmd = descriptor.getCommand(); + AgentParameters.Builder paramsBuilder = AgentParameters.builder(cmd.get(0)); + if (cmd.size() > 1) { + paramsBuilder.args(cmd.subList(1, cmd.size())); + } + Map<String, String> envVars = descriptor.getEnvironmentVariables(); + if (!envVars.isEmpty()) { + validateEnvironment(envVars); + List<String> unexpanded = environmentReferences(envVars); + if (!unexpanded.isEmpty()) { + LOG.log(Level.WARNING, "Agent environment variables contain references that will be passed literally: {0}", // NOI18N + String.join(", ", unexpanded)); + } + paramsBuilder.env(envVars); + } + StdioAcpClientTransport transport = new StdioAcpClientTransport(paramsBuilder.build()); + spec = AcpClient.sync(transport); + } + case WEBSOCKET -> { + WebSocketAcpClientTransport transport = new WebSocketAcpClientTransport(URI.create(descriptor.getUrl())); + spec = AcpClient.sync(transport); + } + default -> throw new IllegalStateException("Unknown transport type: " + descriptor.getTransportType()); // NOI18N + } + + spec.sessionUpdateHandler(this::handleSessionUpdate); + if (AcpWorkspaceFiles.isSupported()) { Review Comment: `AcpWorkspaceFiles.isSupported()` is `false` on macOS: `Files.newDirectoryStream(Path.of("/"))` is not a `SecureDirectoryStream` there (checked with JDK 21 on macOS). As far as I know Windows doesn't provide one either, so in practice only Linux supports it. On the other platforms the client silently stops announcing the `fs` read/write capabilities. The agent then falls back to its own file access, which doesn't go through any of the checks here. So for most desktop users the hardening makes file access less controlled than before, not more. I'd suggest a fallback for providers without `SecureDirectoryStream` (e.g. the canonical-path check from `resolve` plus `NOFOLLOW_LINKS` on the final component) instead of dropping the capability. At the very least, log it so it isn't invisible. ########## ide/libs.jackson/nbproject/org-netbeans-libs-jackson.sig: ########## @@ -1,5 +1,5 @@ #Signature file v4.1 -#Version 2.33 +#Version 2.35 Review Comment: This regenerates the API baseline for the Jackson upgrade (2.17.2 → 2.22.3). Compared to the NetBeans 32 snapshot (`#Version 2.33`), it drops public classes such as `PropertyNamingStrategy$SnakeCaseStrategy`, `$KebabCaseStrategy`, `$PropertyNamingStrategyBase` and `UntypedObjectDeserializer$Vanilla`, plus about 80 public methods. With the old baseline, sigtest would report these as incompatible changes for any module or plugin that depends on `org.netbeans.libs.jackson/2`. As far as I know, the baseline is normally refreshed during the release process, not in a feature PR. I'd keep the NB 32 baseline and make the incompatibility explicit, e.g. with a note in the module's API changes. It would also fit better with the separate Jackson commits than with this ACP hardening commit. ########## agentic/acp.api/src/org/netbeans/modules/acp/api/AcpWorkspaceFiles.java: ########## @@ -0,0 +1,182 @@ +/* + * 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.netbeans.modules.acp.api; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringWriter; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.nio.file.AccessDeniedException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.SecureDirectoryStream; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +final class AcpWorkspaceFiles { + + private AcpWorkspaceFiles() { + } + + static boolean isSupported() { + Path root = Path.of("").toAbsolutePath().getRoot(); + try (DirectoryStream<Path> stream = Files.newDirectoryStream(root)) { + return stream instanceof SecureDirectoryStream<?>; + } catch (IOException ex) { + return false; + } + } + + static Path resolve(List<Path> roots, Path requested, boolean allowNewFile) throws IOException { + if (!requested.isAbsolute() || requested.getParent() == null) { + throw new AccessDeniedException(requested.toString(), null, "An absolute file path is required"); + } + Path resolved; + try { + resolved = requested.toRealPath(); + } catch (NoSuchFileException ex) { + if (!allowNewFile || requested.getFileName().toString().equals("..") + || requested.getFileName().toString().equals(".")) { + throw ex; + } + resolved = requested.getParent().toRealPath().resolve(requested.getFileName()); Review Comment: For a new file, `requested.getParent().toRealPath()` throws `NoSuchFileException` if the parent directory doesn't exist yet. The previous handler created missing parent directories, so an agent writing e.g. `src/main/java/org/example/newpkg/Foo.java` now gets an error. Creating new packages is a common step for agents. If that's intended, the error should say so; otherwise the missing directories need to be created, inside the session roots, before the secure walk. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected] For further information about the NetBeans mailing lists, visit: https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists
