You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by GitBox <gi...@apache.org> on 2022/10/10 20:02:06 UTC

[GitHub] [maven-resolver] michael-o commented on a diff in pull request #200: [MRESOLVER-276][MRESOLVER-268] Post artifact resolve hook

michael-o commented on code in PR #200:
URL: https://github.com/apache/maven-resolver/pull/200#discussion_r991598876


##########
maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource.java:
##########
@@ -159,9 +178,63 @@ private ConcurrentHashMap<String, String> loadProvidedChecksums( Path checksumsF
         }
         else
         {
-            LOGGER.debug( "Checksums file '{}' not found", checksumsFile );
+            LOGGER.debug( "The {} trusted checksums for remote repository {} not exist at '{}'",
+                    checksumAlgorithmFactory.getName(), artifactRepository.getId(), checksumsFile );
         }
 
         return result;
     }
+
+    private String calculateSummaryPath( boolean originAware,
+                                         ArtifactRepository artifactRepository,
+                                         ChecksumAlgorithmFactory checksumAlgorithmFactory )
+    {
+        final String fileName;
+        if ( originAware )
+        {
+            fileName = CHECKSUMS_FILE_PREFIX + "-" + artifactRepository.getId();
+        }
+        else
+        {
+            fileName = CHECKSUMS_FILE_PREFIX;
+        }
+        return fileName + "." + checksumAlgorithmFactory.getFileExtension();
+    }
+
+    private class SummaryFileWriter implements Writer
+    {
+        private final Path basedir;
+
+        private final boolean originAware;
+
+        private SummaryFileWriter( Path basedir, boolean originAware )
+        {
+            this.basedir = basedir;
+            this.originAware = originAware;
+        }
+
+        @Override
+        public void addTrustedArtifactChecksums( Artifact artifact, ArtifactRepository artifactRepository,
+                                                 List<ChecksumAlgorithmFactory> checksumAlgorithmFactories,
+                                                 Map<String, String> trustedArtifactChecksums ) throws IOException
+        {
+            for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories )
+            {
+                String checksum = requireNonNull(
+                        trustedArtifactChecksums.get( checksumAlgorithmFactory.getName() ) );
+                String summaryLine = ArtifactIdUtils.toId( artifact ) + " " + checksum + "\n";
+                Path summaryPath = basedir.resolve(
+                        calculateSummaryPath( originAware, artifactRepository, checksumAlgorithmFactory ) );
+                Files.createDirectories( summaryPath.getParent() );
+                Files.write( summaryPath, summaryLine.getBytes( StandardCharsets.UTF_8 ),
+                        StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND );

Review Comment:
   I am bit worried about this. We have *one* file:
   * What about multithreading? Does `SyncContext` protect us?
   * For hundreds of artifacts opening and closing the same file will have a performance overhead. This reminds me of https://www.sqlite.org/fasterthanfs.html



##########
maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultArtifactResolver.java:
##########
@@ -410,6 +425,11 @@ else if ( local.getFile() != null )
             performDownloads( session, group );
         }
 
+        for ( ArtifactResolverPostProcessor artifactResolverPostProcessor : artifactResolverPostProcessors.values() )
+        {
+            artifactResolverPostProcessor.postProcess( session, results );

Review Comment:
   Why is the outcome now gone?



##########
maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumArtifactResolverPostProcessor.java:
##########
@@ -0,0 +1,231 @@
+package org.eclipse.aether.internal.impl.resolution;
+
+/*
+ * 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.
+ */
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import org.eclipse.aether.RepositorySystemSession;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.repository.ArtifactRepository;
+import org.eclipse.aether.resolution.ArtifactResult;
+import org.eclipse.aether.spi.checksums.TrustedChecksumsSource;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySelector;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmHelper;
+import org.eclipse.aether.transfer.ChecksumFailureException;
+import org.eclipse.aether.util.ConfigUtils;
+import org.eclipse.aether.util.artifact.ArtifactIdUtils;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Artifact resolver processor that verifies the checksums of all resolved artifacts against trusted checksums. Is also
+ * able to "record" (calculate and write them) to trusted checksum sources, that do support this operation.
+ *
+ * @since TBD
+ */
+@Singleton
+@Named( TrustedChecksumArtifactResolverPostProcessor.NAME )
+public final class TrustedChecksumArtifactResolverPostProcessor
+        extends ArtifactResolverPostProcessorSupport
+{
+    public static final String NAME = "trusted-checksum";
+
+    private static final String CONF_CHECKSUM_ALGORITHMS = "checksumAlgorithms";
+
+    private static final String DEFAULT_CHECKSUM_ALGORITHMS = "SHA-1";
+
+    private static final String CONF_FAIL_IF_MISSING = "failIfMissing";
+
+    private static final String CONF_RECORD = "record";
+
+    private static final String CHECKSUM_ALGORITHMS_CACHE_KEY =
+            TrustedChecksumArtifactResolverPostProcessor.class.getName() + ".checksumAlgorithms";
+
+    private final ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector;
+
+    private final Map<String, TrustedChecksumsSource> trustedChecksumsSources;
+
+    @Inject
+    public TrustedChecksumArtifactResolverPostProcessor(
+            ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector,
+            Map<String, TrustedChecksumsSource> trustedChecksumsSources )
+    {
+        super( NAME );
+        this.checksumAlgorithmFactorySelector = requireNonNull( checksumAlgorithmFactorySelector );
+        this.trustedChecksumsSources = requireNonNull( trustedChecksumsSources );
+    }
+
+    @SuppressWarnings( "unchecked" )
+    @Override
+    protected void doProcess( RepositorySystemSession session, List<ArtifactResult> artifactResults )
+    {
+        final List<ChecksumAlgorithmFactory> checksumAlgorithms = (List<ChecksumAlgorithmFactory>) session.getData()
+                .computeIfAbsent( CHECKSUM_ALGORITHMS_CACHE_KEY, () ->
+                        checksumAlgorithmFactorySelector.select(
+                                ConfigUtils.parseCommaSeparatedUniqueNames( ConfigUtils.getString(
+                                        session, DEFAULT_CHECKSUM_ALGORITHMS, CONF_CHECKSUM_ALGORITHMS ) )
+                        ) );
+
+        final boolean failIfMissing = ConfigUtils.getBoolean(
+                session, false, configPropKey( CONF_FAIL_IF_MISSING ) );
+        final boolean record = ConfigUtils.getBoolean( session, false, configPropKey( CONF_RECORD ) );
+
+        for ( ArtifactResult artifactResult : artifactResults )
+        {
+            if ( artifactResult.isResolved() )
+            {
+                if ( record )
+                {
+                    recordArtifactChecksums( session, artifactResult, checksumAlgorithms );
+                }
+                else if ( !validateArtifactChecksums( session, artifactResult, checksumAlgorithms, failIfMissing ) )
+                {
+                    artifactResult.setArtifact( artifactResult.getArtifact().setFile( null ) ); // make it unresolved
+                }
+            }
+        }
+    }
+
+    /**
+     * Calculates and records checksums into trusted sources that support writing.
+     */
+    private void recordArtifactChecksums( RepositorySystemSession session,
+                                          ArtifactResult artifactResult,
+                                          List<ChecksumAlgorithmFactory> checksumAlgorithmFactories )
+    {
+        Artifact artifact = artifactResult.getArtifact();
+        ArtifactRepository artifactRepository = artifactResult.getRepository();
+
+        try
+        {
+            final Map<String, String> calculatedChecksums = ChecksumAlgorithmHelper.calculate(
+                    artifact.getFile(), checksumAlgorithmFactories );
+
+            for ( TrustedChecksumsSource trustedChecksumsSource : trustedChecksumsSources.values() )
+            {
+                try ( TrustedChecksumsSource.Writer writer = trustedChecksumsSource
+                        .getTrustedArtifactChecksumsWriter( session ) )
+                {
+                    if ( writer != null )
+                    {
+                        writer.addTrustedArtifactChecksums( artifact, artifactRepository, checksumAlgorithmFactories,
+                                calculatedChecksums );
+                    }
+                }
+            }
+        }
+        catch ( IOException e )
+        {
+            throw new UncheckedIOException( "Could not calculate amd write required checksums for "
+                    + artifact.getFile(), e );
+        }
+    }
+
+    /**
+     * Validates trusted checksums against {@link ArtifactResult}, returns {@code true} denoting "valid" checksums or
+     * {@code false} denoting "invalid" checksums.
+     */
+    private boolean validateArtifactChecksums( RepositorySystemSession session,
+                                               ArtifactResult artifactResult,
+                                               List<ChecksumAlgorithmFactory> checksumAlgorithmFactories,
+                                               boolean failIfMissing )
+    {
+        Artifact artifact = artifactResult.getArtifact();
+        ArtifactRepository artifactRepository = artifactResult.getRepository();
+
+        boolean valid = true;
+        boolean validated = false;
+        try
+        {
+            // full set: calculate all algorithms we were asked for
+            final Map<String, String> calculatedChecksums = ChecksumAlgorithmHelper.calculate(
+                    artifact.getFile(), checksumAlgorithmFactories );
+
+            for ( Map.Entry<String, TrustedChecksumsSource> entry : trustedChecksumsSources.entrySet() )
+            {
+                final String trustedSourceName = entry.getKey();
+                final TrustedChecksumsSource trustedChecksumsSource = entry.getValue();
+
+                // upper bound set: ask source for checksums, ideally same as calculatedChecksums but may be less
+                Map<String, String> trustedChecksums = trustedChecksumsSource.getTrustedArtifactChecksums(
+                        session, artifact, artifactRepository, checksumAlgorithmFactories );
+
+                if ( trustedChecksums == null )
+                {
+                    continue; // not enabled
+                }
+                validated = true;
+
+                if ( !calculatedChecksums.equals( trustedChecksums ) )
+                {
+                    Set<String> missingTrustedAlg = new HashSet<>( calculatedChecksums.keySet() );
+                    missingTrustedAlg.removeAll( trustedChecksums.keySet() );
+
+                    if ( !missingTrustedAlg.isEmpty() && failIfMissing )
+                    {
+                        artifactResult.addException( new ChecksumFailureException( "Missing from " + trustedSourceName
+                                + " trusted checksum(s) " + missingTrustedAlg + " for artifact "
+                                + ArtifactIdUtils.toId( artifact ) ) );
+                        valid = false;
+                    }
+
+                    // compare values but only present ones, failIfMissing handled above
+                    // we still want to report all: algX - missing, algY - mismatch, etc
+                    for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories )
+                    {
+                        String calculatedChecksum = calculatedChecksums.get( checksumAlgorithmFactory.getName() );
+                        String trustedChecksum = trustedChecksums.get( checksumAlgorithmFactory.getName() );
+                        if ( trustedChecksum != null && !Objects.equals( calculatedChecksum, trustedChecksum ) )
+                        {
+                            artifactResult.addException( new ChecksumFailureException( "Artifact "
+                                    + ArtifactIdUtils.toId( artifact ) + " trusted checksum mismatch: "
+                                    + trustedSourceName + "=" + trustedChecksum + "; calculated="
+                                    + calculatedChecksum ) );
+                            valid = false;
+                        }
+                    }
+                }
+            }
+
+            if ( !validated && failIfMissing )
+            {
+                artifactResult.addException( new ChecksumFailureException( "There are no enabled trusted checksum"

Review Comment:
   checksums



##########
maven-resolver-util/src/main/java/org/eclipse/aether/util/ConfigUtils.java:
##########
@@ -395,4 +398,31 @@ public static List<?> getList( RepositorySystemSession session, List<?> defaultV
         return getMap( session.getConfigProperties(), defaultValue, keys );
     }
 
+    /**
+     * Utility method to parse configuration string that contains comma separated list of names into
+     * {@link List<String>}, never returns {@code null}.
+     *
+     * @since TBD
+     */
+    public static List<String> parseCommaSeparatedNames( String commaSeparatedNamed )

Review Comment:
   `String commaSeparatedNames`



##########
maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumArtifactResolverPostProcessor.java:
##########
@@ -0,0 +1,231 @@
+package org.eclipse.aether.internal.impl.resolution;
+
+/*
+ * 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.
+ */
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import org.eclipse.aether.RepositorySystemSession;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.repository.ArtifactRepository;
+import org.eclipse.aether.resolution.ArtifactResult;
+import org.eclipse.aether.spi.checksums.TrustedChecksumsSource;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySelector;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmHelper;
+import org.eclipse.aether.transfer.ChecksumFailureException;
+import org.eclipse.aether.util.ConfigUtils;
+import org.eclipse.aether.util.artifact.ArtifactIdUtils;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Artifact resolver processor that verifies the checksums of all resolved artifacts against trusted checksums. Is also
+ * able to "record" (calculate and write them) to trusted checksum sources, that do support this operation.
+ *
+ * @since TBD
+ */
+@Singleton
+@Named( TrustedChecksumArtifactResolverPostProcessor.NAME )
+public final class TrustedChecksumArtifactResolverPostProcessor

Review Comment:
   Shouldn't this be `TrustedChecksums...` since it is also `TrustedChecksumsSource`?



##########
maven-resolver-util/src/main/java/org/eclipse/aether/util/ConfigUtils.java:
##########
@@ -395,4 +398,31 @@ public static List<?> getList( RepositorySystemSession session, List<?> defaultV
         return getMap( session.getConfigProperties(), defaultValue, keys );
     }
 
+    /**
+     * Utility method to parse configuration string that contains comma separated list of names into
+     * {@link List<String>}, never returns {@code null}.
+     *
+     * @since TBD
+     */
+    public static List<String> parseCommaSeparatedNames( String commaSeparatedNamed )
+    {
+        if ( commaSeparatedNamed == null || commaSeparatedNamed.trim().isEmpty() )
+        {
+            return Collections.emptyList();
+        }
+        return Arrays.stream( commaSeparatedNamed.split( "," ) )
+                .filter( s -> s != null && !s.trim().isEmpty() )
+                .collect( toList() );
+    }
+
+    /**
+     * Utility method to parse configuration string that contains comma separated list of names into
+     * {@link List<String>} with unique elements (duplicates, if any, are discarded), never returns {@code null}.
+     *
+     * @since TBD
+     */
+    public static List<String> parseCommaSeparatedUniqueNames( String commaSeparatedNamed )

Review Comment:
   `String commaSeparatedNames`



##########
maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource.java:
##########
@@ -117,9 +108,69 @@ protected Map<String, String> performLookup( RepositorySystemSession session,
             catch ( IOException e )
             {
                 // unexpected, log, skip
-                LOGGER.warn( "Could not read provided checksum for '{}' at path '{}'", artifact, checksumPath, e );
+                LOGGER.warn( "Could not read '{}' trusted checksum on path '{}'", artifact, checksumPath, e );

Review Comment:
   `...read artifact '{}'`



##########
maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumArtifactResolverPostProcessor.java:
##########
@@ -0,0 +1,231 @@
+package org.eclipse.aether.internal.impl.resolution;
+
+/*
+ * 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.
+ */
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import org.eclipse.aether.RepositorySystemSession;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.repository.ArtifactRepository;
+import org.eclipse.aether.resolution.ArtifactResult;
+import org.eclipse.aether.spi.checksums.TrustedChecksumsSource;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySelector;
+import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmHelper;
+import org.eclipse.aether.transfer.ChecksumFailureException;
+import org.eclipse.aether.util.ConfigUtils;
+import org.eclipse.aether.util.artifact.ArtifactIdUtils;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Artifact resolver processor that verifies the checksums of all resolved artifacts against trusted checksums. Is also
+ * able to "record" (calculate and write them) to trusted checksum sources, that do support this operation.
+ *
+ * @since TBD
+ */
+@Singleton
+@Named( TrustedChecksumArtifactResolverPostProcessor.NAME )
+public final class TrustedChecksumArtifactResolverPostProcessor
+        extends ArtifactResolverPostProcessorSupport
+{
+    public static final String NAME = "trusted-checksum";
+
+    private static final String CONF_CHECKSUM_ALGORITHMS = "checksumAlgorithms";
+
+    private static final String DEFAULT_CHECKSUM_ALGORITHMS = "SHA-1";
+
+    private static final String CONF_FAIL_IF_MISSING = "failIfMissing";
+
+    private static final String CONF_RECORD = "record";
+
+    private static final String CHECKSUM_ALGORITHMS_CACHE_KEY =
+            TrustedChecksumArtifactResolverPostProcessor.class.getName() + ".checksumAlgorithms";
+
+    private final ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector;
+
+    private final Map<String, TrustedChecksumsSource> trustedChecksumsSources;
+
+    @Inject
+    public TrustedChecksumArtifactResolverPostProcessor(
+            ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector,
+            Map<String, TrustedChecksumsSource> trustedChecksumsSources )
+    {
+        super( NAME );
+        this.checksumAlgorithmFactorySelector = requireNonNull( checksumAlgorithmFactorySelector );
+        this.trustedChecksumsSources = requireNonNull( trustedChecksumsSources );
+    }
+
+    @SuppressWarnings( "unchecked" )
+    @Override
+    protected void doProcess( RepositorySystemSession session, List<ArtifactResult> artifactResults )
+    {
+        final List<ChecksumAlgorithmFactory> checksumAlgorithms = (List<ChecksumAlgorithmFactory>) session.getData()
+                .computeIfAbsent( CHECKSUM_ALGORITHMS_CACHE_KEY, () ->
+                        checksumAlgorithmFactorySelector.select(
+                                ConfigUtils.parseCommaSeparatedUniqueNames( ConfigUtils.getString(
+                                        session, DEFAULT_CHECKSUM_ALGORITHMS, CONF_CHECKSUM_ALGORITHMS ) )
+                        ) );
+
+        final boolean failIfMissing = ConfigUtils.getBoolean(
+                session, false, configPropKey( CONF_FAIL_IF_MISSING ) );
+        final boolean record = ConfigUtils.getBoolean( session, false, configPropKey( CONF_RECORD ) );
+
+        for ( ArtifactResult artifactResult : artifactResults )
+        {
+            if ( artifactResult.isResolved() )
+            {
+                if ( record )

Review Comment:
   So here this is a mere collect (similar to a preflight) and on the second run it will re used?



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org