Skip to content
Open
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
35 changes: 23 additions & 12 deletions cmd/cli-uploader/cliapi/cliapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,23 +83,25 @@ func GetVersion() (string, int, error) {
return parsedResult.Version, parsedResult.VersionInt, nil
}

// GetConfig returns the upload configuration of the Gokapi server
func GetConfig() (int, int, bool, error) {
// GetConfig returns the upload configuration of the Gokapi server: the maximum file size, the chunk size,
// whether end-to-end encryption is enabled and the maximum expiry in seconds (0 if unlimited)
func GetConfig() (int, int, bool, int64, error) {
result, err := getUrl(gokapiUrl+"/info/config", []header{}, false)
if err != nil {
return 0, 0, false, err
return 0, 0, false, 0, err
}
type expectedFormat struct {
MaxFilesize int
MaxChunksize int
MaxExpirySeconds int64
EndToEndEncryptionEnabled bool
}
var parsedResult expectedFormat
err = json.Unmarshal([]byte(result), &parsedResult)
if err != nil {
return 0, 0, false, err
return 0, 0, false, 0, err
}
return parsedResult.MaxFilesize, parsedResult.MaxChunksize, parsedResult.EndToEndEncryptionEnabled, nil
return parsedResult.MaxFilesize, parsedResult.MaxChunksize, parsedResult.EndToEndEncryptionEnabled, parsedResult.MaxExpirySeconds, nil
}

func stripApiKeyOnRedirect(req *http.Request, via []*http.Request) error {
Expand Down Expand Up @@ -159,7 +161,7 @@ func UploadFile(uploadParams cliflags.FlagConfig) (models.FileApiOutput, error)
os.Exit(4)
}
defer file.Close()
maxSize, chunkSize, isE2e, err := GetConfig()
maxSize, chunkSize, isE2e, maxExpirySeconds, err := GetConfig()
if err != nil {
return models.FileApiOutput{}, err
}
Expand Down Expand Up @@ -200,7 +202,7 @@ func UploadFile(uploadParams cliflags.FlagConfig) (models.FileApiOutput, error)
return models.FileApiOutput{}, err
}
}
metaData, err := completeChunk(uuid, "Encrypted File", sizeBytes, realSize, true, uploadParams, progressBar)
metaData, err := completeChunk(uuid, "Encrypted File", sizeBytes, realSize, true, uploadParams, maxExpirySeconds, progressBar)
if err != nil {
return models.FileApiOutput{}, err
}
Expand All @@ -227,7 +229,7 @@ func UploadFile(uploadParams cliflags.FlagConfig) (models.FileApiOutput, error)
return models.FileApiOutput{}, err
}
}
metaData, err := completeChunk(uuid, nameToBase64(file, uploadParams), sizeBytes, realSize, false, uploadParams, progressBar)
metaData, err := completeChunk(uuid, nameToBase64(file, uploadParams), sizeBytes, realSize, false, uploadParams, maxExpirySeconds, progressBar)
if err != nil {
return models.FileApiOutput{}, err
}
Expand Down Expand Up @@ -470,7 +472,7 @@ func uploadChunk(f io.Reader, uuid string, offset, chunkSize, filesize int64, pr
return nil
}

func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool, uploadParams cliflags.FlagConfig, progressBar *progressbar.ProgressBar) (models.FileApiOutput, error) {
func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool, uploadParams cliflags.FlagConfig, maxExpirySeconds int64, progressBar *progressbar.ProgressBar) (models.FileApiOutput, error) {
type expectedFormat struct {
FileInfo models.FileApiOutput `json:"FileInfo"`
}
Expand All @@ -480,17 +482,20 @@ func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool,
if !uploadParams.JsonOutput {
fmt.Println("Finalising...")
}
result, err := getUrl(gokapiUrl+"/chunk/complete", []header{
headers := []header{
{"uuid", uid},
{"filename", filename},
{"filesize", strconv.FormatInt(filesize, 10)},
{"realsize", strconv.FormatInt(realsize, 10)},
{"isE2E", strconv.FormatBool(useE2e)},
{"allowedDownloads", strconv.Itoa(uploadParams.ExpiryDownloads)},
{"expiryDays", strconv.Itoa(uploadParams.ExpiryDays)},
{"password", uploadParams.Password},
{"contenttype", "application/octet-stream"},
}, true)
}
if isExpiryHeaderRequired(uploadParams, maxExpirySeconds) {
headers = append(headers, header{"expiryDays", strconv.Itoa(uploadParams.ExpiryDays)})
}
result, err := getUrl(gokapiUrl+"/chunk/complete", headers, true)
if err != nil {
return models.FileApiOutput{}, err
}
Expand All @@ -502,6 +507,12 @@ func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool,
return parsedResult.FileInfo, nil
}

// isExpiryHeaderRequired returns false if the server limits the expiry and the user did not set one,
// so that the server's default applies instead of the CLI's default of unlimited, which would be refused
func isExpiryHeaderRequired(uploadParams cliflags.FlagConfig, maxExpirySeconds int64) bool {
return maxExpirySeconds == 0 || uploadParams.IsExpiryDaysSet
}

func lockUnlockE2eLock(isUnlock bool) error {
var url = gokapiUrl + "/e2e/mutex/lock"
if isUnlock {
Expand Down
40 changes: 40 additions & 0 deletions cmd/cli-uploader/cliapi/cliapi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//go:build test

package cliapi

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/forceu/gokapi/cmd/cli-uploader/cliflags"
"github.com/forceu/gokapi/internal/test"
)

func TestCompleteChunkExpiryHeader(t *testing.T) {
var receivedHeaders http.Header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHeaders = r.Header.Clone()
_, _ = w.Write([]byte(`{"Result":"OK","FileInfo":{}}`))
}))
defer server.Close()
Init(server.URL, "apikey", nil)

testCases := []struct {
name string
params cliflags.FlagConfig
maxExpirySeconds int64
expectedHeader []string
}{
{"no server limit, flag not set", cliflags.FlagConfig{}, 0, []string{"0"}},
{"no server limit, flag set", cliflags.FlagConfig{ExpiryDays: 5, IsExpiryDaysSet: true}, 0, []string{"5"}},
{"server limit, flag not set", cliflags.FlagConfig{}, 3600, nil},
{"server limit, flag set", cliflags.FlagConfig{ExpiryDays: 0, IsExpiryDaysSet: true}, 3600, []string{"0"}},
}
for _, tc := range testCases {
tc.params.JsonOutput = true
_, err := completeChunk("uuid", "file", 1, 1, false, tc.params, tc.maxExpirySeconds, nil)
test.IsNilWithMessage(t, err, tc.name)
test.IsEqual(t, receivedHeaders.Values("expiryDays"), tc.expectedHeader)
}
}
2 changes: 1 addition & 1 deletion cmd/cli-uploader/cliconfig/cliconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func CreateLogin() {
}
fmt.Print("OK\nDownloading configuration...")

_, _, isE2E, err := cliapi.GetConfig()
_, _, isE2E, _, err := cliapi.GetConfig()
if err != nil {
fmt.Println("FAIL")
if errors.Is(err, cliapi.ErrUnauthorised) {
Expand Down
4 changes: 3 additions & 1 deletion cmd/cli-uploader/cliflags/cliflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type FlagConfig struct {
ExpiryDays int
ExpiryDownloads int
Password string
IsExpiryDaysSet bool
}

// Parse parses the command line arguments and returns the mode.
Expand Down Expand Up @@ -91,6 +92,7 @@ func GetUploadParameters(mode int) FlagConfig {
fallthrough
case "--expiry-days":
result.ExpiryDays = requireInt(getParameter(&i))
result.IsExpiryDaysSet = true
case "-d":
fallthrough
case "--expiry-downloads":
Expand Down Expand Up @@ -296,7 +298,7 @@ func printUsage(exitCode int) {
fmt.Println(" -c, --configuration <path> Path to configuration file (default: gokapi-cli.json)")
fmt.Println(" -j, --json Output the result in JSON only")
fmt.Println(" -x, --disable-e2e Disable end-to-end encryption")
fmt.Println(" -e, --expiry-days <int> Set file expiry in days (default: unlimited)")
fmt.Println(" -e, --expiry-days <int> Set file expiry in days (default: unlimited, or the server's maximum if set)")
fmt.Println(" -d, --expiry-downloads <int> Set max allowed downloads (default: unlimited)")
fmt.Println(" -p, --password <string> Set a password for the file")
fmt.Println(" -n, --name <string> Change final filename for uploaded file")
Expand Down
30 changes: 30 additions & 0 deletions cmd/cli-uploader/cliflags/cliflags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//go:build test

package cliflags

import (
"os"
"testing"

"github.com/forceu/gokapi/internal/test"
)

func TestGetUploadParametersExpiryDays(t *testing.T) {
originalArgs := os.Args
defer func() { os.Args = originalArgs }()

os.Args = []string{"gokapi-cli", "upload", "-f", "file"}
result := GetUploadParameters(ModeUpload)
test.IsEqualInt(t, result.ExpiryDays, 0)
test.IsEqualBool(t, result.IsExpiryDaysSet, false)

os.Args = []string{"gokapi-cli", "upload", "-f", "file", "--expiry-days", "0"}
result = GetUploadParameters(ModeUpload)
test.IsEqualInt(t, result.ExpiryDays, 0)
test.IsEqualBool(t, result.IsExpiryDaysSet, true)

os.Args = []string{"gokapi-cli", "upload", "-f", "file", "-e", "7"}
result = GetUploadParameters(ModeUpload)
test.IsEqualInt(t, result.ExpiryDays, 7)
test.IsEqualBool(t, result.IsExpiryDaysSet, true)
}
12 changes: 12 additions & 0 deletions docs/advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,18 @@ Available environment variables
+-------------------------------------+----------------------------------------------------------------------------------------------------------+-----------------+-----------------------------+
| GOKAPI_LOG_STDOUT | Also outputs all log file entries to the console output, if set to true | No | false |
+-------------------------------------+----------------------------------------------------------------------------------------------------------+-----------------+-----------------------------+
| GOKAPI_MAX_EXPIRY_SECONDS | Sets the maximum time in seconds that a file is stored before it expires | No | 0 |
| | | | |
| | Applies to all users including admins: uploads, file request uploads, edits, | | |
| | | | |
| | duplicates and file request links. A longer or unlimited expiry is refused, the | | |
| | | | |
| | default expiry is reduced to this value and files uploaded through file requests | | |
| | | | |
| | expire after this time | | |
| | | | |
| | Set to 0 to disable the limit | | |
+-------------------------------------+----------------------------------------------------------------------------------------------------------+-----------------+-----------------------------+
| GOKAPI_MAX_FILESIZE | Sets the maximum allowed file size in MB | Yes | 102400 |
| | | | |
| | Default 102400 = 100GB | | |
Expand Down
4 changes: 2 additions & 2 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ After you have started the Gokapi server, log in with your credentials by going
There you can list and manage files and upload new files. You will also see three fields:

- *Allowed downloads* lets you set how many times a file can be downloaded before it gets deleted
- *Expiry in days* lets you set after how many days a file gets deleted latest
- *Expiry in days* lets you set after how many days a file gets deleted latest. If the server sets a maximum lifetime with ``GOKAPI_MAX_EXPIRY_SECONDS``, files cannot be stored for longer or without a time limit, and files uploaded through file requests expire after that time
- *Password* lets you set a password that a user needs to enter before downloading the file. Please note that the file on the storage server is not encrypted.

Uploading new files
Expand Down Expand Up @@ -116,7 +116,7 @@ To create a new request, click the *Plus* icon at the top right. To modify an ex
* - **Max Size**
- Set a maximum total size (in MB) for the entire request.
* - **Expiry**
- Set a date after which the link will no longer function.
- Set a date after which the link will no longer function. If the server sets a maximum lifetime with ``GOKAPI_MAX_EXPIRY_SECONDS``, the date cannot be later than that and the link cannot be kept without an expiry.
* - **Notes**
- Public notes that are shown on the upload page

Expand Down
7 changes: 7 additions & 0 deletions internal/environment/Environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ type Environment struct {
// for all users
// Default 10240 = 10GB
MaxSizeGuestUploadMb int `env:"MAX_SIZE_GUESTUPLOAD" envDefault:"10240" onlyPositive:"true"`
// Sets the maximum time in seconds that a file is stored before it expires
// Applies to all users including admins: uploads, file request uploads, edits,
// duplicates and file request links. A longer or unlimited expiry is refused, the
// default expiry is reduced to this value and files uploaded through file requests
// expire after this time
// Set to 0 to disable the limit
MaxExpirySeconds int64 `env:"MAX_EXPIRY_SECONDS" envDefault:"0" onlyPositive:"true"`
// Set the number of chunks that are uploaded in parallel for a single file
MaxParallelUploads int `env:"MAX_PARALLEL_UPLOADS" envDefault:"3" onlyPositive:"true" persistent:"true"`
// Sets the minimum free space on the disk in MB for accepting an upload
Expand Down
12 changes: 12 additions & 0 deletions internal/environment/Environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ func TestEnvLoad(t *testing.T) {
os.Unsetenv("GOKAPI_MAX_FILESIZE")
}

func TestMaxExpirySeconds(t *testing.T) {
env := New()
test.IsEqualInt64(t, env.MaxExpirySeconds, 0)
os.Setenv("GOKAPI_MAX_EXPIRY_SECONDS", "3600")
env = New()
test.IsEqualInt64(t, env.MaxExpirySeconds, 3600)
os.Setenv("GOKAPI_MAX_EXPIRY_SECONDS", "-5")
env = New()
test.IsEqualInt64(t, env.MaxExpirySeconds, 0)
os.Unsetenv("GOKAPI_MAX_EXPIRY_SECONDS")
}

func TestIsAwsProvided(t *testing.T) {
os.Unsetenv("GOKAPI_AWS_BUCKET")
os.Unsetenv("GOKAPI_AWS_REGION")
Expand Down
2 changes: 2 additions & 0 deletions internal/webserver/Webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,7 @@ type AdminView struct {
CpuLoad int
MemoryUsagePercent int
DiskUsagePercent int
MaxExpirySeconds int64
DataServed int64
Uptime int64
TimeNow int64
Expand Down Expand Up @@ -929,6 +930,7 @@ func (u *AdminView) convertGlobalConfig(view int, user models.User) *AdminView {
u.IsAdminView = true
u.ActiveView = view
u.MaxFileSize = config.MaxFileSizeMB
u.MaxExpirySeconds = configuration.GetEnvironment().MaxExpirySeconds
u.IsLogoutAvailable = authentication.IsLogoutAvailable()
u.ShowApiMenu = showApiMenu
u.IsUserTabAvailable = config.Authentication.Method != models.AuthenticationDisabled
Expand Down
Loading