Repository navigation
JSON-LD: time out remote context fetches and remember failures #4617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
reinkrul
wants to merge
2
commits into
master
Choose a base branch
from
fix/4615-jsonld-context-timeout
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,13 +24,25 @@ import ( | |
| "errors" | ||
| "fmt" | ||
| ssi "github.com/nuts-foundation/go-did" | ||
| "github.com/nuts-foundation/nuts-node/v6/http/client" | ||
| "github.com/nuts-foundation/nuts-node/v6/jsonld/log" | ||
| "github.com/nuts-foundation/nuts-node/v6/vcr/assets" | ||
| "github.com/piprate/json-gold/ld" | ||
| "io/fs" | ||
| "net/http" | ||
| "net/url" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| // remoteContextTimeout bounds a single fetch of a remote JSON-LD context document. | ||
| // Contexts are fetched while processing network transactions, so a server that never answers must not block that processing. | ||
| var remoteContextTimeout = 5 * time.Second | ||
|
|
||
| // remoteContextFailureTTL is how long a failed remote context fetch is remembered. | ||
| // During that time, loads of the same URL fail immediately with the original error instead of fetching again. | ||
| var remoteContextFailureTTL = 5 * time.Minute | ||
|
|
||
| // ContextsConfig contains config for json-ld document loader | ||
| type ContextsConfig struct { | ||
| // RemoteAllowList A list with urls as string which are allowed to request | ||
|
|
@@ -193,9 +205,11 @@ func NewContextLoader(allowUnlistedExternalCalls bool, contexts ContextsConfig) | |
| ld.NewCachingDocumentLoader( | ||
| // Handle all embedded file system files | ||
| NewEmbeddedFSDocumentLoader(assets.Assets, | ||
| // Last in the chain is the defaultLoader which can resolve | ||
| // local files and remote (via http) context documents | ||
| ld.NewDefaultDocumentLoader(nil)))) | ||
| // Remember failed remote fetches, so a dead context server costs one timeout instead of one per document | ||
| newFailureCachingLoader(remoteContextFailureTTL, | ||
| // Last in the chain is the defaultLoader which can resolve | ||
| // local files and remote (via http) context documents | ||
| ld.NewDefaultDocumentLoader(newRemoteContextHTTPClient()))))) | ||
|
|
||
| // If unlisted calls are not allowed, filter all calls to the defaultLoader | ||
| if !allowUnlistedExternalCalls { | ||
|
|
@@ -219,6 +233,87 @@ func NewContextLoader(allowUnlistedExternalCalls bool, contexts ContextsConfig) | |
| return loader, nil | ||
| } | ||
|
|
||
| // newRemoteContextHTTPClient returns the HTTP client used to fetch remote JSON-LD contexts. | ||
| // json-gold needs a *http.Client, so the node's strict HTTP client (timeout, SSRF guard, URL checks, response size limit) | ||
| // is wrapped as its transport. | ||
| func newRemoteContextHTTPClient() *http.Client { | ||
| return &http.Client{Transport: strictClientTransport{client: client.New(remoteContextTimeout)}} | ||
| } | ||
|
|
||
| // strictClientTransport adapts a client.StrictHTTPClient to http.RoundTripper. | ||
| // The strict client follows redirects itself, so the outer http.Client receives the final response. | ||
| type strictClientTransport struct { | ||
| client *client.StrictHTTPClient | ||
| } | ||
|
|
||
| func (s strictClientTransport) RoundTrip(request *http.Request) (*http.Response, error) { | ||
| // RoundTrip must not modify the request, but the strict client sets the User-Agent header. | ||
| return s.client.Do(request.Clone(request.Context())) | ||
| } | ||
|
|
||
| type failedLoad struct { | ||
| err error | ||
| until time.Time | ||
| } | ||
|
|
||
| // failureCachingLoader remembers failed loads per URL for a fixed time, and returns the remembered error without | ||
| // calling the next loader during that time. Successful loads are not cached here (see ld.NewCachingDocumentLoader). | ||
| type failureCachingLoader struct { | ||
| ttl time.Duration | ||
| nextLoader ld.DocumentLoader | ||
| mutex sync.Mutex | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This type copies much of the already used |
||
| failures map[string]failedLoad | ||
| } | ||
|
|
||
| func newFailureCachingLoader(ttl time.Duration, nextLoader ld.DocumentLoader) *failureCachingLoader { | ||
| return &failureCachingLoader{ | ||
| ttl: ttl, | ||
| nextLoader: nextLoader, | ||
| failures: map[string]failedLoad{}, | ||
| } | ||
| } | ||
|
|
||
| // LoadDocument returns the remembered error if loading u failed less than ttl ago, otherwise it calls the next loader. | ||
| func (f *failureCachingLoader) LoadDocument(u string) (*ld.RemoteDocument, error) { | ||
| if err := f.recentFailure(u); err != nil { | ||
| log.Logger().Debugf("Not fetching JSON-LD context, it failed recently (url=%s)", u) | ||
| return nil, err | ||
| } | ||
| document, err := f.nextLoader.LoadDocument(u) | ||
| if err != nil { | ||
| f.recordFailure(u, err) | ||
| log.Logger().WithError(err).Warnf("Failed to load JSON-LD context, not retrying for %s (url=%s)", f.ttl, u) | ||
| } | ||
| return document, err | ||
| } | ||
|
|
||
| func (f *failureCachingLoader) recentFailure(u string) error { | ||
| f.mutex.Lock() | ||
| defer f.mutex.Unlock() | ||
| failure, ok := f.failures[u] | ||
| if !ok { | ||
| return nil | ||
| } | ||
| if time.Now().After(failure.until) { | ||
| delete(f.failures, u) | ||
| return nil | ||
| } | ||
| return failure.err | ||
| } | ||
|
|
||
| func (f *failureCachingLoader) recordFailure(u string, err error) { | ||
| f.mutex.Lock() | ||
| defer f.mutex.Unlock() | ||
| now := time.Now() | ||
| // Prune expired entries, so the map stays bounded by the number of URLs that failed within the last ttl. | ||
| for failedURL, failure := range f.failures { | ||
| if now.After(failure.until) { | ||
| delete(f.failures, failedURL) | ||
| } | ||
| } | ||
| f.failures[u] = failedLoad{err: err, until: now.Add(f.ttl)} | ||
| } | ||
|
|
||
| // LDUtil package a set of often used JSON-LD operations for re-usability. | ||
| type LDUtil struct { | ||
| LDDocumentLoader ld.DocumentLoader | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This nests two http.Clients: the outer one json-gold needs, and the one inside
StrictHTTPClient. All the real behaviour lives in the inner one. It applies the
5s timeout, follows redirects with checkRedirect, and buffers the body before
RoundTrip returns, so the outer client only ever sees a final non-redirect
response. Its Timeout and CheckRedirect are therefore unused on purpose.
Worth stating that in the comment, because the next reader will see
&http.Client{Transport: ...} with no Timeout and add one, and then there are
two timeouts that disagree. Suggested wording:
Also note that this RoundTrip bends the http.RoundTripper contract (it follows
redirects and returns errors for oversized bodies), so it should stay private
to this package rather than become a general adapter. If we want a real
*http.Client with the strict protections, that belongs in http/client as a
per-hop transport, and pki/validator.go (CRL fetching on http.DefaultTransport,
no SSRF guard, no body limit) would be the second consumer.