fix: return 404 for empty repositories

Some endpoints (`/api/v1/repos/*/*/raw`, `/api/v1/repos/*/*/media`, ...;
anything that uses both `context.ReferencesGitRepo()` and
`context.RepoRefForAPI` really) returned a 500 when the repository was
completely empty. This resulted in some confusion in
https://github.com/datalad/datalad-usage-dashboard/issues/47 because the
same request for a non-existent file in a repository could sometimes
generate a 404 and sometimes a 500, depending on if the git repository
is initialized at all or not.

Returning a 404 seems more appropriate here, since this isn't an
unexpected internal error, but just another way of not finding the
requested data.
This commit is contained in:
Matthias Riße 2025-02-20 10:28:06 +01:00
parent d81baf21e9
commit 772c393e3c
2 changed files with 19 additions and 1 deletions

View file

@ -365,7 +365,7 @@ func RepoRefForAPI(next http.Handler) http.Handler {
ctx := GetAPIContext(req)
if ctx.Repo.GitRepo == nil {
ctx.InternalServerError(fmt.Errorf("no open git repo"))
ctx.NotFound(fmt.Errorf("no open git repo"))
return
}

View file

@ -136,3 +136,21 @@ func TestEmptyRepoAddFileByAPI(t *testing.T) {
DecodeJSON(t, resp, &apiRepo)
assert.Equal(t, "new_branch", apiRepo.DefaultBranch)
}
func TestEmptyRepoRawAPIRequestsReturn404(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user30")
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository)
req := NewRequest(t, "GET", "/api/v1/repos/user30/empty/raw/main/something").AddTokenAuth(token)
_ = session.MakeRequest(t, req, http.StatusNotFound)
}
func TestEmptyRepoMediaAPIRequestsReturn404(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user30")
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository)
req := NewRequest(t, "GET", "/api/v1/repos/user30/empty/media/main/something").AddTokenAuth(token)
_ = session.MakeRequest(t, req, http.StatusNotFound)
}