View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.connector.basic;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.net.URI;
24  import java.nio.charset.StandardCharsets;
25  import java.nio.file.Files;
26  import java.nio.file.Path;
27  import java.util.ArrayList;
28  import java.util.Arrays;
29  import java.util.HashMap;
30  import java.util.LinkedHashMap;
31  import java.util.List;
32  import java.util.Map;
33  
34  import org.eclipse.aether.internal.test.util.TestChecksumProcessor;
35  import org.eclipse.aether.internal.test.util.TestFileUtils;
36  import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory;
37  import org.eclipse.aether.spi.connector.checksum.ChecksumPolicy;
38  import org.eclipse.aether.spi.connector.checksum.ChecksumPolicy.ChecksumKind;
39  import org.eclipse.aether.spi.connector.layout.RepositoryLayout;
40  import org.eclipse.aether.spi.io.PathProcessorSupport;
41  import org.eclipse.aether.transfer.ChecksumFailureException;
42  import org.junit.jupiter.api.BeforeEach;
43  import org.junit.jupiter.api.Test;
44  import org.junit.jupiter.api.io.TempDir;
45  
46  import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.MD5;
47  import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA1;
48  import static org.junit.jupiter.api.Assertions.*;
49  
50  public class ChecksumValidatorTest {
51  
52      private static class StubChecksumPolicy implements ChecksumPolicy {
53  
54          boolean inspectAll;
55  
56          boolean tolerateFailure;
57  
58          private final ArrayList<String> callbacks = new ArrayList<>();
59  
60          private Object conclusion;
61  
62          @Override
63          public boolean onChecksumMatch(String algorithm, ChecksumKind kind) {
64              callbacks.add(String.format("match(%s, %s)", algorithm, kind));
65              if (inspectAll) {
66                  if (conclusion == null) {
67                      conclusion = true;
68                  }
69                  return false;
70              }
71              return true;
72          }
73  
74          @Override
75          public void onChecksumMismatch(String algorithm, ChecksumKind kind, ChecksumFailureException exception)
76                  throws ChecksumFailureException {
77              callbacks.add(String.format("mismatch(%s, %s)", algorithm, kind));
78              if (inspectAll) {
79                  conclusion = exception;
80                  return;
81              }
82              throw exception;
83          }
84  
85          @Override
86          public void onChecksumError(String algorithm, ChecksumKind kind, ChecksumFailureException exception) {
87              callbacks.add(String.format(
88                      "error(%s, %s, %s)", algorithm, kind, exception.getCause().getMessage()));
89          }
90  
91          @Override
92          public void onNoMoreChecksums() throws ChecksumFailureException {
93              callbacks.add("noMore()");
94              if (conclusion instanceof ChecksumFailureException) {
95                  throw (ChecksumFailureException) conclusion;
96              } else if (!Boolean.TRUE.equals(conclusion)) {
97                  throw ChecksumFailureException.noneAvailable("no checksums", null);
98              }
99          }
100 
101         @Override
102         public void onTransferRetry() {
103             callbacks.add("retry()");
104         }
105 
106         @Override
107         public boolean onTransferChecksumFailure(ChecksumFailureException exception) {
108             callbacks.add(String.format("fail(%s)", exception.getMessage()));
109             return tolerateFailure;
110         }
111 
112         void assertCallbacks(String... callbacks) {
113             assertEquals(Arrays.asList(callbacks), this.callbacks);
114         }
115     }
116 
117     private static class StubChecksumFetcher implements ChecksumValidator.ChecksumFetcher {
118 
119         HashMap<URI, Object> checksums = new HashMap<>();
120 
121         ArrayList<Path> checksumFiles = new ArrayList<>();
122 
123         private final ArrayList<URI> fetchedFiles = new ArrayList<>();
124 
125         @Override
126         public boolean fetchChecksum(URI remote, Path local) throws Exception {
127             fetchedFiles.add(remote);
128             Object checksum = checksums.get(remote);
129             if (checksum == null) {
130                 return false;
131             }
132             if (checksum instanceof Exception) {
133                 throw (Exception) checksum;
134             }
135             Files.createDirectories(local.getParent());
136             Files.write(local, checksum.toString().getBytes(StandardCharsets.UTF_8));
137             checksumFiles.add(local);
138             return true;
139         }
140 
141         void mock(String algo, Object value) {
142             checksums.put(toUri(algo), value);
143         }
144 
145         void assertFetchedFiles(String... algos) {
146             List<URI> expected = new ArrayList<>();
147             for (String algo : algos) {
148                 expected.add(toUri(algo));
149             }
150             assertEquals(expected, fetchedFiles);
151         }
152 
153         private static URI toUri(String algo) {
154             return newChecksum(algo).getLocation();
155         }
156     }
157 
158     private StubChecksumPolicy policy;
159 
160     private StubChecksumFetcher fetcher;
161 
162     @TempDir
163     private Path tempDir;
164 
165     private File dataFile;
166 
167     private static final TestChecksumAlgorithmSelector selector = new TestChecksumAlgorithmSelector();
168 
169     private List<ChecksumAlgorithmFactory> newChecksumAlgorithmFactories(String... factories) {
170         List<ChecksumAlgorithmFactory> checksums = new ArrayList<>();
171         for (String factory : factories) {
172             checksums.add(selector.select(factory));
173         }
174         return checksums;
175     }
176 
177     private static RepositoryLayout.ChecksumLocation newChecksum(String factory) {
178         return RepositoryLayout.ChecksumLocation.forLocation(URI.create("file"), selector.select(factory));
179     }
180 
181     private List<RepositoryLayout.ChecksumLocation> newChecksums(
182             List<ChecksumAlgorithmFactory> checksumAlgorithmFactories) {
183         List<RepositoryLayout.ChecksumLocation> checksums = new ArrayList<>();
184         for (ChecksumAlgorithmFactory factory : checksumAlgorithmFactories) {
185             checksums.add(RepositoryLayout.ChecksumLocation.forLocation(URI.create("file"), factory));
186         }
187         return checksums;
188     }
189 
190     private ChecksumValidator newValidator(String... factories) {
191         return newValidator(null, factories);
192     }
193 
194     private ChecksumValidator newValidator(Map<String, String> providedChecksums, String... factories) {
195         List<ChecksumAlgorithmFactory> checksumAlgorithmFactories = newChecksumAlgorithmFactories(factories);
196         return new ChecksumValidator(
197                 dataFile.toPath(),
198                 checksumAlgorithmFactories,
199                 new PathProcessorSupport(),
200                 new TestChecksumProcessor(),
201                 fetcher,
202                 policy,
203                 providedChecksums,
204                 newChecksums(checksumAlgorithmFactories));
205     }
206 
207     private Map<String, ?> checksums(String... algoDigestPairs) {
208         Map<String, Object> checksums = new LinkedHashMap<>();
209         for (int i = 0; i < algoDigestPairs.length; i += 2) {
210             String algo = algoDigestPairs[i];
211             String digest = algoDigestPairs[i + 1];
212             if (digest == null) {
213                 checksums.put(algo, new IOException("error"));
214             } else {
215                 checksums.put(algo, digest);
216             }
217         }
218         return checksums;
219     }
220 
221     @BeforeEach
222     void init() throws Exception {
223         dataFile = Files.createTempFile(tempDir, "tmpfile-", ".data").toFile();
224         dataFile.delete();
225         policy = new StubChecksumPolicy();
226         fetcher = new StubChecksumFetcher();
227     }
228 
229     @Test
230     void testValidate_NullPolicy() throws Exception {
231         policy = null;
232         ChecksumValidator validator = newValidator(SHA1);
233         validator.validate(checksums(SHA1, "ignored"), null);
234         fetcher.assertFetchedFiles();
235     }
236 
237     @Test
238     void testValidate_AcceptOnFirstMatch() throws Exception {
239         ChecksumValidator validator = newValidator(SHA1);
240         fetcher.mock(SHA1, "foo");
241         validator.validate(checksums(SHA1, "foo"), null);
242         fetcher.assertFetchedFiles(SHA1);
243         policy.assertCallbacks("match(SHA-1, REMOTE_EXTERNAL)");
244     }
245 
246     @Test
247     void testValidate_FailOnFirstMismatch() {
248         ChecksumValidator validator = newValidator(SHA1);
249         fetcher.mock(SHA1, "foo");
250         try {
251             validator.validate(checksums(SHA1, "not-foo"), null);
252             fail("expected exception");
253         } catch (ChecksumFailureException e) {
254             assertEquals("foo", e.getExpected());
255             assertEquals(ChecksumKind.REMOTE_EXTERNAL.name(), e.getExpectedKind());
256             assertEquals("not-foo", e.getActual());
257             assertTrue(e.isRetryWorthy());
258         }
259         fetcher.assertFetchedFiles(SHA1);
260         policy.assertCallbacks("mismatch(SHA-1, REMOTE_EXTERNAL)");
261     }
262 
263     @Test
264     void testValidate_ProvidedAllComparableAlgorithmsMustMatch() {
265         // the weaker algorithm matches, the stronger one does not: the artifact must be rejected regardless
266         // of map iteration order (previously the first matching algorithm accepted the artifact and skipped
267         // the remaining, stronger checksums)
268         Map<String, String> provided = new LinkedHashMap<>();
269         provided.put(MD5, "bar");
270         provided.put(SHA1, "foo");
271         ChecksumValidator validator = newValidator(provided, SHA1, MD5);
272         try {
273             validator.validate(checksums(SHA1, "not-foo", MD5, "bar"), null);
274             fail("expected exception");
275         } catch (ChecksumFailureException e) {
276             assertEquals("foo", e.getExpected());
277             assertEquals(ChecksumKind.PROVIDED.name(), e.getExpectedKind());
278             assertEquals("not-foo", e.getActual());
279             assertTrue(e.isRetryWorthy());
280         }
281         fetcher.assertFetchedFiles();
282         policy.assertCallbacks("match(MD5, PROVIDED)", "mismatch(SHA-1, PROVIDED)");
283     }
284 
285     @Test
286     void testValidate_ProvidedAllMatchingAccepts() throws Exception {
287         Map<String, String> provided = new LinkedHashMap<>();
288         provided.put(SHA1, "foo");
289         provided.put(MD5, "bar");
290         ChecksumValidator validator = newValidator(provided, SHA1, MD5);
291         validator.validate(checksums(SHA1, "foo", MD5, "bar"), null);
292         fetcher.assertFetchedFiles();
293         policy.assertCallbacks("match(SHA-1, PROVIDED)", "match(MD5, PROVIDED)");
294     }
295 
296     @Test
297     void testValidate_IncludedWeakMatchDoesNotMaskStrongMismatch() {
298         ChecksumValidator validator = newValidator(SHA1, MD5);
299         try {
300             validator.validate(checksums(SHA1, "not-foo", MD5, "bar"), checksums(MD5, "bar", SHA1, "foo"));
301             fail("expected exception");
302         } catch (ChecksumFailureException e) {
303             assertEquals("foo", e.getExpected());
304             assertEquals(ChecksumKind.REMOTE_INCLUDED.name(), e.getExpectedKind());
305             assertEquals("not-foo", e.getActual());
306         }
307         fetcher.assertFetchedFiles();
308         policy.assertCallbacks("match(MD5, REMOTE_INCLUDED)", "mismatch(SHA-1, REMOTE_INCLUDED)");
309     }
310 
311     @Test
312     void testValidate_AcceptOnEnd() throws Exception {
313         policy.inspectAll = true;
314         ChecksumValidator validator = newValidator(SHA1, MD5);
315         fetcher.mock(SHA1, "foo");
316         fetcher.mock(MD5, "bar");
317         validator.validate(checksums(SHA1, "foo", MD5, "bar"), null);
318         fetcher.assertFetchedFiles(SHA1, MD5);
319         policy.assertCallbacks("match(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()");
320     }
321 
322     @Test
323     void testValidate_FailOnEnd() {
324         policy.inspectAll = true;
325         ChecksumValidator validator = newValidator(SHA1, MD5);
326         fetcher.mock(SHA1, "foo");
327         fetcher.mock(MD5, "bar");
328         try {
329             validator.validate(checksums(SHA1, "not-foo", MD5, "bar"), null);
330             fail("expected exception");
331         } catch (ChecksumFailureException e) {
332             assertEquals("foo", e.getExpected());
333             assertEquals(ChecksumKind.REMOTE_EXTERNAL.name(), e.getExpectedKind());
334             assertEquals("not-foo", e.getActual());
335             assertTrue(e.isRetryWorthy());
336         }
337         fetcher.assertFetchedFiles(SHA1, MD5);
338         policy.assertCallbacks("mismatch(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()");
339     }
340 
341     @Test
342     void testValidate_IncludedBeforeExternal() throws Exception {
343         policy.inspectAll = true;
344         HashMap<String, String> provided = new HashMap<>();
345         provided.put(SHA1, "foo");
346         ChecksumValidator validator = newValidator(provided, SHA1, MD5);
347         fetcher.mock(SHA1, "foo");
348         fetcher.mock(MD5, "bar");
349         validator.validate(checksums(SHA1, "foo", MD5, "bar"), checksums(SHA1, "foo", MD5, "bar"));
350         fetcher.assertFetchedFiles(SHA1, MD5);
351         policy.assertCallbacks(
352                 "match(SHA-1, PROVIDED)",
353                 "match(SHA-1, REMOTE_INCLUDED)",
354                 "match(MD5, REMOTE_INCLUDED)",
355                 "match(SHA-1, REMOTE_EXTERNAL)",
356                 "match(MD5, REMOTE_EXTERNAL)",
357                 "noMore()");
358     }
359 
360     @Test
361     void testValidate_CaseInsensitive() throws Exception {
362         policy.inspectAll = true;
363         ChecksumValidator validator = newValidator(SHA1);
364         fetcher.mock(SHA1, "FOO");
365         validator.validate(checksums(SHA1, "foo"), checksums(SHA1, "foo"));
366         policy.assertCallbacks("match(SHA-1, REMOTE_INCLUDED)", "match(SHA-1, REMOTE_EXTERNAL)", "noMore()");
367     }
368 
369     @Test
370     void testValidate_MissingRemoteChecksum() throws Exception {
371         ChecksumValidator validator = newValidator(SHA1, MD5);
372         fetcher.mock(MD5, "bar");
373         validator.validate(checksums(MD5, "bar"), null);
374         fetcher.assertFetchedFiles(SHA1, MD5);
375         policy.assertCallbacks("match(MD5, REMOTE_EXTERNAL)");
376     }
377 
378     @Test
379     void testValidate_InaccessibleRemoteChecksum() throws Exception {
380         ChecksumValidator validator = newValidator(SHA1, MD5);
381         fetcher.mock(SHA1, new IOException("inaccessible"));
382         fetcher.mock(MD5, "bar");
383         validator.validate(checksums(MD5, "bar"), null);
384         fetcher.assertFetchedFiles(SHA1, MD5);
385         policy.assertCallbacks("error(SHA-1, REMOTE_EXTERNAL, inaccessible)", "match(MD5, REMOTE_EXTERNAL)");
386     }
387 
388     @Test
389     void testValidate_InaccessibleLocalChecksum() throws Exception {
390         ChecksumValidator validator = newValidator(SHA1, MD5);
391         fetcher.mock(SHA1, "foo");
392         fetcher.mock(MD5, "bar");
393         validator.validate(checksums(SHA1, null, MD5, "bar"), null);
394         fetcher.assertFetchedFiles(MD5);
395         policy.assertCallbacks("error(SHA-1, REMOTE_EXTERNAL, error)", "match(MD5, REMOTE_EXTERNAL)");
396     }
397 
398     @Test
399     void testHandle_Accept() {
400         policy.tolerateFailure = true;
401         ChecksumValidator validator = newValidator(SHA1);
402         assertTrue(validator.handle(ChecksumFailureException.noneAvailable("accept", null)));
403         policy.assertCallbacks("fail(accept)");
404     }
405 
406     @Test
407     void testHandle_Reject() {
408         policy.tolerateFailure = false;
409         ChecksumValidator validator = newValidator(SHA1);
410         assertFalse(validator.handle(ChecksumFailureException.noneAvailable("reject", null)));
411         policy.assertCallbacks("fail(reject)");
412     }
413 
414     @Test
415     void testRetry_ResetPolicy() {
416         ChecksumValidator validator = newValidator(SHA1);
417         validator.retry();
418         policy.assertCallbacks("retry()");
419     }
420 
421     @Test
422     void testRetry_RemoveTempFiles() throws Exception {
423         ChecksumValidator validator = newValidator(SHA1);
424         fetcher.mock(SHA1, "foo");
425         validator.validate(checksums(SHA1, "foo"), null);
426         fetcher.assertFetchedFiles(SHA1);
427         assertEquals(1, fetcher.checksumFiles.size());
428         validator.retry();
429         for (Path file : fetcher.checksumFiles) {
430             assertFalse(Files.exists(file), file.toAbsolutePath().toString());
431         }
432     }
433 
434     @Test
435     void testCommit_SaveChecksumFiles() throws Exception {
436         policy.inspectAll = true;
437         ChecksumValidator validator = newValidator(SHA1, MD5);
438         fetcher.mock(MD5, "bar");
439         validator.validate(checksums(SHA1, "foo", MD5, "bar"), checksums(SHA1, "foo"));
440         assertEquals(1, fetcher.checksumFiles.size());
441         validator.commit();
442         File checksumFile = new File(dataFile.getPath() + ".sha1");
443         assertTrue(checksumFile.isFile(), checksumFile.getAbsolutePath());
444         assertEquals("foo", TestFileUtils.readString(checksumFile));
445         checksumFile = new File(dataFile.getPath() + ".md5");
446         assertTrue(checksumFile.isFile(), checksumFile.getAbsolutePath());
447         assertEquals("bar", TestFileUtils.readString(checksumFile));
448         for (Path file : fetcher.checksumFiles) {
449             assertFalse(Files.exists(file), file.toAbsolutePath().toString());
450         }
451     }
452 
453     @Test
454     void testNoCommit_NoTempFiles() throws Exception {
455         ChecksumValidator validator = newValidator(SHA1);
456         fetcher.mock(SHA1, "foo");
457         validator.validate(checksums(SHA1, "foo"), null);
458         fetcher.assertFetchedFiles(SHA1);
459         assertEquals(1, fetcher.checksumFiles.size());
460         for (Path file : fetcher.checksumFiles) {
461             assertFalse(Files.exists(file), file.toAbsolutePath().toString());
462         }
463     }
464 }