Skip to content

Add a server-wide maximum file lifetime (GOKAPI_MAX_EXPIRY_SECONDS) - #440

Open
D3strukt0r wants to merge 4 commits into
Forceu:masterfrom
D3strukt0r:feat/max-expiry
Open

D3strukt0r wants to merge 4 commits into
Forceu:masterfrom
D3strukt0r:feat/max-expiry

Conversation

@D3strukt0r

@D3strukt0r D3strukt0r commented Oct 31, 2026 •

Copy link
Copy Markdown

Description

Closes #265. cc @Forceu, and @i0rt and @Str00pwafel, who asked for this in #265.

Adds GOKAPI_MAX_EXPIRY_SECONDS, a server-wide maximum lifetime for files in seconds (0 or unset = no limit, behaviour unchanged). When it is set:

  • An explicit expiry that is longer than the maximum, or unlimited, is refused with HTTP 400 and the new error code ExpiryTooLong: /chunk/complete, /files/add, /files/modify and /files/duplicate. Admins included.
  • Without an explicit expiry, the default becomes the shorter of 14 days and the maximum.
  • Files uploaded through file requests, which are stored without a time limit today, expire after the maximum.
  • Duplicating a file whose expiry is unlimited or beyond the maximum without passing expiryDays is refused, so the copy can't outlive the limit.
  • /info/config reports MaxExpirySeconds. gokapi-cli uses it: when the server has a maximum and --expiry-days isn't given, it leaves the expiry out so the server default applies instead of sending "unlimited". Without a maximum the CLI behaves as before.
  • Admin UI: when a maximum is set, the time limit can't be switched off on the upload page, the days field is limited to it, and the edit dialog has no "unlimited" option and a calendar that ends at the maximum. Note: editing a file that is still unlimited from before the maximum was set pre-fills its expiry with the maximum, so saving the dialog shortens it.

The check lives in one place, fileupload.CheckMaxExpiry, with CapToMaxExpiry for expiries the uploader didn't choose. The setting is environment-only like GOKAPI_MAX_SIZE_GUESTUPLOAD, so there is no config or database change. Existing files keep their expiry when the maximum is switched on.

This probably conflicts with your draft #405 in routing.go, FileUpload.go and Api.go; happy to rebase onto it if you'd rather merge that first.

Screenshots (GOKAPI_MAX_EXPIRY_SECONDS=1209600, 14 days)

Upload page: the expiry can't be switched off and is limited to 14 days.

Bildschirmfoto 2026-10-31 um 15 15 52

Edit dialog: no "unlimited" option, the calendar ends at the maximum.

Bildschirmfoto 2026-10-31 um 15 16 15

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactor / Chore

Technical Details

  • Database changes: No
  • Storage backend affected: No (applies to Local and S3 alike)
  • Usage of AI: Yes. The implementation and tests were written with Claude Code (Anthropic), following a design I specified. I reviewed the code, and the behaviour was checked end to end on a running server as described below.

How Has This Been Tested?

  • Manual Testing: server built from this branch with GOKAPI_MAX_EXPIRY_SECONDS=3600 and local storage: uploads with expiryDays=0 and 30 refused with 400, without expiryDays expiring after one hour; editing to unlimited refused; duplicating an unlimited file without expiryDays refused; a guest upload through a file request expires after one hour; gokapi-cli without --expiry-days works; admin upload page and edit dialog checked in Chrome (also with a 14-day maximum, see screenshots). With the variable unset everything behaves as before (unlimited uploads, 14-day default, unlimited guest uploads). File requests (added after review): the dialog locks the expiry on and caps the calendar at the maximum; /uploadrequest/save refuses unlimited and over-limit expiries with 400 ExpiryTooLong, and a request saved without an expiry gets 14 days capped to the maximum. A typed expiry above the maximum is clamped before the upload starts.
  • Unit Tests: go test ./... -parallel 8 with the CI tag sets test,awsmock, test,noaws, test,noaws,integration and test,awstest, all passing (13 new tests each).
  • Environment: Docker (golang:1.27, Go 1.27.4 as in go.mod) on macOS

Checklist

  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have made corresponding changes to the documentation.
  • My changes generate no new warnings.

@daniele-doit

Copy link
Copy Markdown

Thanks for working on this @D3strukt0r — we run Gokapi under a strict retention policy (no unlimited uploads, hard 90-day cap across all users) and currently have to enforce this via custom/admin.js + DB triggers, so having it built in would let us drop our workaround.

While reviewing the diff against our setup (and current master, which now has a small conflict in routing.go / Api.go after 0d51522), I noticed a few edge cases that might be worth covering here or as small follow-ups:

1. Capping File Request link expiry (apiURequestSave)

Capping the uploaded files in apiChunkUploadRequestComplete / parseConfig solves the storage side, but in apiURequestSave (internal/webserver/api/Api.go) the request link itself can still be created or edited with Expiry == 0 (unlimited) or beyond MaxExpirySeconds:

if request.IsExpirySet {
	err := fileupload.CheckMaxExpiry(request.Expiry == 0, request.Expiry)
	if err != nil {
		sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, err.Error())
		return
	}
	uploadRequest.Expiry = request.Expiry
} else if isNewRequest && configuration.GetEnvironment().MaxExpirySeconds > 0 {
	uploadRequest.Expiry = time.Now().Unix() + configuration.GetEnvironment().MaxExpirySeconds
}

(Along with passing maxExpiryTimestamp to createCalendar("mi_expiry", ...) and hiding/locking #mc_expiry in admin_ui_filerequest.js, matching what showEditModal already does in admin_ui_upload.js.)

2. Clamping typed values on #expiryDays before Dropzone starts uploading

In applyMaxExpiryToUpload() (admin_ui_upload.js), setting expiryDays.max = maxDays restricts the spinner arrows, but a user can still type a larger number directly. Since Dropzone reads expiryDays.value in JS without native HTML form validation, a large multi-GB upload will send all chunks first and only fail with 400 ExpiryTooLong at the end on /api/chunk/complete. Clamping expiryDays.value on change (or inside chunkUploaded before calling apiChunkComplete) avoids wasted uploads.

3. Optional clamping of pre-existing unlimited files

Keeping existing files untouched by default makes total sense so nobody loses files unexpectedly. For installations enabling GOKAPI_MAX_EXPIRY_SECONDS for compliance/retention reasons, an opt-in env flag (e.g. GOKAPI_MAX_EXPIRY_ENFORCE_EXISTING=true, default false) running during storage.CleanUp or startup through the DB abstraction layer would handle both SQLite and Redis cleanly:

func enforceMaxExpiryOnExisting(timeNow int64) {
	env := configuration.GetEnvironment()
	if env.MaxExpirySeconds == 0 || !env.EnforceMaxExpiryExisting {
		return
	}
	maxTimestamp := timeNow + env.MaxExpirySeconds
	for _, file := range database.GetAllMetadata() {
		if file.UnlimitedTime || file.ExpireAt > maxTimestamp {
			file.UnlimitedTime = false
			file.ExpireAt = maxTimestamp
			database.SaveMetaData(file)
		}
	}
}

4. config.json persistence for non-Docker setups

On bare-metal/systemd deployments configured primarily via config.json, marking MaxExpirySeconds with persistent:"true" (similar to MAX_FILESIZE / MaxFileSizeMB) could also be nice if @Forceu prefers keeping global limits in config.json as well, though env-only works fine via systemd Environment= too.

Happy to help test a rebased branch if useful!

@D3strukt0r

Copy link
Copy Markdown
Author

Thanks a lot for the careful review, @daniele-doit, and for the snippets.

I rebased the branch onto current master. The conflict was with 88827de's new size check in apiChunkUploadRequestComplete: both checks are in now, the size check first, then the expiry cap.

1. File request link expiry: done. With GOKAPI_MAX_EXPIRY_SECONDS set, /uploadrequest/save refuses expiry=0 (unlimited) and an expiry later than now + maximum with 400 ExpiryTooLong, both when creating and when editing. The check runs before anything is stored, so a refused new request leaves no orphaned request or API key behind. A new request saved without an expiry header gets the same default as files: 14 days, or the maximum if that is shorter. Editing a request without the header leaves its expiry as it is. Without a maximum nothing changes. In the UI, the expiry checkbox in the file request dialog is locked on (disabled, like the max files/size checkboxes for guest limits), the calendar stops at the maximum, and the default and the stored fr_expiry default are clamped to it. The openapi description of the expiry header says so.

2. Typed expiry days: done. #expiryDays is now clamped to the maximum on input and change, again in the Dropzone addedfile handler before the defaults are saved (so no over-limit default ends up in localStorage and the upload starts with a valid value), and once more right before /chunk/complete as a guard.

3. Clamping existing files: not in this PR. It rewrites existing users' data, and it would be a read-modify-save through SaveMetaData that can race with a download-count update, like apiEditFile today. Whether an instance may shorten files that were uploaded under different rules also feels like a policy call for @Forceu. I'm happy to do it as an opt-in follow-up (off by default, as you suggested) if that's wanted.

4. persistent:"true": not in this PR. The tag on its own only changes the docs table. Real persistence means a config.json field, copying it during setup, switching every runtime read to the config, a config version bump (23 to 24) and fixture changes. The guest upload limits it sits next to (GOKAPI_MAX_SIZE_GUESTUPLOAD, GOKAPI_MAX_FILES_GUESTUPLOAD) are env-only as well, and on bare metal systemd's Environment= covers it. If @Forceu prefers global limits in config.json, I can do that as a follow-up.

New commits on top of the rebased feature commit: a test for the file request save, the file request change, and the typed-days fix. All four CI tag sets pass.

Checked in a browser against a local build with GOKAPI_MAX_EXPIRY_SECONDS=604800: the upload field stops at 7, typing 999 turns into 7 and 0 into 1; a file added with 999 typed into the field (without the input event) was stored with exactly 7 days; the file request dialog shows the expiry checkbox locked on with the default and the calendar's last day at now + 7 days; through the API, a new request with expiry=0 or 30 days gets 400 ExpiryTooLong, 5 days is saved, and one without the header gets exactly 7 days. Restarted without the variable, expiry=0 and a request without the header are unlimited again, as before.

cc @Forceu

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Restrict Expiry Time and Download Limit to Predefined Values

2 participants