Skip to content
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

Fix missing link target #662

Merged
merged 2 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions internal/runner/nomad_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,21 +166,25 @@
}

ls2json := &nullio.Ls2JsonWriter{Target: content, Ctx: ctx}
defer ls2json.Close()
retrieveCommand := (&dto.ExecutionRequest{Command: fmt.Sprintf("%s %q", command, path)}).FullCommand()
exitCode, err := r.api.ExecuteCommand(ctx, r.id, retrieveCommand, false, privilegedExecution,
&nullio.Reader{Ctx: ctx}, ls2json, io.Discard)
writerErr := ls2json.Close()

switch {
case ls2json.HasStartedWriting() && err == nil && exitCode == 0:
// Successful. Nothing to do.
case ls2json.HasStartedWriting() && err == nil && errors.Is(writerErr, nullio.ErrLinkTargetPermissionDenied):
// Nothing to do. All available information has been returned.
case ls2json.HasStartedWriting():
// if HasStartedWriting the status code of the response is already sent.
// Therefore, we cannot notify CodeOcean about an error at this point anymore.
log.WithError(err).WithField("exitCode", exitCode).Warn("Ignoring error of listing the file system")
log.WithError(err).WithField("writerError", writerErr).WithField("exitCode", exitCode).
Warn("Ignoring error of listing the file system")

Check warning on line 183 in internal/runner/nomad_runner.go

View check run for this annotation

Codecov / codecov/patch

internal/runner/nomad_runner.go#L182-L183

Added lines #L182 - L183 were not covered by tests
err = nil
case err != nil:
err = fmt.Errorf("%w: nomad error during retrieve file headers: %w",
nomad.ErrExecutorCommunicationFailed, err)
case err != nil || writerErr != nil:
err = fmt.Errorf("%w: nomad error during retrieve file headers: %w, %w",
nomad.ErrExecutorCommunicationFailed, err, writerErr)

Check warning on line 187 in internal/runner/nomad_runner.go

View check run for this annotation

Codecov / codecov/patch

internal/runner/nomad_runner.go#L185-L187

Added lines #L185 - L187 were not covered by tests
case exitCode != 0:
err = ErrFileNotFound
case !ls2json.HasStartedWriting():
Expand Down
16 changes: 12 additions & 4 deletions pkg/nullio/ls2json.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
Expand All @@ -20,6 +21,7 @@
pathLineRegex = regexp.MustCompile(`(.*):$`)
headerLineRegex = regexp.
MustCompile(`([-aAbcCdDlMnpPsw?])([-rwxXsStT]{9})(\+?) +\d+ +(.+?) +(.+?) +(\d+) +(\d+) +(.*)$`)
ErrLinkTargetPermissionDenied = errors.New("permission denied for reading link target")
)

const (
Expand All @@ -44,6 +46,7 @@
remaining []byte
latestPath []byte
sentrySpan *sentry.Span
err error
}

func (w *Ls2JsonWriter) HasStartedWriting() bool {
Expand Down Expand Up @@ -101,14 +104,15 @@
return count, err
}

func (w *Ls2JsonWriter) Close() {
func (w *Ls2JsonWriter) Close() error {
if w.jsonStartSent {
count, err := w.Target.Write([]byte("]}"))
if count == 0 || err != nil {
log.WithContext(w.sentrySpan.Context()).WithError(err).Warn("Could not Close ls2json writer")
}
w.sentrySpan.Finish()
}
return w.err
}

func (w *Ls2JsonWriter) writeLine(line []byte) (count int, err error) {
Expand Down Expand Up @@ -163,11 +167,15 @@
if entryType == dto.EntryTypeLink {
parts := strings.Split(string(name), " -> ")
const NumberOfPartsInALink = 2
if len(parts) == NumberOfPartsInALink {
switch len(parts) {
case NumberOfPartsInALink:
name = dto.FilePath(parts[0])
linkTarget = dto.FilePath(parts[1])
} else {
log.WithContext(w.sentrySpan.Context()).Error("could not split link into name and target")
case 1:
// This case happens when a user tries to read the target of a link without permission. See #596.
MrSerth marked this conversation as resolved.
Show resolved Hide resolved
w.err = errors.Join(w.err, ErrLinkTargetPermissionDenied)
default:
log.WithContext(w.sentrySpan.Context()).WithField("name", name).Error("could not split link into name and target")

Check warning on line 178 in pkg/nullio/ls2json.go

View check run for this annotation

Codecov / codecov/patch

pkg/nullio/ls2json.go#L177-L178

Added lines #L177 - L178 were not covered by tests
}
}

Expand Down
41 changes: 37 additions & 4 deletions tests/e2e/runners_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ func (s *E2ETestSuite) TestListFileSystem_Nomad() {
ExecutionEnvironmentID: tests.DefaultEnvironmentIDAsInteger,
})
s.Require().NoError(err)
getFileURL, err := url.Parse(helpers.BuildURL(api.BasePath, api.RunnersPath, runnerID, api.UpdateFileSystemPath))
s.Require().NoError(err)

s.Run("No files", func() {
getFileURL, err := url.Parse(helpers.BuildURL(api.BasePath, api.RunnersPath, runnerID, api.UpdateFileSystemPath))
s.Require().NoError(err)
response, err := http.Get(getFileURL.String())
s.Require().NoError(err)
s.Equal(http.StatusOK, response.StatusCode)
Expand All @@ -120,8 +120,6 @@ func (s *E2ETestSuite) TestListFileSystem_Nomad() {
s.Require().NoError(err)
s.Equal(http.StatusNoContent, resp.StatusCode)

getFileURL, err := url.Parse(helpers.BuildURL(api.BasePath, api.RunnersPath, runnerID, api.UpdateFileSystemPath))
s.Require().NoError(err)
response, err := http.Get(getFileURL.String())
s.Require().NoError(err)
s.Equal(http.StatusOK, response.StatusCode)
Expand All @@ -138,6 +136,41 @@ func (s *E2ETestSuite) TestListFileSystem_Nomad() {
s.Equal("root", fileHeader.Group)
s.Equal("rwxr--r--", fileHeader.Permissions)
})

s.Run("With links", func() {
s.Run("allowed", func() {
path := "/proc/self/cwd"
getFileURL.RawQuery = url.Values{api.PathKey: []string{path}}.Encode()

response, err := http.Get(getFileURL.String())
s.Require().NoError(err)
s.Equal(http.StatusOK, response.StatusCode)
listFilesResponse := new(dto.ListFileSystemResponse)
err = json.NewDecoder(response.Body).Decode(listFilesResponse)
s.Require().NoError(err)
s.Require().Equal(1, len(listFilesResponse.Files))
fileHeader := listFilesResponse.Files[0]
s.Equal(dto.FilePath(path), fileHeader.Name)
s.Equal(dto.EntryTypeLink, fileHeader.EntryType)
s.Equal(dto.FilePath("/workspace"), fileHeader.LinkTarget)
})
s.Run("denied", func() {
path := "/proc/1/cwd"
getFileURL.RawQuery = url.Values{api.PathKey: []string{path}}.Encode()

response, err := http.Get(getFileURL.String())
s.Require().NoError(err)
s.Equal(http.StatusOK, response.StatusCode)
listFilesResponse := new(dto.ListFileSystemResponse)
err = json.NewDecoder(response.Body).Decode(listFilesResponse)
s.Require().NoError(err)
s.Require().Equal(1, len(listFilesResponse.Files))
fileHeader := listFilesResponse.Files[0]
s.Equal(dto.FilePath(path), fileHeader.Name)
s.Equal(dto.EntryTypeLink, fileHeader.EntryType)
s.Empty(fileHeader.LinkTarget)
})
})
}

func (s *E2ETestSuite) TestCopyFilesRoute() {
Expand Down
Loading