diff --git a/errors.go b/errors.go index b8b7456..75ba087 100644 --- a/errors.go +++ b/errors.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "net/url" "slices" "strings" ) @@ -146,3 +147,20 @@ func position(err error) (int, int) { return 0, 0 } + +// newUnreachableError reports that the URL in key did not answer. err +// gives the cause and does not name the URL, so the URL appears once. +func newUnreachableError(key string, u *URL, err error) ValidationError { + return newValidationErrorf(key, "'%s' not reachable: %s", (*url.URL)(u).String(), err.Error()) +} + +// newNotImageError reports that the file value in key is not an image. +// When the request failed for the URL value itself, the URL is named only +// once. A URL resolved from a relative path stays in the message. +func newNotImageError(key string, value string, err error) ValidationError { + if dlErr, ok := errors.AsType[*downloadError](err); ok && dlErr.URL == value { + err = dlErr.Err + } + + return newValidationErrorf(key, "'%s' is not an image: %s", value, err.Error()) +} diff --git a/errors_test.go b/errors_test.go index d136621..92a818a 100644 --- a/errors_test.go +++ b/errors_test.go @@ -2,6 +2,8 @@ package publiccode import ( "encoding/json" + "errors" + "net/url" "testing" ) @@ -121,3 +123,34 @@ func TestValidationWarningErrorEmptyKey(t *testing.T) { t.Errorf("got %q, want %q", got, want) } } + +func TestNewUnreachableErrorNamesURLOnce(t *testing.T) { + u, _ := url.Parse("https://example.invalid/x/y.git") + got := newUnreachableError("url", (*URL)(u), errors.New("no such host")) + + want := "'https://example.invalid/x/y.git' not reachable: no such host" + if got.Description != want { + t.Errorf("Description = %q, want %q", got.Description, want) + } +} + +func TestNewNotImageErrorNamesURLOnce(t *testing.T) { + const raw = "https://example.com/raw/shot.png" + + tests := []struct { + value string + want string + }{ + {raw, "'" + raw + "' is not an image: not found"}, + {"shot.png", "'shot.png' is not an image: downloading " + raw + ": not found"}, + } + + for _, tt := range tests { + err := &downloadError{URL: raw, Err: errors.New("not found")} + + got := newNotImageError("screenshots[0]", tt.value, err) + if got.Description != tt.want { + t.Errorf("Description = %q, want %q", got.Description, tt.want) + } + } +} diff --git a/fields.go b/fields.go index 7ed3f87..d0c71ba 100644 --- a/fields.go +++ b/fields.go @@ -29,7 +29,7 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU if checksNetwork && publiccodev0.URL != nil { if reachable, err := parser.isReachable(*(*url.URL)(publiccodev0.URL)); !reachable { - vr = append(vr, newValidationErrorf("url", "'%s' not reachable: %s", publiccodev0.URL, err.Error())) + vr = append(vr, newUnreachableError("url", publiccodev0.URL, err)) } if !parser.isRepo((*url.URL)(publiccodev0.URL)) { @@ -39,19 +39,13 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU if checksNetwork && publiccodev0.LandingURL != nil { if reachable, err := parser.isReachable(*(*url.URL)(publiccodev0.LandingURL)); !reachable { - vr = append(vr, newValidationErrorf( - "landingURL", - "'%s' not reachable: %s", publiccodev0.LandingURL, err.Error(), - )) + vr = append(vr, newUnreachableError("landingURL", publiccodev0.LandingURL, err)) } } if checksNetwork && publiccodev0.Roadmap != nil { if reachable, err := parser.isReachable(*(*url.URL)(publiccodev0.Roadmap)); !reachable { - vr = append(vr, newValidationErrorf( - "roadmap", - "'%s' not reachable: %s", publiccodev0.Roadmap, err.Error(), - )) + vr = append(vr, newUnreachableError("roadmap", publiccodev0.Roadmap, err)) } } @@ -213,18 +207,16 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU if checksNetwork && desc.Documentation != nil { if reachable, err := parser.isReachable(*(*url.URL)(desc.Documentation)); !reachable { - vr = append(vr, newValidationErrorf( - fmt.Sprintf("description.%s.documentation", lang), - "'%s' not reachable: %s", desc.Documentation, err.Error(), + vr = append(vr, newUnreachableError( + fmt.Sprintf("description.%s.documentation", lang), desc.Documentation, err, )) } } if checksNetwork && desc.APIDocumentation != nil { if reachable, err := parser.isReachable(*(*url.URL)(desc.APIDocumentation)); !reachable { - vr = append(vr, newValidationErrorf( - fmt.Sprintf("description.%s.apiDocumentation", lang), - "'%s' not reachable: %s", desc.APIDocumentation, err.Error(), + vr = append(vr, newUnreachableError( + fmt.Sprintf("description.%s.apiDocumentation", lang), desc.APIDocumentation, err, )) } } @@ -238,10 +230,7 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU if u != nil { isImage, err := parser.isImageFile(*u, network) if !isImage { - vr = append(vr, newValidationErrorf( - keyName, - "'%s' is not an image: %s", v, err.Error(), - )) + vr = append(vr, newNotImageError(keyName, v, err)) } } } @@ -272,10 +261,17 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU it := publiccodev0.IT + if publiccodev0.IT != nil { + vr = append(vr, newValidationWarning( + "IT", + "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", + )) + } + if publiccodev0.It != nil { vr = append(vr, newValidationWarning( "it", - "Lowercase country codes are DEPRECATED and will be removed in the future. Use 'IT' instead", + "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", )) it = publiccodev0.It @@ -359,7 +355,7 @@ func validateFieldsV1(publiccode PublicCode, parser *Parser, network bool, baseU if checksNetwork && publiccodev1.URL != nil { if reachable, err := parser.isReachable(*(*url.URL)(publiccodev1.URL)); !reachable { - vr = append(vr, newValidationErrorf("url", "'%s' not reachable: %s", publiccodev1.URL, err.Error())) + vr = append(vr, newUnreachableError("url", publiccodev1.URL, err)) } if !parser.isRepo((*url.URL)(publiccodev1.URL)) { @@ -369,19 +365,13 @@ func validateFieldsV1(publiccode PublicCode, parser *Parser, network bool, baseU if checksNetwork && publiccodev1.LandingURL != nil { if reachable, err := parser.isReachable(*(*url.URL)(publiccodev1.LandingURL)); !reachable { - vr = append(vr, newValidationErrorf( - "landingURL", - "'%s' not reachable: %s", publiccodev1.LandingURL, err.Error(), - )) + vr = append(vr, newUnreachableError("landingURL", publiccodev1.LandingURL, err)) } } if checksNetwork && publiccodev1.Roadmap != nil { if reachable, err := parser.isReachable(*(*url.URL)(publiccodev1.Roadmap)); !reachable { - vr = append(vr, newValidationErrorf( - "roadmap", - "'%s' not reachable: %s", publiccodev1.Roadmap, err.Error(), - )) + vr = append(vr, newUnreachableError("roadmap", publiccodev1.Roadmap, err)) } } @@ -429,18 +419,16 @@ func validateFieldsV1(publiccode PublicCode, parser *Parser, network bool, baseU for lang, desc := range publiccodev1.Description { if checksNetwork && desc.Documentation != nil { if reachable, err := parser.isReachable(*(*url.URL)(desc.Documentation)); !reachable { - vr = append(vr, newValidationErrorf( - fmt.Sprintf("description.%s.documentation", lang), - "'%s' not reachable: %s", desc.Documentation, err.Error(), + vr = append(vr, newUnreachableError( + fmt.Sprintf("description.%s.documentation", lang), desc.Documentation, err, )) } } if checksNetwork && desc.APIDocumentation != nil { if reachable, err := parser.isReachable(*(*url.URL)(desc.APIDocumentation)); !reachable { - vr = append(vr, newValidationErrorf( - fmt.Sprintf("description.%s.apiDocumentation", lang), - "'%s' not reachable: %s", desc.APIDocumentation, err.Error(), + vr = append(vr, newUnreachableError( + fmt.Sprintf("description.%s.apiDocumentation", lang), desc.APIDocumentation, err, )) } } @@ -454,10 +442,7 @@ func validateFieldsV1(publiccode PublicCode, parser *Parser, network bool, baseU if u != nil { isImage, err := parser.isImageFile(*u, network) if !isImage { - vr = append(vr, newValidationErrorf( - keyName, - "'%s' is not an image: %s", v, err.Error(), - )) + vr = append(vr, newNotImageError(keyName, v, err)) } } } diff --git a/internal/httpclient/httpclient.go b/internal/httpclient/httpclient.go index 4d74225..4bd0c6c 100644 --- a/internal/httpclient/httpclient.go +++ b/internal/httpclient/httpclient.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + neturl "net/url" "strconv" "time" ) @@ -66,7 +67,7 @@ func New(doer Doer) *Client { // it waits and tries again: for as long as Retry-After says, until the // time in X-Ratelimit-Reset, or with an exponential backoff from one // minute when the server gave no time. A wait the server asks for is -// capped at 30 seconds. +// capped at 30 seconds. Errors give the cause without naming url. func (c *Client) Get(url string, headers map[string]string) ([]byte, error) { return c.GetWithContext(context.Background(), url, headers) } @@ -118,7 +119,13 @@ func (c *Client) do(ctx context.Context, url string, headers map[string]string) resp, err := c.doer.Do(req) if err != nil { - return nil, fmt.Errorf("requesting %s: %w", url, err) + // *url.Error names the method and the URL. The caller names the + // URL in its own message, so return only the cause. + if urlErr, ok := errors.AsType[*neturl.Error](err); ok { + return nil, urlErr.Err + } + + return nil, fmt.Errorf("sending the request: %w", err) } return resp, nil diff --git a/internal/httpclient/httpclient_test.go b/internal/httpclient/httpclient_test.go index 573b68c..34afaca 100644 --- a/internal/httpclient/httpclient_test.go +++ b/internal/httpclient/httpclient_test.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "net/http/httptest" + neturl "net/url" "slices" "testing" "time" @@ -359,3 +360,24 @@ func TestGetCountsBlindRetriesOnTheirOwn(t *testing.T) { t.Errorf("waits = %v, want %v", *waits, want) } } + +type doerFunc func(*http.Request) (*http.Response, error) + +func (f doerFunc) Do(req *http.Request) (*http.Response, error) { + return f(req) +} + +func TestGetTransportErrorOmitsURL(t *testing.T) { + errDial := errors.New("dial tcp: lookup example.invalid: no such host") + c := New(doerFunc(func(req *http.Request) (*http.Response, error) { + return nil, &neturl.Error{Op: "Get", URL: req.URL.String(), Err: errDial} + })) + + _, err := c.Get("https://example.invalid/x/y.git", nil) + if !errors.Is(err, errDial) { + t.Fatalf("err = %v, want %v", err, errDial) + } + if err.Error() != errDial.Error() { + t.Errorf("err = %q, want only the cause %q", err, errDial) + } +} diff --git a/testdata/v0/valid/dependsOn.yml b/testdata/v0/valid/dependsOn.yml index 3e1f74a..467d161 100644 --- a/testdata/v0/valid/dependsOn.yml +++ b/testdata/v0/valid/dependsOn.yml @@ -90,12 +90,3 @@ dependsOn: # List of dependencies. The only mandatory list is the proprietary on optional: true - name: NFC Reader2 optional: true - -IT: - countryExtensionVersion: "0.2" - - piattaforme: - spid: false - pagopa: false - cie: false - anpr: false diff --git a/testdata/v0/valid/no-network/valid.yml b/testdata/v0/valid/no-network/valid.yml index 9ff48a3..81b7693 100644 --- a/testdata/v0/valid/no-network/valid.yml +++ b/testdata/v0/valid/no-network/valid.yml @@ -208,11 +208,3 @@ dependsOn: hardware: - name: NFC Reader optional: true - -IT: - piattaforme: - spid: false - pagopa: false - cie: false - anpr: false - io: false diff --git a/testdata/v0/valid/valid.yml b/testdata/v0/valid/valid.yml index b6c41de..fab8bf1 100644 --- a/testdata/v0/valid/valid.yml +++ b/testdata/v0/valid/valid.yml @@ -211,11 +211,3 @@ dependsOn: hardware: - name: NFC Reader optional: true - -IT: - piattaforme: - spid: false - pagopa: false - cie: false - anpr: false - io: false diff --git a/testdata/v0/valid/countryExtensionVersion_1.0.yml b/testdata/v0/valid_with_warnings/countryExtensionVersion_1.0.yml similarity index 100% rename from testdata/v0/valid/countryExtensionVersion_1.0.yml rename to testdata/v0/valid_with_warnings/countryExtensionVersion_1.0.yml diff --git a/testdata/v0/valid/valid_no_it_conforme.yml b/testdata/v0/valid_with_warnings/valid_no_it_conforme.yml similarity index 100% rename from testdata/v0/valid/valid_no_it_conforme.yml rename to testdata/v0/valid_with_warnings/valid_no_it_conforme.yml diff --git a/testdata/v0/valid/valid_with_country_specific_section_uppercase.yml b/testdata/v0/valid_with_warnings/valid_with_country_specific_section_uppercase.yml similarity index 100% rename from testdata/v0/valid/valid_with_country_specific_section_uppercase.yml rename to testdata/v0/valid_with_warnings/valid_with_country_specific_section_uppercase.yml diff --git a/v0_test.go b/v0_test.go index cba0719..6113eb9 100644 --- a/v0_test.go +++ b/v0_test.go @@ -16,6 +16,7 @@ func TestValidWithWarningTestcasesV0_NoNetwork(t *testing.T) { expected := map[string]error{ "authorsFile.yml": ValidationResults{ ValidationWarning{"", "legal.authorsFile", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 63, 3}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 95, 1}, }, } @@ -55,6 +56,7 @@ func TestInvalidTestcasesV0_NoNetwork(t *testing.T) { ValidationWarning{"", "usedBy", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 21, 1}, ValidationWarning{"", "description.en.videos", "This key is DEPRECATED and will be removed in the future. Link videos from the documentation or the website instead", 62, 5}, ValidationWarning{"", "dependsOn.open", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 102, 3}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 118, 1}, }, // monochromeLogo @@ -156,6 +158,7 @@ func TestInvalidTestcasesV0(t *testing.T) { ValidationError{"", "landingURL", "wrong type for this field", 8, 1}, ValidationWarning{"", "usedBy", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 21, 1}, ValidationWarning{"", "dependsOn.open", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 98, 3}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 114, 1}, }, "landingURL_invalid.yml": ValidationResults{ ValidationError{"", "landingURL", "landingURL must be an HTTP URL", 8, 1}, @@ -163,6 +166,7 @@ func TestInvalidTestcasesV0(t *testing.T) { ValidationWarning{"", "usedBy", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 21, 1}, ValidationWarning{"", "description.en.videos", "This key is DEPRECATED and will be removed in the future. Link videos from the documentation or the website instead", 62, 5}, ValidationWarning{"", "dependsOn.open", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 102, 3}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 118, 1}, }, // isBasedOn @@ -584,15 +588,18 @@ func TestInvalidTestcasesV0(t *testing.T) { // it.* "it_countryExtensionVersion_invalid.yml": ValidationResults{ ValidationError{"", "IT.countryExtensionVersion", "countryExtensionVersion must be one of the following: \"0.2\" or \"1.0\"", 12, 3}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 11, 1}, }, "it_riuso_codiceIPA_invalid.yml": ValidationResults{ ValidationError{"", "IT.riuso.codiceIPA", "codiceIPA must be a valid Italian Public Administration Code (iPA) (see https://github.com/publiccodeyml/italian-organizations-ipa-vocabulary)", 55, 5}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 53, 1}, }, "it_IT_duplicated.yml": ValidationResults{ ValidationWarning{"", "usedBy", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 19, 1}, ValidationWarning{"", "description.en.videos", "This key is DEPRECATED and will be removed in the future. Link videos from the documentation or the website instead", 60, 5}, ValidationWarning{"", "dependsOn.open", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 85, 3}, - ValidationWarning{"", "it", "Lowercase country codes are DEPRECATED and will be removed in the future. Use 'IT' instead", 114, 1}, + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 105, 1}, + ValidationWarning{"", "it", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 114, 1}, ValidationError{"", "it", "'IT' key already present. Remove this key", 114, 1}, }, "it_wrong_case.yml": ValidationResults{ @@ -679,13 +686,15 @@ func TestValidWithWarningsTestcasesV0(t *testing.T) { ValidationWarning{"", "outputTypes", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 50, 1}, }, "valid_with_it_conforme_gdpr.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 101, 1}, ValidationWarning{"", "IT.conforme.gdpr", "This key is DEPRECATED and will be removed in the future. Add a 'supports' entry with id 'alias:gdpr' instead", 108, 5}, }, "valid_with_it_conforme.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 101, 1}, ValidationWarning{"", "IT.conforme", "This key is DEPRECATED and will be removed in the future. It's safe to drop it", 103, 3}, }, "valid_with_country_specific_section_downcase.yml": ValidationResults{ - ValidationWarning{"", "it", "Lowercase country codes are DEPRECATED and will be removed in the future. Use 'IT' instead", 91, 1}, + ValidationWarning{"", "it", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 91, 1}, }, "valid_with_lowercase_countries.yml": ValidationResults{ ValidationWarning{"", "intendedAudience.countries[0]", "Lowercase country codes are DEPRECATED. Use uppercase instead ('IT')", 27, 7}, @@ -715,6 +724,7 @@ func TestValidWithWarningsTestcasesV0(t *testing.T) { ValidationWarning{"", "description.en-GB.videos", "This key is DEPRECATED and will be removed in the future. Link videos from the documentation or the website instead", 37, 5}, }, "valid_with_IT_piattaforme.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 215, 1}, ValidationWarning{"", "IT.piattaforme.spid", "This key is DEPRECATED and will be removed in the future. Add a 'supports' entry with id 'alias:spid' instead", 217, 5}, ValidationWarning{"", "IT.piattaforme.pagopa", "This key is DEPRECATED and will be removed in the future. Add a 'supports' entry with id 'alias:pagopa' instead", 218, 5}, ValidationWarning{"", "IT.piattaforme.cie", "This key is DEPRECATED and will be removed in the future. Add a 'supports' entry with id 'alias:cie' instead", 219, 5}, @@ -722,8 +732,18 @@ func TestValidWithWarningsTestcasesV0(t *testing.T) { ValidationWarning{"", "IT.piattaforme.io", "This key is DEPRECATED and will be removed in the future. Add a 'supports' entry with id 'alias:io' instead", 221, 5}, }, "valid_with_IT_riuso_codiceIPA.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 101, 1}, ValidationWarning{"", "IT.riuso.codiceIPA", "This key is DEPRECATED and will be removed in the future. Use 'organisation.uri' and set it to 'urn:x-italian-pa:pcm' instead", 103, 5}, }, + "valid_with_country_specific_section_uppercase.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 90, 1}, + }, + "countryExtensionVersion_1.0.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 90, 1}, + }, + "valid_no_it_conforme.yml": ValidationResults{ + ValidationWarning{"", "IT", "This key is DEPRECATED and will be removed in the future. Migrate its keys as their warnings say, then drop it", 90, 1}, + }, } dir := "testdata/v0/valid_with_warnings/" @@ -788,7 +808,7 @@ func TestRelativePathsOrURLs(t *testing.T) { // Remote publiccode.yml and relative path in screenshots: // should look for the screenshot remotely relative to this URL {"https://raw.githubusercontent.com/italia/publiccode-parser-go/2a1f25a36e0f2ab2d71efb67db8b66ff00573fbe/testdata/v0/invalid/description_en_screenshots_missing_file.yml", ValidationResults{ - ValidationError{"", "description.en.screenshots[0]", "'no_such_file.png' is not an image: HTTP GET failed for https://raw.githubusercontent.com/italia/publiccode-parser-go/2a1f25a36e0f2ab2d71efb67db8b66ff00573fbe/testdata/v0/invalid/no_such_file.png: not found", 42, 9}, + ValidationError{"", "description.en.screenshots[0]", "'no_such_file.png' is not an image: downloading https://raw.githubusercontent.com/italia/publiccode-parser-go/2a1f25a36e0f2ab2d71efb67db8b66ff00573fbe/testdata/v0/invalid/no_such_file.png: not found", 42, 9}, }}, // Local publiccode.yml and relative path in screenshot: diff --git a/validations.go b/validations.go index 65833cc..5cba7e9 100644 --- a/validations.go +++ b/validations.go @@ -31,6 +31,22 @@ var errMissingURLScheme = errors.New("missing URL scheme") var oembedSchemes []*regexp.Regexp +// downloadError is a failed request for a file the manifest points to. +// URL is the address requested, which may be a raw URL resolved from a +// relative path, and Err the cause, which does not name it. +type downloadError struct { + URL string + Err error +} + +func (e *downloadError) Error() string { + return fmt.Sprintf("downloading %s: %v", e.URL, e.Err) +} + +func (e *downloadError) Unwrap() error { + return e.Err +} + func init() { var schemes []string @@ -80,7 +96,8 @@ func getHeaderFromDomain(domain Domain, url string) map[string]string { } // isReachable checks whether the URL resource is reachable. -// An URL resource is reachable if it returns HTTP 200. +// An URL resource is reachable if it returns HTTP 200. The error gives the +// cause and does not name the URL: callers name it. func (p *Parser) isReachable(u url.URL) (bool, error) { // Don't check if we are running in WASM because we'd most likely // fail due to CORS errors. @@ -94,7 +111,7 @@ func (p *Parser) isReachable(u url.URL) (bool, error) { _, err := p.httpclient.Get(u.String(), getHeaderFromDomain(p.domain, u.String())) if err != nil { - return false, fmt.Errorf("HTTP GET failed for %s: %w", u.String(), err) + return false, fmt.Errorf("%w", err) } return true, nil @@ -166,7 +183,12 @@ func (p *Parser) isImageFile(u url.URL, network bool) (bool, error) { return false, fmt.Errorf("invalid file extension for: %s", netutil.DisplayURL(&u)) //nolint:err113,lll // dynamic message with path context } - return p.fileExists(u, network) + exists, err := p.fileExists(u, network) + if !exists && u.Scheme != "file" && u.Scheme != "" { + return false, &downloadError{URL: netutil.DisplayURL(&u), Err: err} + } + + return exists, err } // validLogo returns true if the file path in value is a valid logo. @@ -206,7 +228,7 @@ func (p *Parser) validLogo(u url.URL, network bool) (bool, error) { body, err := p.httpclient.Get(u.String(), getHeaderFromDomain(p.domain, u.String())) if err != nil { - return false, fmt.Errorf("downloading %s: %w", u.String(), err) + return false, fmt.Errorf("downloading %s: %w", netutil.DisplayURL(&u), err) } content = bytes.NewReader(body) diff --git a/validations_test.go b/validations_test.go index 4948cdc..a7f1606 100644 --- a/validations_test.go +++ b/validations_test.go @@ -112,6 +112,37 @@ func TestIsReachableNon200(t *testing.T) { } } +func TestIsReachableErrorOmitsURL(t *testing.T) { + srv := httptest.NewServer(http.NotFoundHandler()) + target := srv.URL + "/path" + srv.Close() + + p, _ := NewParser(ParserConfig{AllowNetworkToPrivateHosts: true}) + parsed, _ := url.Parse(target) + reachable, err := p.isReachable(*parsed) + if reachable || err == nil { + t.Fatalf("expected an unreachable URL, got %v, %v", reachable, err) + } + // The dial error names the address, as the cause, but not the URL. + if strings.Contains(err.Error(), "/path") { + t.Errorf("the cause names the URL: %v", err) + } +} + +func TestIsImageFileNamesRequestedURL(t *testing.T) { + srv := httptest.NewServer(http.NotFoundHandler()) + defer srv.Close() + + p, _ := NewParser(ParserConfig{AllowNetworkToPrivateHosts: true}) + parsed, _ := url.Parse(srv.URL + "/shot.png") + _, err := p.isImageFile(*parsed, true) + + want := "downloading " + srv.URL + "/shot.png: not found" + if err == nil || err.Error() != want { + t.Errorf("err = %v, want %q", err, want) + } +} + func TestIsImageFileInvalidExtension(t *testing.T) { p, _ := NewParser(ParserConfig{DisableNetwork: true}) u := url.URL{Scheme: "file", Path: "/tmp/test.gif"}