mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-18 22:33:42 +00:00
feat: new ui (#1455)
This commit is contained in:
742 files changed
+59951
-5934
No files matched your search
@@ -197,6 +197,25 @@ func GetTask(w http.ResponseWriter, r *http.Request) {
|
||||
WriteJson(w, model.NewOkResult(task))
|
||||
}
|
||||
|
||||
func GetTaskStatus(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
taskId := vars["id"]
|
||||
if taskId == "" {
|
||||
WriteJson(w, model.NewErrorResult("param invalid: id", model.CodeInvalidParam))
|
||||
return
|
||||
}
|
||||
status, err := Downloader.RuntimeStatus(taskId)
|
||||
if err != nil {
|
||||
if err == download.ErrTaskNotFound {
|
||||
WriteJson(w, model.NewErrorResult("task not found", model.CodeTaskNotFound))
|
||||
return
|
||||
}
|
||||
WriteJson(w, model.NewErrorResult(err.Error()))
|
||||
return
|
||||
}
|
||||
WriteJson(w, model.NewOkResult(status))
|
||||
}
|
||||
|
||||
func GetTasks(w http.ResponseWriter, r *http.Request) {
|
||||
filter, errResult := parseFilter(r)
|
||||
if errResult != nil {
|
||||
|
||||
+63
-25
@@ -35,6 +35,11 @@ var (
|
||||
Downloader *download.Downloader
|
||||
)
|
||||
|
||||
const (
|
||||
webAuthCookieName = "gopeed_web_auth"
|
||||
webAuthTokenTTL = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
func Start(startCfg *model.StartConfig) (port int, err error) {
|
||||
// avoid repeat start
|
||||
if srv != nil {
|
||||
@@ -118,6 +123,9 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := Downloader.ContinueOnStartup(); err != nil {
|
||||
Downloader.Logger.Warn().Err(err).Msg("auto-start tasks failed")
|
||||
}
|
||||
|
||||
var r = mux.NewRouter()
|
||||
r.Methods(http.MethodGet).Path("/api/v1/info").HandlerFunc(Info)
|
||||
@@ -132,6 +140,7 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
|
||||
r.Methods(http.MethodDelete).Path("/api/v1/tasks/{id}").HandlerFunc(DeleteTask)
|
||||
r.Methods(http.MethodDelete).Path("/api/v1/tasks").HandlerFunc(DeleteTasks)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/tasks/{id}").HandlerFunc(GetTask)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/tasks/{id}/status").HandlerFunc(GetTaskStatus)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/tasks").HandlerFunc(GetTasks)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/tasks/{id}/stats").HandlerFunc(GetStats)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/config").HandlerFunc(GetConfig)
|
||||
@@ -164,7 +173,17 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
|
||||
return
|
||||
}
|
||||
|
||||
WriteJson(w, model.NewOkResult(token))
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: webAuthCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
Expires: time.Now().Add(webAuthTokenTTL),
|
||||
MaxAge: int(webAuthTokenTTL.Seconds()),
|
||||
HttpOnly: true,
|
||||
Secure: requestUsesHTTPS(r),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
WriteJson(w, model.NewNilResult())
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -182,6 +201,16 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
|
||||
|
||||
r.Use(func(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if enableWebAuth && isProtectedWebFilePath(r.URL.Path) {
|
||||
cookie, err := r.Cookie(webAuthCookieName)
|
||||
if err != nil || !validWebAuthToken(cookie.Value, startCfg.WebAuth) {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
if enableApiToken {
|
||||
apiTokenHeader := r.Header["X-Api-Token"]
|
||||
// If api token header is set, only check api token ignore basic auth
|
||||
@@ -202,30 +231,8 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
|
||||
return
|
||||
}
|
||||
|
||||
token := r.Header.Get("Authorization")
|
||||
if token == "" {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
tokenData, err := aesDecrypt(aesKey, token)
|
||||
if err != nil {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
parts := strings.SplitN(string(tokenData), ":", 3)
|
||||
username := parts[0]
|
||||
password := parts[1]
|
||||
timestamp, _ := strconv.Atoi(parts[2])
|
||||
|
||||
if username != startCfg.WebAuth.Username || password != startCfg.WebAuth.Password {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the token is expired (7 days)
|
||||
if time.Now().Unix()-int64(timestamp) > 7*24*3600 {
|
||||
cookie, err := r.Cookie(webAuthCookieName)
|
||||
if err != nil || !validWebAuthToken(cookie.Value, startCfg.WebAuth) {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
@@ -261,6 +268,37 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
|
||||
return srv, listener, nil
|
||||
}
|
||||
|
||||
func isProtectedWebFilePath(urlPath string) bool {
|
||||
return urlPath == "/fs" || strings.HasPrefix(urlPath, "/fs/")
|
||||
}
|
||||
|
||||
func validWebAuthToken(token string, auth *model.WebAuth) bool {
|
||||
if token == "" || auth == nil {
|
||||
return false
|
||||
}
|
||||
tokenData, err := aesDecrypt(aesKey, token)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
parts := strings.SplitN(string(tokenData), ":", 3)
|
||||
if len(parts) != 3 || parts[0] != auth.Username || parts[1] != auth.Password {
|
||||
return false
|
||||
}
|
||||
timestamp, err := strconv.ParseInt(parts[2], 10, 64)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return time.Now().Unix()-timestamp <= int64(webAuthTokenTTL.Seconds())
|
||||
}
|
||||
|
||||
func requestUsesHTTPS(r *http.Request) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
forwardedProto := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0])
|
||||
return strings.EqualFold(forwardedProto, "https")
|
||||
}
|
||||
|
||||
func resolvePath(urlPath string, prefix string) (identity string, path string, err error) {
|
||||
// remove prefix
|
||||
clearPath := strings.TrimPrefix(urlPath, prefix)
|
||||
|
||||
+92
-11
@@ -144,6 +144,23 @@ func TestCreateDirectTask(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetTaskStatus(t *testing.T) {
|
||||
doTest(func() {
|
||||
resolved := httpRequestCheckOk[*download.ResolveResult](http.MethodPost, "/api/v1/resolve", resolveReq)
|
||||
taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", &model.CreateTask{Rid: resolved.ID})
|
||||
status := httpRequestCheckOk[*download.TaskRuntimeStatus](http.MethodGet, "/api/v1/tasks/"+taskId+"/status", nil)
|
||||
if status.Total != test.BuildSize {
|
||||
t.Fatalf("task status total = %d, want %d", status.Total, test.BuildSize)
|
||||
}
|
||||
if status.Files == nil {
|
||||
t.Fatal("task status files must be an empty array or contain file progress, not null")
|
||||
}
|
||||
|
||||
code, _ := httpRequest[*download.TaskRuntimeStatus](http.MethodGet, "/api/v1/tasks/missing/status", nil)
|
||||
checkCode(code, model.CodeTaskNotFound)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateDirectTaskBatch(t *testing.T) {
|
||||
doTest(func() {
|
||||
reqs := make([]*base.CreateTaskBatchItem, 0)
|
||||
@@ -438,6 +455,7 @@ func TestGetAndPutConfig(t *testing.T) {
|
||||
doTest(func() {
|
||||
cfg := httpRequestCheckOk[*base.DownloaderStoreConfig](http.MethodGet, "/api/v1/config", nil)
|
||||
cfg.DownloadDir = "./download"
|
||||
cfg.AutoStartTasks = true
|
||||
cfg.Extra = map[string]any{
|
||||
"serverConfig": &Config{
|
||||
Host: "127.0.0.1",
|
||||
@@ -809,16 +827,73 @@ func TestAuthorization(t *testing.T) {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
token := httpRequestCheckOk[string](http.MethodPost, "/api/web/login", cfg.WebAuth)
|
||||
authToken := fmt.Sprintf("Bearer %s", token)
|
||||
authHeaders := map[string]string{
|
||||
"Authorization": authToken,
|
||||
status, loginHeaders, loginBody := doHttpRequest1(http.MethodPost, "/api/web/login", nil, cfg.WebAuth)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("login status = %d, want %d", status, http.StatusOK)
|
||||
}
|
||||
var loginResult model.Result[any]
|
||||
if err := json.Unmarshal(loginBody, &loginResult); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loginResult.Data != nil {
|
||||
t.Fatalf("login response exposed session data: %#v", loginResult.Data)
|
||||
}
|
||||
loginResponse := &http.Response{Header: http.Header{"Set-Cookie": []string{loginHeaders["Set-Cookie"]}}}
|
||||
cookies := loginResponse.Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("login cookies = %d, want 1", len(cookies))
|
||||
}
|
||||
authCookie := cookies[0]
|
||||
if authCookie.Name != webAuthCookieName || authCookie.Value == "" || authCookie.Path != "/" ||
|
||||
!authCookie.HttpOnly || authCookie.SameSite != http.SameSiteLaxMode || authCookie.MaxAge <= 0 {
|
||||
t.Fatalf("unexpected login cookie: %#v", authCookie)
|
||||
}
|
||||
bearerHeaders := map[string]string{
|
||||
"Authorization": "Bearer " + authCookie.Value,
|
||||
}
|
||||
authCookieHeader := map[string]string{
|
||||
"Cookie": fmt.Sprintf("%s=%s", authCookie.Name, authCookie.Value),
|
||||
}
|
||||
|
||||
for _, filePath := range []string{
|
||||
"/fs/extensions/not_exist/icon.png",
|
||||
"/fs/tasks/not_exist/file.bin",
|
||||
} {
|
||||
status, _ = doHttpRequest0(http.MethodGet, filePath, nil, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("unauthenticated %s status = %d, want %d", filePath, status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, filePath, bearerHeaders, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("Bearer-only %s status = %d, want %d", filePath, status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, filePath, authCookieHeader, nil)
|
||||
if status != http.StatusNotFound {
|
||||
t.Errorf("cookie-authenticated %s status = %d, want %d", filePath, status, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/fs/future-resource", nil, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("unauthenticated future /fs route status = %d, want %d", status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/fs/extensions/not_exist/icon.png", map[string]string{
|
||||
"Cookie": webAuthCookieName + "=invalid",
|
||||
}, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("invalid-cookie file status = %d, want %d", status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", nil, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusUnauthorized)
|
||||
}
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", bearerHeaders, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("Bearer-authenticated API status = %v, want %v", status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
|
||||
"Authorization": "xxx",
|
||||
@@ -841,7 +916,7 @@ func TestAuthorization(t *testing.T) {
|
||||
|
||||
fakeToken := buildToken("fake", "fake", time.Now().Unix())
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
|
||||
"Authorization": fmt.Sprintf("Bearer %s", fakeToken),
|
||||
"Cookie": fmt.Sprintf("%s=%s", webAuthCookieName, fakeToken),
|
||||
}, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusUnauthorized)
|
||||
@@ -849,13 +924,19 @@ func TestAuthorization(t *testing.T) {
|
||||
|
||||
expireToken := buildToken(cfg.WebAuth.Username, cfg.WebAuth.Password, time.Now().Add(-time.Hour*8*24).Unix())
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
|
||||
"Authorization": fmt.Sprintf("Bearer %s", expireToken),
|
||||
"Cookie": fmt.Sprintf("%s=%s", webAuthCookieName, expireToken),
|
||||
}, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusUnauthorized)
|
||||
}
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/fs/extensions/not_exist/icon.png", map[string]string{
|
||||
"Cookie": fmt.Sprintf("%s=%s", webAuthCookieName, expireToken),
|
||||
}, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("expired-cookie file status = %d, want %d", status, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", authHeaders, nil)
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", authCookieHeader, nil)
|
||||
if status != http.StatusOK {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusOK)
|
||||
}
|
||||
@@ -868,16 +949,16 @@ func TestAuthorization(t *testing.T) {
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
|
||||
"Authorization": authToken,
|
||||
"X-Api-Token": cfg.ApiToken,
|
||||
"Cookie": fmt.Sprintf("%s=%s", authCookie.Name, authCookie.Value),
|
||||
"X-Api-Token": cfg.ApiToken,
|
||||
}, nil)
|
||||
if status != http.StatusOK {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusOK)
|
||||
}
|
||||
|
||||
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
|
||||
"Authorization": authToken,
|
||||
"X-Api-Token": "",
|
||||
"Cookie": fmt.Sprintf("%s=%s", authCookie.Name, authCookie.Value),
|
||||
"X-Api-Token": "",
|
||||
}, nil)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusUnauthorized)
|
||||
|
||||
Reference in new issue
Block a user