From 81668193bda64a3f5f4705e018e089193a03c7e4 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Thu, 5 Nov 2026 20:57:59 -0700 Subject: [PATCH 1/4] Added pathed file upload endpoints, added better file typing --- .claude/skills/lightning-server.md | 6 +- CLAUDE.md | 4 +- REVIEW-GUIDE-5.4.md | 2 +- .../lightningserver/demo/Server.kt | 4 +- docs-guide/drafts/files.md | 12 +- docs-guide/drafts/serialization.md | 12 +- docs-guide/guide/project-structure.md | 2 +- docs/files.md | 12 +- docs/files/index.md | 3 +- docs/migration-v4-to-v5.md | 2 +- files-shared/build.gradle.kts | 13 - .../files/ClientFileUploadEndpoints.kt | 59 ++++ .../files/ClientUploadEarlyEndpoints.kt | 24 -- .../files/LiveClientModelRestEndpoints.kt | 22 -- .../lightningserver/files/index.md | 14 +- .../lightningserver/files/models.kt | 42 ++- files/build.gradle.kts | 6 + .../files/GlobalUploadEndpoints.kt | 91 ++++++ .../lightningserver/files/UploadBasis.kt | 278 ++++++++++++++++++ .../files/UploadEarlyEndpoints.kt | 273 ----------------- .../lightningserver/files/UploadEndpoints.kt | 74 +++++ .../files/UploadForNextRequest.kt | 25 ++ .../lightningserver/files/UploadToken.kt | 6 +- .../files/FileSystemEndpointsTest.kt | 2 +- .../files/FilesModuleReviewTests.kt | 2 +- .../files/PathedUploadEndpointsTest.kt | 135 +++++++++ .../files/UploadEarlyEndpointTest.kt | 6 +- .../files/UploadEarlyNoScannerTest.kt | 10 +- .../files/UploadEarlyScanningTest.kt | 57 ++-- .../files/UploadEarlySdkTests.kt | 2 +- .../lightningserver/files/generated/Api.kt | 2 +- .../files/generated/LiveApi.kt | 2 +- 32 files changed, 769 insertions(+), 435 deletions(-) create mode 100644 files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientFileUploadEndpoints.kt delete mode 100644 files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientUploadEarlyEndpoints.kt delete mode 100644 files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/LiveClientModelRestEndpoints.kt create mode 100644 files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt create mode 100644 files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt delete mode 100644 files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpoints.kt create mode 100644 files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt create mode 100644 files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt create mode 100644 files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt diff --git a/.claude/skills/lightning-server.md b/.claude/skills/lightning-server.md index d38b9d282..198d90bd6 100644 --- a/.claude/skills/lightning-server.md +++ b/.claude/skills/lightning-server.md @@ -427,11 +427,11 @@ Server.typedEndpoint.test("pathArg", auth = auth, input = RequestData(...)) ⚠️ **Duplicate UploadEarlyEndpoint Declarations** -If you create multiple instances of `UploadEarlyEndpoint` (e.g., in different modules or endpoints), they will have * +If you create multiple instances of `GlobalUploadEndpoints` (e.g., in different modules or endpoints), they will have * *conflicting declarations for how `ServerFile` is serialized**. This causes runtime serialization errors that manifest as `500 Internal Server Error` responses in tests, even though the code compiles successfully. -**Solution:** Only instantiate `UploadEarlyEndpoint` once in your server definition: +**Solution:** Only instantiate `GlobalUploadEndpoints` once in your server definition: ```kotlin object Server : ServerBuilder() { @@ -445,7 +445,7 @@ object Server : ServerBuilder() { } ``` -If you need multiple upload endpoints, reuse the same `UploadEarlyEndpoint` instance or use different endpoint patterns. +If you need multiple upload endpoints, reuse the same `GlobalUploadEndpoints` instance or use different endpoint patterns. ## Common Patterns diff --git a/CLAUDE.md b/CLAUDE.md index 0c146f49e..2d704cdbb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -107,12 +107,12 @@ calls encode their output. #### Common Testing Pitfalls -**Duplicate UploadEarlyEndpoint declarations**: If you create multiple instances of `UploadEarlyEndpoint` (e.g., in +**Duplicate UploadEarlyEndpoint declarations**: If you create multiple instances of `GlobalUploadEndpoints` (e.g., in different modules or test files), they will have conflicting declarations for how `ServerFile` is serialized. This causes runtime serialization errors that manifest as `500 Internal Server Error` responses in tests, even though the code compiles successfully. -**Solution**: Only instantiate `UploadEarlyEndpoint` once in your server definition and reference it from tests. Do not +**Solution**: Only instantiate `GlobalUploadEndpoints` once in your server definition and reference it from tests. Do not create separate instances for testing. ## Architecture diff --git a/REVIEW-GUIDE-5.4.md b/REVIEW-GUIDE-5.4.md index e50c45f2b..30212115a 100644 --- a/REVIEW-GUIDE-5.4.md +++ b/REVIEW-GUIDE-5.4.md @@ -255,7 +255,7 @@ Opt-in. Nothing outside the modules depends on them, the demo doesn't use them, ## 3. Fallout (skim) - **`@Queryable`** replaces `@Serializable @GenerateDataClassPaths` on all models (last commit, `9f39ebba1`). Mechanical; it relies on `@Queryable` implying `@Serializable`. -- **`context(ServerRuntime)` → `context(Engine)`** for setup-only APIs: settings, `Runtime`, `ResolvedPath`, `Authentication(...)`, `testAuth`, SDK generation, `DatabaseTableRegistration`, `UploadEarlyEndpoint`. `SDK.Runtime` now extends `EngineBase`. +- **`context(ServerRuntime)` → `context(Engine)`** for setup-only APIs: settings, `Runtime`, `ResolvedPath`, `Authentication(...)`, `testAuth`, SDK generation, `DatabaseTableRegistration`, `GlobalUploadEndpoints`. `SDK.Runtime` now extends `EngineBase`. - **Interceptor ports:** `AccessLogInterceptor` and `OriginRecording` are `ExecutionInterceptor`s (id suffix now from `execution.logicalId`). CORS, Gzip and SecurityHeaders are physical `HttpInterceptor`/`WebSocketInterceptor`s. `RateLimitInterceptor` is both an `ExecutionInterceptor`, which charges each request a client made (bulk parts and virtual sockets included, internal calls excluded), and an `HttpInterceptor`, which adds its headers. - **`ApiWebSocketHandler` builder lambdas** became `suspend context(ServerRuntime) Connection.() -> …`. `ConnectionWrapper` is now local. `ModelRestUpdatesWebsocket` closes with reason text. - **Small moves:** `ApiHttpHandler` factories moved verbatim to [ApiHttpHandler.builder.kt](typed/src/main/kotlin/com/lightningkite/lightningserver/typed/ApiHttpHandler.builder.kt). `CacheMutex` lost its stored server. `MetaEndpoints` bulk uses `serverRuntime.handle`. diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt index ac54d47f5..22475d192 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt @@ -12,7 +12,7 @@ import com.lightningkite.lightningserver.definition.builder.* import com.lightningkite.lightningserver.demo.endpoints.* import com.lightningkite.lightningserver.demo.models.User import com.lightningkite.lightningserver.files.Files -import com.lightningkite.lightningserver.files.UploadEarlyEndpoint +import com.lightningkite.lightningserver.files.GlobalUploadEndpoints import com.lightningkite.lightningserver.http.* import com.lightningkite.lightningserver.pathing.PathSpec0 import com.lightningkite.lightningserver.pathing.fullUrl @@ -130,7 +130,7 @@ object Server : ServerBuilder() { val user = path.path("user") include UserEndpoints - val uploadEarly = path.path("upload") module UploadEarlyEndpoint(files, database, Runtime.Constant(listOf())) + val uploadEarly = path.path("upload") module GlobalUploadEndpoints(files, database, Runtime.Constant(listOf())) /** * Basic Examples - Simple HTTP endpoints demonstrating fundamental patterns. diff --git a/docs-guide/drafts/files.md b/docs-guide/drafts/files.md index 8643a6ded..c6fbb6b61 100644 --- a/docs-guide/drafts/files.md +++ b/docs-guide/drafts/files.md @@ -5,7 +5,7 @@ Lightning Server provides a unified abstraction for file storage through `ExternalFileSystem`. Files are addressed server-side as `ExternalFile` values and serialized to clients as `ServerFile` URLs. The -`UploadEarlyEndpoint` handles the standard upload workflow where a client uploads a file before +`GlobalUploadEndpoints` handles the standard upload workflow where a client uploads a file before referencing it in a subsequent API call. ## Imports @@ -43,7 +43,7 @@ Converting between the two: - `fileObject.serverFile` — wraps the `ExternalFile`'s internal URL in a `ServerFile` (available everywhere; no runtime needed). - `serverFile.fileObject` — resolves a `ServerFile` back to a `ExternalFile` using the contextual - serializer registered by `UploadEarlyEndpoint`. Requires a `ServerRuntime` context; throws + serializer registered by `GlobalUploadEndpoints`. Requires a `ServerRuntime` context; throws `IllegalStateException` if no serializer is configured. ## Declaring the Files Setting @@ -69,12 +69,12 @@ object FileServer : ServerBuilder() { } ``` -> **Singleton rule:** Instantiate `UploadEarlyEndpoint` exactly **once** per server. The endpoint +> **Singleton rule:** Instantiate `GlobalUploadEndpoints` exactly **once** per server. The endpoint > registers a contextual serializer for `ServerFile`; a second instance registers a conflicting > serializer and causes runtime serialization errors (500 responses) that are difficult to trace. > See also: CLAUDE.md testing pitfalls. -`UploadEarlyEndpoint` constructor parameters (all optional beyond `files` and `database`): +`GlobalUploadEndpoints` constructor parameters (all optional beyond `files` and `database`): | Parameter | Default | Purpose | |---|---|---| @@ -171,7 +171,7 @@ data class Post( ) : HasId ``` -When `Post` is returned by an endpoint within the same server that contains `UploadEarlyEndpoint`, +When `Post` is returned by an endpoint within the same server that contains `GlobalUploadEndpoints`, `image` is automatically signed before it reaches the client. When a client submits a `Post` with `image` set to a `futureCallToken`, the serializer validates, resolves, and cleans up the token. @@ -281,5 +281,5 @@ external database is needed. [Media Processing](media.md). - **Validation** — annotate `ServerFile` fields with `@MimeType(…)` and register `AnnotationValidators.Files` to enforce file type and size limits at the model layer. -- **Cleanup** — `UploadEarlyEndpoint` includes a built-in `cleanupSchedule` that runs daily and +- **Cleanup** — `GlobalUploadEndpoints` includes a built-in `cleanupSchedule` that runs daily and removes expired upload records and their associated files. diff --git a/docs-guide/drafts/serialization.md b/docs-guide/drafts/serialization.md index 94323d286..3f32f46ae 100644 --- a/docs-guide/drafts/serialization.md +++ b/docs-guide/drafts/serialization.md @@ -150,7 +150,7 @@ object Server : ServerBuilder() { When your server includes sub-builders (via `include`), their `externalSerialization` and `internalSerialization` are merged with the root at `build()` time. -`UploadEarlyEndpoint` (see [ServerFile](#serverfile-serialization) below) uses this +`GlobalUploadEndpoints` (see [ServerFile](#serverfile-serialization) below) uses this mechanism to inject the `ExternalServerFileSerializer` contextual entry. ## Polymorphic and Sealed Types @@ -252,7 +252,7 @@ defers to whatever serializer is registered in the current `SerializersModule` f `ServerFile::class`. On the client side (where no contextual override is present), `DirectServerFileSerializer` kicks in — it reads and writes the raw URL string unchanged. -**On the server side**, `UploadEarlyEndpoint` overrides `externalSerialization` to +**On the server side**, `GlobalUploadEndpoints` overrides `externalSerialization` to inject `ExternalServerFileSerializer` as the contextual entry: ```kotlin @@ -264,7 +264,7 @@ override val externalSerialization: Runtime = Runtime.Cached } ``` -This means **any endpoint that shares a ServerBuilder tree with an `UploadEarlyEndpoint` +This means **any endpoint that shares a ServerBuilder tree with an `GlobalUploadEndpoints` gets the secure serializer automatically**. You do not register it manually. ### What ExternalServerFileSerializer Does @@ -299,16 +299,16 @@ recommended in production. request body. `ExternalServerFileSerializer.deserialize` validates the token and resolves it to the final internal URL. -> **Gotcha: one `UploadEarlyEndpoint` per server tree.** If you declare multiple +> **Gotcha: one `GlobalUploadEndpoints` per server tree.** If you declare multiple > instances in the same `ServerBuilder` tree they will both try to register a > contextual serializer for `ServerFile`, which causes a -> `ConflictingSerializerException` at startup. Declare it once and share the +> `ConflictingSerializerException` at startup. Declare it once and share the > reference. ## What's Next - **Files** — how to declare `ExternalFileSystem.Settings()`, wire a file system backend, - and configure `UploadEarlyEndpoint` for your server (see the files draft chapter). + and configure `GlobalUploadEndpoints` for your server (see the files draft chapter). - **Typed Endpoints** — typed endpoints call `registerBasicMediaTypeCoders()` and use `parse`/`toTypedData` automatically; you usually only need to read this chapter when working with raw `HttpHandler`s or custom wire formats. diff --git a/docs-guide/guide/project-structure.md b/docs-guide/guide/project-structure.md index 3209e9477..eef1de9f0 100644 --- a/docs-guide/guide/project-structure.md +++ b/docs-guide/guide/project-structure.md @@ -86,7 +86,7 @@ modules. These are what you reference in your dependency blocks. | Module | Type | What it provides | |---|---|---| -| `files` | JVM | `UploadEarlyEndpoint`, signed-URL generation, multi-backend file storage | +| `files` | JVM | `GlobalUploadEndpoints`, signed-URL generation, multi-backend file storage | | `files-shared` | KMP | `ServerFile`, `ServerFileWithMetadata` types | | `media` | JVM | Image processing (resize, crop, convert) via Scrimage | | `media-shared` | KMP | Media operation types | diff --git a/docs/files.md b/docs/files.md index ba5acff40..f4e24cd47 100644 --- a/docs/files.md +++ b/docs/files.md @@ -126,9 +126,9 @@ When a `ServerFile` is serialized out to a client, its URL is automatically sign file stays private as long as you only serialize references to it for people you want to be able to read it. Do not build a public file-sharing feature on top of this behavior by accident. -## The `UploadEarlyEndpoint` (recommended upload flow) +## The `GlobalUploadEndpoints` (recommended upload flow) -`UploadEarlyEndpoint` is an opinionated group of endpoints for the common "upload now, reference later" pattern. It +`GlobalUploadEndpoints` is an opinionated group of endpoints for the common "upload now, reference later" pattern. It lets a client upload a file before the request that actually uses it, without turning your file system into an open file-sharing service. @@ -177,15 +177,15 @@ Verifying up front also makes the subsequent request faster, since the scan has With an empty scanner list, uploads go straight to the ready location and are certified as already scanned. -### ⚠️ Only one `UploadEarlyEndpoint` per server +### ⚠️ Only one `GlobalUploadEndpoints` per server -`UploadEarlyEndpoint` registers a **contextual serializer for `ServerFile`** (via its `externalSerialization`) so -that upload tokens can be decoded as `ServerFile` values. If you instantiate `UploadEarlyEndpoint` more than once +`GlobalUploadEndpoints` registers a **contextual serializer for `ServerFile`** (via its `externalSerialization`) so +that upload tokens can be decoded as `ServerFile` values. If you instantiate `GlobalUploadEndpoints` more than once (for example, a separate instance created only for a test), the multiple instances register **conflicting `ServerFile` serializers**. This does not fail at compile time — it surfaces at runtime as serialization errors, typically appearing as `500 Internal Server Error` responses. -**Instantiate `UploadEarlyEndpoint` exactly once in your server definition and reference that single instance +**Instantiate `GlobalUploadEndpoints` exactly once in your server definition and reference that single instance everywhere, including from tests.** ## Available Backends diff --git a/docs/files/index.md b/docs/files/index.md index d91c67a6d..df934ec89 100644 --- a/docs/files/index.md +++ b/docs/files/index.md @@ -2,7 +2,8 @@ This package provides primitives and endpoints for working with user-provided files. -- files-shared: Common models used across platforms (UploadForNextRequest, UploadInformation). +- files-shared: Common models and the client interface used across platforms (UploadTarget, UnverifiedUpload, + ClientFileUploadEndpoints). - files: JVM server endpoints and helpers for serving files and implementing the early-upload workflow. Contents diff --git a/docs/migration-v4-to-v5.md b/docs/migration-v4-to-v5.md index f346a52df..b4f1c589f 100644 --- a/docs/migration-v4-to-v5.md +++ b/docs/migration-v4-to-v5.md @@ -190,7 +190,7 @@ See [WebSockets](websockets.md) for the current API. needs `context(runtime: ServerRuntime)`. - **`collection()` unresolved.** Replace `.collection()`/`.baseCollection()` with `.table()`/`.baseTable()`. - **Wrong `Instant` import.** Use `kotlin.time.Instant`, not `kotlinx.datetime.Instant`. -- **Duplicate `UploadEarlyEndpoint`.** Instantiate it exactly once; multiple instances register conflicting +- **Duplicate `GlobalUploadEndpoints`.** Instantiate it exactly once; multiple instances register conflicting `ServerFile` serializers and cause runtime 500s. See [File Systems](files.md). ## Client and KiteUI migration diff --git a/files-shared/build.gradle.kts b/files-shared/build.gradle.kts index 87860580a..a65866528 100644 --- a/files-shared/build.gradle.kts +++ b/files-shared/build.gradle.kts @@ -3,7 +3,6 @@ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { alias(libs.plugins.kotlin.multiplatform) - alias(libs.plugins.ksp) alias(libs.plugins.kotlin.serialization) alias(libs.plugins.androidKmpLibrary) alias(libs.plugins.dokka) @@ -54,29 +53,17 @@ kotlin { api(libs.services.files.client) api(libs.services.database.shared) } - kotlin { - srcDir(file("build/generated/ksp/common/commonMain/kotlin")) - } } val commonTest = getByName("commonTest") { dependencies { implementation(libs.kotlin.test) } - kotlin { - srcDir(file("build/generated/ksp/common/commonTest/kotlin")) - } } val jvmMain = getByName("jvmMain") {} val jvmTest = getByName("jvmTest") {} } } -dependencies { - configurations.filter { it.name.startsWith("ksp") && it.name != "ksp" }.forEach { - add(it.name, libs.services.database.processor) - } -} - dependencies { coreLibraryDesugaring(libs.androidDesugaring) } diff --git a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientFileUploadEndpoints.kt b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientFileUploadEndpoints.kt new file mode 100644 index 000000000..f0898f343 --- /dev/null +++ b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientFileUploadEndpoints.kt @@ -0,0 +1,59 @@ +package com.lightningkite.lightningserver.files + +import com.lightningkite.lightningserver.HttpMethod +import com.lightningkite.lightningserver.typed.Fetcher +import com.lightningkite.lightningserver.typed.LiveVersion +import com.lightningkite.services.files.DirectServerFileSerializer +import com.lightningkite.services.files.ServerFile +import kotlinx.serialization.builtins.serializer + +/** + * Client for a server's `UploadEndpoints` or `GlobalUploadEndpoints` module. + * + * To send a file: call [getFileUploadUrl], PUT the bytes to [UploadTarget.uploadUrl], pass + * [UploadTarget.token] to [verifyUpload], then put the [ServerFile] it returns wherever a request + * expects a file. + */ +@LiveVersion(LiveClientFileUploadEndpoints::class) +public interface ClientFileUploadEndpoints { + /** + * Returns a URL to PUT a file to, and a token that refers to that file. + * + * Both expire, usually within a day; upload and verify promptly. + */ + public suspend fun getFileUploadUrl(): UploadTarget + + /** + * Scans the file [upload] refers to, and returns it as a [ServerFile] a later request can use. + * + * It expires like the upload it came from, so use it promptly. + * + * Verify every upload, even on servers with no scanners: there the call is a cheap no-op. + */ + public suspend fun verifyUpload(upload: UnverifiedUploadToken): ServerFile + + @Suppress("DEPRECATION") + @Deprecated("Renamed to getFileUploadUrl.", ReplaceWith("getFileUploadUrl()")) + public suspend fun uploadFileForRequest(): UploadInformation = + getFileUploadUrl().let { UploadInformation(it.uploadUrl, it.token.raw) } + + @Deprecated("Use verifyUpload.", ReplaceWith("verifyUpload(UnverifiedUpload(input)).location")) + public suspend fun verifyUploadedFile(input: String): String = verifyUpload(UnverifiedUploadToken(input)).location +} + +public open class LiveClientFileUploadEndpoints( + public val fetcher: Fetcher, + public val subpath: String, +) : ClientFileUploadEndpoints { + override suspend fun getFileUploadUrl(): UploadTarget = + fetcher(subpath, HttpMethod.GET, Unit.serializer(), Unit, UploadTarget.serializer()) + + override suspend fun verifyUpload(upload: UnverifiedUploadToken): ServerFile = + fetcher("$subpath/verify", HttpMethod.POST, UnverifiedUploadToken.serializer(), upload, DirectServerFileSerializer) +} + +@Deprecated("Renamed", ReplaceWith("com.lightningkite.lightningserver.files.ClientFileUploadEndpoints")) +public typealias ClientUploadEarlyEndpoints = ClientFileUploadEndpoints + +@Deprecated("Renamed", ReplaceWith("com.lightningkite.lightningserver.files.LiveClientFileUploadEndpoints")) +public typealias LiveClientUploadEarlyEndpoints = LiveClientFileUploadEndpoints diff --git a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientUploadEarlyEndpoints.kt b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientUploadEarlyEndpoints.kt deleted file mode 100644 index a28ac504c..000000000 --- a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/ClientUploadEarlyEndpoints.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.lightningkite.lightningserver.files - -import com.lightningkite.lightningserver.typed.LiveVersion - -@LiveVersion(LiveClientUploadEarlyEndpoints::class) -public interface ClientUploadEarlyEndpoints { - /** - * Upload File for Request - * - * Upload a file to make a request later. Times out in around 10 minutes. - * - * **Auth Requirements:** No Requirements - * */ - public suspend fun uploadFileForRequest(): com.lightningkite.lightningserver.files.UploadInformation - - /** - * Verify uploaded file - * - * Checks out a file and moves it out of jail if it's safe. Makes for significantly faster subsequent requests. - * - * **Auth Requirements:** No Requirements - * */ - public suspend fun verifyUploadedFile(input: kotlin.String): kotlin.String -} diff --git a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/LiveClientModelRestEndpoints.kt b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/LiveClientModelRestEndpoints.kt deleted file mode 100644 index 0db954ca7..000000000 --- a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/LiveClientModelRestEndpoints.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.lightningkite.lightningserver.files - -import com.lightningkite.lightningserver.HttpMethod -import com.lightningkite.lightningserver.typed.Fetcher -import kotlinx.serialization.builtins.serializer - -public open class LiveClientUploadEarlyEndpoints( - public val fetcher: Fetcher, - public val subpath: String, -) : ClientUploadEarlyEndpoints { - override suspend fun uploadFileForRequest(): com.lightningkite.lightningserver.files.UploadInformation = - fetcher( - subpath, - HttpMethod.GET, - kotlin.Unit.serializer(), - kotlin.Unit, - com.lightningkite.lightningserver.files.UploadInformation.serializer() - ) - - override suspend fun verifyUploadedFile(input: kotlin.String): kotlin.String = - fetcher("$subpath/verify", HttpMethod.POST, kotlin.String.serializer(), input, kotlin.String.serializer()) -} diff --git a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/index.md b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/index.md index 3c0b15e6e..9f5dcfccd 100644 --- a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/index.md +++ b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/index.md @@ -4,13 +4,13 @@ This shared module provides simple models used by the files module and any clien Files -- models.kt — UploadForNextRequest and UploadInformation used to power the early-upload flow. -- ClientUploadEarlyEndpoints.kt — The client interface for the early-upload endpoints. -- LiveClientModelRestEndpoints.kt — LiveClientUploadEarlyEndpoints, the Fetcher-backed implementation of that - interface. +- models.kt — UploadTarget and UnverifiedUpload, which clients use in the upload flow, plus the deprecated + UploadInformation. +- ClientFileUploadEndpoints.kt — ClientFileUploadEndpoints, the client interface for the upload endpoints, and + LiveClientFileUploadEndpoints, its Fetcher-backed implementation. Overview -- UploadForNextRequest is stored server-side to track single-use prepared uploads and cleanup. -- UploadInformation is returned to clients when initiating an early upload; it contains the presigned PUT URL and a - token that can be sent later as a ServerFile in an API call. +- UploadTarget is returned to clients when starting an upload; it contains the presigned PUT URL and an + UnverifiedUpload token. Verifying that token returns a ServerFile to send in a later API call. +- The server-side tracking model, UploadForNextRequest, lives in the files module and never reaches clients. diff --git a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/models.kt b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/models.kt index bad8d6980..58329549b 100644 --- a/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/models.kt +++ b/files-shared/src/commonMain/kotlin/com/lightningkite/lightningserver/files/models.kt @@ -1,29 +1,30 @@ package com.lightningkite.lightningserver.files -import com.lightningkite.services.data.Queryable -import com.lightningkite.services.database.HasId import com.lightningkite.services.files.ServerFile +import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable -import kotlin.time.Instant -import kotlin.uuid.Uuid +import kotlin.jvm.JvmInline /** - * Record for tracking a prepared upload and guarding against reuse. - * Stored in the database to enable cleanup and single-use semantics. + * Where to upload a new file, returned by `getFileUploadUrl`. * - * **Do not expose this table through a REST or model endpoint.** Between preparation and verification - * [file] names a file in the upload jail, which has not been scanned. Serializing one hands a client a - * signed URL that [com.lightningkite.services.files.ExternalServerFileSerializer] will accept straight - * back as a usable `ServerFile`, bypassing scanning entirely. + * PUT the file's bytes to [uploadUrl], then pass [token] to `verifyUpload`. */ -@Queryable -public data class UploadForNextRequest( - override val _id: Uuid = Uuid.random(), - /** The file location (as a ServerFile URL) associated with this prepared upload. */ - val file: ServerFile, - /** Expiration time after which the upload is considered invalid/garbage. */ - val expires: Instant, -) : HasId +@Serializable +public data class UploadTarget( + val uploadUrl: String, + // Claude: keeps the wire format of UploadInformation, so old clients and other SDKs decode it unchanged + @SerialName("futureCallToken") val token: UnverifiedUploadToken, +) + +/** + * A file the client has been told to upload, which a later request can't use yet. + * + * Pass it to `verifyUpload` to get a [ServerFile] that requests can use. + */ +@Serializable +@JvmInline +public value class UnverifiedUploadToken(public val raw: String) /** * Information returned to a client when initiating an early upload. @@ -32,12 +33,9 @@ public data class UploadForNextRequest( * - [futureCallToken]: A token that can be serialized/deserialized as a ServerFile in a later request. * Typically time-limited; clients should use it promptly. */ +@Deprecated("Use UploadTarget, which types its token.", ReplaceWith("UploadTarget")) @Serializable public data class UploadInformation( val uploadUrl: String, val futureCallToken: String, ) - -/* -TODO(API): Consider a stronger type than raw String for futureCallToken to avoid confusion and accidental misuse. -*/ diff --git a/files/build.gradle.kts b/files/build.gradle.kts index cdf724d9e..334b55914 100644 --- a/files/build.gradle.kts +++ b/files/build.gradle.kts @@ -2,6 +2,7 @@ import com.lightningkite.deployhelpers.lkLibrary plugins { alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.ksp) alias(libs.plugins.kotlin.serialization) alias(libs.plugins.dokka) id("signing") @@ -14,6 +15,8 @@ dependencies { api(libs.services.database) api(libs.services.files) + ksp(libs.services.database.processor) + testImplementation(libs.kotlin.test) testImplementation(libs.kotlin.test.junit) } @@ -24,6 +27,9 @@ kotlin { optIn.add("kotlin.time.ExperimentalTime") optIn.add("kotlin.uuid.ExperimentalUuidApi") } + sourceSets.main { + kotlin.srcDir("build/generated/ksp/main/kotlin") + } } lkLibrary( diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt new file mode 100644 index 000000000..0cd0d11c0 --- /dev/null +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt @@ -0,0 +1,91 @@ +package com.lightningkite.lightningserver.files + +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.auth.noAuth +import com.lightningkite.lightningserver.definition.* +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.http.get +import com.lightningkite.lightningserver.http.post +import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.typed.ApiHttpHandler +import com.lightningkite.lightningserver.typed.explicitApiHttpHandler +import com.lightningkite.lightningserver.typed.sdk.* +import com.lightningkite.services.database.* +import com.lightningkite.services.files.* +import kotlin.time.Duration +import kotlin.time.Duration.Companion.days + +@Deprecated("Renamed to better reflect its purpose", ReplaceWith("GlobalUploadEndpoints", "com.lightningkite.lightningserver.files.GlobalUploadEndpoints")) +public typealias UploadEarlyEndpoint = GlobalUploadEndpoints + +/** + * Provides a single endpoint pair for early file upload, storing every file at the root of [filePath]. + * + * See [UploadBasis] for the flow and its gotchas. To give each feature its own folder and permission + * check instead, include an [UploadBasis] and declare a [UploadEndpoints] per feature. + */ +public class GlobalUploadEndpoints( + public val files: Runtime, + public val database: Runtime, + public val fileScanner: Runtime>, + public val jailFilePath: String = "upload-jail", + public val filePath: String = "uploaded", + public val expiration: Duration = 1.days, + public val authOptions: AuthRequirement<*> = noAuth, + public val foreignUrlHandling: ForeignUrlHandling = ForeignUrlHandling.ERROR, +) : ServerBuilder() { + init { + sdkSettings.clientInterface = ClientFileUploadEndpoints::class.info() + } + + public val basis: UploadBasis = path include UploadBasis( + files = files, + database = database, + fileScanner = fileScanner, + jailFilePath = jailFilePath, + filePath = filePath, + expiration = expiration, + foreignUrlHandling = foreignUrlHandling, + ) + + /** Mints and checks the tokens this endpoint hands to clients. */ + public val tokens: Runtime get() = basis.tokens + + /** Contextual serializer used for ServerFile values; see [UploadBasis.serializer]. */ + public val serializer: Runtime get() = basis.serializer + + /** + * GET handler to prepare an upload. Returns an [UploadTarget] containing the presigned upload URL and + * the [UnverifiedUploadToken] to pass to [verify]. + */ + public val endpoint: ApiHttpHandler?, Unit, UploadTarget> = + path.get bind ApiHttpHandler( + auth = authOptions, + summary = "Upload File for Request", + functionName = "getFileUploadUrl", + description = "Upload a file to make a request later. Times out in $expiration.", + errorCases = listOf(), + implementation = { _: Unit -> basis.prepare(folder = "") } + ) + + /** + * POST handler to verify a previously uploaded file, scanning it and promoting it to the ready + * location. Returns a [ServerFile] to send in a later request. + */ + public val verify: ApiHttpHandler?, UnverifiedUploadToken, ServerFile> = + path.path("verify").post bind explicitApiHttpHandler( + auth = authOptions, + inputType = UnverifiedUploadToken.serializer(), + // Claude: the location is the scanned token; the contextual serializer would send a signed URL instead, + // which the server would never claim, so cleanup would delete the file. + outputType = DirectServerFileSerializer, + summary = "Verify uploaded file", + functionName = "verifyUpload", + description = "Scans an uploaded file and moves it out of jail so later requests can use it.", + errorCases = listOf(basis.fileScanFailedError), + implementation = { upload: UnverifiedUploadToken -> basis.verify(folder = "", upload) } + ) + + /** Daily cleanup of expired uploads; see [UploadBasis.cleanupSchedule]. */ + public val cleanupSchedule: ScheduledTask get() = basis.cleanupSchedule +} diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt new file mode 100644 index 000000000..87138a309 --- /dev/null +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt @@ -0,0 +1,278 @@ +package com.lightningkite.lightningserver.files + +import com.lightningkite.lightningserver.BadRequestException +import com.lightningkite.lightningserver.LSError +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.auth.noAuth +import com.lightningkite.lightningserver.definition.* +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.encryption.Signer +import com.lightningkite.lightningserver.encryption.signerBlocking +import com.lightningkite.lightningserver.http.HttpStatus +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.runtime.engine +import com.lightningkite.lightningserver.runtime.now +import com.lightningkite.lightningserver.typed.registerTable +import com.lightningkite.services.database.* +import com.lightningkite.services.files.* +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.modules.SerializersModule +import kotlin.time.Duration +import kotlin.time.Duration.Companion.days +import kotlin.uuid.Uuid + +/** + * Holds what every early upload shares: the tokens, the ServerFile serializer, the tracking table and + * its cleanup. It declares no endpoints of its own; [UploadEndpoints] modules declare those. + * + * Include it once, then give each place that accepts uploads its own [UploadEndpoints] with [uploadEndpoints]: + * ```kotlin + * val uploads = path.path("uploads") include UploadBasis(files, database, fileScanner = { listOf() }) + * val avatarUpload = path.path("users").path("avatar-upload") include + * uploads.uploadEndpoints("users/avatars", UserAuth.require()) + * ``` + * + * Flow: + * - Client calls a [UploadEndpoints.upload] to obtain an [UploadTarget]: an upload URL and an [UnverifiedUploadToken]. + * - Client uploads the file (PUT) to uploadUrl. + * - Client calls that module's [UploadEndpoints.verify], which scans the file and returns a token + * naming the scanned copy. + * - Client includes that token as a serialized ServerFile in a later request. + * + * Gotchas: + * - When file scanners are configured, verify is **required**, not an optimization: a token for an + * unscanned upload is rejected during deserialization. With no scanners configured there is nothing + * to scan, so the first token is already usable and verify is a no-op. + * - The file system must sign the references it issues whenever scanners are configured, or a client + * can simply name the jail file instead of verifying it; this is checked, and fails loudly. + * - Turning scanning on is not retroactive. Tokens minted while no scanners were configured name + * files the client uploaded straight to the ready location, and stay usable until they expire + * ([expiration]), so scanning only covers everything once the outstanding ones have aged out. + * - Upload tokens are time-limited by [expiration]. Ensure your client uses them promptly. + * - This installs the contextual ServerFile serializer, so a server should include only one basis. + */ +public class UploadBasis( + public val files: Runtime, + public val database: Runtime, + public val fileScanner: Runtime>, + public val jailFilePath: String = "upload-jail", + public val filePath: String = "uploaded", + public val expiration: Duration = 1.days, + public val foreignUrlHandling: ForeignUrlHandling = ForeignUrlHandling.ERROR, +) : ServerBuilder() { + + // Defines the table, registers it, and creates its once-per-deploy prepare task. + private val uploadForNextRequestTable = database.registerTable("UploadForNextRequest") + + /** + * The file system, with the precondition the jail/ready split depends on checked once before + * anything uses it. + * + * Everything here resolves the file system through this rather than through [files], so no entry + * point can reach storage without the check having run. + */ + private val checkedFiles: Runtime = Runtime.Cached { + files().also { + require(fileScanner().isEmpty() || it.referencesAreUnforgeable) { + "File scanning cannot be enforced on file system '${it.name}': it does not sign the " + + "references it issues, so a client can name the unscanned jail file directly " + + "rather than going through the verify endpoint. Give it a signedUrlDuration, or " + + "configure no scanners." + } + } + } + + /** Where a client's presigned upload lands while it is still untrusted. */ + private val jail: Runtime = Runtime.Cached { checkedFiles().root.then(jailFilePath) } + + /** + * Where scanned files live. Nothing hands out a presigned upload URL for this location while + * scanners are configured, which is what lets verify freeze a file's bytes by copying here. + */ + private val ready: Runtime = Runtime.Cached { checkedFiles().root.then(filePath) } + + private val uploadSigner: Runtime = secretBasis.signerBlocking("upload-files") + + /** Mints and checks the tokens handed to clients. */ + public val tokens: Runtime = Runtime.Cached { UploadTokens(uploadSigner(), engine.clock) } + + /** + * Contextual serializer used for ServerFile values. + * + * It resolves this basis's tokens and nothing else: it holds no scanners and cannot name the + * jail location, so it has no way to turn an unscanned upload into a usable ServerFile. + * + * That only closes the token path. A client can still submit a plain URL, which falls through to + * [ExternalFileSystem.parseExternalUrl] - safe while the file system signs its URLs, and not safe + * when it does not, since an unsigned backend accepts any path a client cares to name, jail + * included. Configure the file system with signing on whenever scanners are in use. + */ + public val serializer: Runtime = Runtime.Cached { + val ready = ready() + val tokens = tokens() + val table = uploadForNextRequestTable() + ExternalServerFileSerializer( + fileSystems = listOf(checkedFiles()), + foreignUrlHandling = foreignUrlHandling, + resolveUpload = { raw -> + when (val token = tokens.parseOrNull(raw)) { + null -> null + + is UploadToken.Unscanned -> throw IllegalArgumentException( + "This file has not been scanned yet. Send its token to the verify endpoint and use what that returns." + ) + + is UploadToken.Scanned -> ready.then(token.key).also { file -> + // The row exists only to keep the file alive until something claims it; now that + // something has, drop it so the cleanup task doesn't delete a file in use. + runBlocking { + table.deleteManyIgnoringOld(Condition { it.file eq file.serverFile }) + } + } + } + }, + ) + } + + /** + * Registers [serializer] as the contextual serializer for ServerFile so that endpoints and tests can + * encode/decode values without having to pass a serializer explicitly. + */ + override val externalSerialization: Runtime = Runtime.Cached { + SerializersModule { + contextual(ServerFile::class, serializer()) + } + } + + internal val fileScanFailedError = LSError( + http = HttpStatus.BadRequest.code, + detail = "file-scan-failed", + message = "The uploaded file was rejected by a file scanner.", + ) + + // Claude: an empty folder keeps keys at the root, which is where UploadEarlyEndpoint has always put them. + private fun newKey(folder: String): String = + if (folder.isEmpty()) "${Uuid.random()}.file" else "$folder/${Uuid.random()}.file" + + /** Returns an upload URL and token for a new file under [folder]. */ + context(_: ServerRuntime) + internal suspend fun prepare(folder: String): UploadTarget { + val key = newKey(folder) + // With no scanners there is nothing to promote, so the client uploads straight to the + // ready location and its token is born scanned. + val nothingToScan = fileScanner().isEmpty() + val target = (if (nothingToScan) ready() else jail()).then(key) + uploadForNextRequestTable().insertOne( + UploadForNextRequest(expires = now().plus(expiration), file = target.serverFile) + ) + return UploadTarget( + uploadUrl = target.uploadUrl(expiration), + token = UnverifiedUploadToken( + tokens().sign( + if (nothingToScan) UploadToken.Scanned(key) else UploadToken.Unscanned(key), + expiration, + ) + ), + ) + } + + /** + * Scans the file [upload] names and promotes it to the ready location, keeping it in [folder]. + * + * Returns a [ServerFile] whose location is the scanned token, not a URL, so it must be encoded with + * [DirectServerFileSerializer]; the contextual serializer resolves it only when a later request sends it back. + */ + context(_: ServerRuntime) + internal suspend fun verify(folder: String, upload: UnverifiedUploadToken): ServerFile { + val parsed = tokens().parseOrNull(upload.raw) + ?: throw IllegalArgumentException("Not an upload token.") + if (parsed.key.substringBeforeLast('/', "") != folder) + throw IllegalArgumentException("This token was issued for a different upload endpoint.") + return when (parsed) { + // Already verified. Returning the token unchanged makes a retry safe. + is UploadToken.Scanned -> ServerFile(upload.raw) + + is UploadToken.Unscanned -> { + // Promote under a fresh server-chosen key rather than reusing the client's. The + // jail stays writable through the presigned upload URL for the whole expiration + // window, so a client that re-uploads and verifies again would otherwise + // overwrite - or, when the rescan fails, delete - a file it had already had + // certified and handed out. Distinct keys make every certified file immutable. + val promotedKey = newKey(folder) + val safe = ready().then(promotedKey) + + // Record the file before creating it. The cleanup task collects by row, so + // inserting first means a crash anywhere below leaves a tracked file rather + // than an orphan nothing will ever delete. + uploadForNextRequestTable().insertOne( + UploadForNextRequest(expires = now().plus(expiration), file = safe.serverFile) + ) + + // Copy first, then scan the copy - never scan the jail file in place, because + // the client could swap the bytes afterwards through that same upload URL. + // Nothing can write to the ready location, so once copied the bytes are frozen + // and the scan below covers exactly what will later be served. + jail().then(parsed.key).copyTo(safe) + try { + fileScanner().scan(safe) + } catch (cancellation: CancellationException) { + // The cleanup below is suspend work, which fails immediately in a cancelled + // scope and would only bury the cancellation under a suppressed exception. + // The row inserted above already guarantees the file gets collected. + throw cancellation + } catch (e: Exception) { + // Nothing can reference an unscanned ready file - only the line below mints + // a Scanned token, and promotedKey is unguessable - so this is prompt + // hygiene rather than the thing keeping us safe. Suppress rather than mask: + // the scan failure is the error worth reporting. + try { + safe.delete() + } catch (cleanupFailure: Exception) { + e.addSuppressed(cleanupFailure) + } + // A scanner rejecting the file is the client's fault, not ours. + if (e is FileScanException) throw BadRequestException( + detail = fileScanFailedError.detail, + message = e.message ?: fileScanFailedError.message, + cause = e, + ) + throw e + } + + // The jail copy is deliberately left in place: its own row expires and the + // cleanup task collects it, and leaving it lets a client that lost our response + // retry without re-uploading. + ServerFile(tokens().sign(UploadToken.Scanned(promotedKey), expiration)) + } + } + } + + /** + * Daily cleanup of expired uploads. Removes database entries and attempts to delete the associated file. + */ + public val cleanupSchedule: ScheduledTask = path.path("cleanupUploads") bind ScheduledTask(frequency = 1.days) { + uploadForNextRequestTable().deleteMany(Condition { it.expires lt now() }).forEach { + try { + it.file.externalFile.delete() + } catch (e: Exception) { + e.printStackTrace() + } + } + } + + /** + * Returns a [UploadEndpoints] module that stores uploads under [folder] using this basis. + * + * The module still has to be included at a path: + * ```kotlin + * val avatarUpload = path.path("avatar-upload") include Server.uploads.uploadEndpoints("users/avatars", UserAuth.require()) + * ``` + * + * [auth] defaults to [noAuth], which lets anyone upload; pass a requirement unless that is intended. + * + * @throws IllegalArgumentException if [folder] is blank or starts or ends with `/`. + */ + public fun uploadEndpoints(folder: String, auth: AuthRequirement<*> = noAuth): UploadEndpoints = + UploadEndpoints(this, folder, auth) +} diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpoints.kt deleted file mode 100644 index 976b253aa..000000000 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpoints.kt +++ /dev/null @@ -1,273 +0,0 @@ -package com.lightningkite.lightningserver.files - -import com.lightningkite.lightningserver.BadRequestException -import com.lightningkite.lightningserver.LSError -import com.lightningkite.lightningserver.auth.AuthRequirement -import com.lightningkite.lightningserver.auth.noAuth -import com.lightningkite.lightningserver.definition.* -import com.lightningkite.lightningserver.definition.builder.ServerBuilder -import com.lightningkite.lightningserver.encryption.Signer -import com.lightningkite.lightningserver.encryption.signerBlocking -import com.lightningkite.lightningserver.http.HttpStatus -import com.lightningkite.lightningserver.http.get -import com.lightningkite.lightningserver.http.post -import com.lightningkite.lightningserver.pathing.PathSpec0 -import com.lightningkite.lightningserver.runtime.now -import com.lightningkite.lightningserver.runtime.engine -import com.lightningkite.lightningserver.typed.ApiHttpHandler -import com.lightningkite.lightningserver.typed.registerTable -import com.lightningkite.lightningserver.typed.sdk.* -import com.lightningkite.services.database.* -import com.lightningkite.services.files.* -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.runBlocking -import kotlinx.serialization.modules.SerializersModule -import kotlin.time.Duration -import kotlin.time.Duration.Companion.days -import kotlin.uuid.Uuid - -/** - * Provides an opinionated set of endpoints for client-side early file upload and later usage within API calls. - * - * Flow: - * - Client calls [endpoint] to obtain an uploadUrl and a futureCallToken. - * - Client uploads the file (PUT) to uploadUrl. - * - Client calls [verify], which scans the file and returns a token naming the scanned copy. - * - Client includes that token as a serialized ServerFile in a later request. - * - * Gotchas: - * - When file scanners are configured, [verify] is **required**, not an optimization: a token for an - * unscanned upload is rejected during deserialization. With no scanners configured there is nothing - * to scan, so the first token is already usable and [verify] is a no-op. - * - The file system must sign the references it issues whenever scanners are configured, or a client - * can simply name the jail file instead of verifying it; this is checked, and fails loudly. - * - Turning scanning on is not retroactive. Tokens minted while no scanners were configured name - * files the client uploaded straight to the ready location, and stay usable until they expire - * ([expiration]), so scanning only covers everything once the outstanding ones have aged out. - * - The futureCallToken is time-limited by [expiration]. Ensure your client uses it promptly. - */ -public class UploadEarlyEndpoint( - public val files: Runtime, - public val database: Runtime, - public val fileScanner: Runtime>, - public val jailFilePath: String = "upload-jail", - public val filePath: String = "uploaded", - public val expiration: Duration = 1.days, - public val authOptions: AuthRequirement<*> = noAuth, - public val foreignUrlHandling: ForeignUrlHandling = ForeignUrlHandling.ERROR, -) : ServerBuilder() { - init { - sdkSettings.clientInterface = ClientUploadEarlyEndpoints::class.info() - } - - // Defines the table, registers it, and creates its once-per-deploy prepare task. - private val uploadForNextRequestTable = database.registerTable("UploadForNextRequest") - - /** - * The file system, with the precondition the jail/ready split depends on checked once before - * anything uses it. - * - * Everything here resolves the file system through this rather than through [files], so no entry - * point can reach storage without the check having run. - */ - private val checkedFiles: Runtime = Runtime.Cached { - files().also { - require(fileScanner().isEmpty() || it.referencesAreUnforgeable) { - "File scanning cannot be enforced on file system '${it.name}': it does not sign the " + - "references it issues, so a client can name the unscanned jail file directly " + - "rather than going through the verify endpoint. Give it a signedUrlDuration, or " + - "configure no scanners." - } - } - } - - /** Where a client's presigned upload lands while it is still untrusted. */ - private val jail: Runtime = Runtime.Cached { checkedFiles().root.then(jailFilePath) } - - /** - * Where scanned files live. Nothing hands out a presigned upload URL for this location while - * scanners are configured, which is what lets [verify] freeze a file's bytes by copying here. - */ - private val ready: Runtime = Runtime.Cached { checkedFiles().root.then(filePath) } - - private val uploadSigner: Runtime = secretBasis.signerBlocking("upload-files") - - /** Mints and checks the tokens this endpoint hands to clients. */ - public val tokens: Runtime = Runtime.Cached { UploadTokens(uploadSigner(), engine.clock) } - - /** - * Contextual serializer used for ServerFile values. - * - * It resolves this endpoint's tokens and nothing else: it holds no scanners and cannot name the - * jail location, so it has no way to turn an unscanned upload into a usable ServerFile. - * - * That only closes the token path. A client can still submit a plain URL, which falls through to - * [ExternalFileSystem.parseExternalUrl] - safe while the file system signs its URLs, and not safe - * when it does not, since an unsigned backend accepts any path a client cares to name, jail - * included. Configure this endpoint's file system with signing on whenever scanners are in use. - */ - public val serializer: Runtime = Runtime.Cached { - val ready = ready() - val tokens = tokens() - val table = uploadForNextRequestTable() - ExternalServerFileSerializer( - fileSystems = listOf(checkedFiles()), - foreignUrlHandling = foreignUrlHandling, - resolveUpload = { raw -> - when (val token = tokens.parseOrNull(raw)) { - null -> null - - is UploadToken.Unscanned -> throw IllegalArgumentException( - "This file has not been scanned yet. Send its token to the verify endpoint and use what that returns." - ) - - is UploadToken.Scanned -> ready.then(token.key).also { file -> - // The row exists only to keep the file alive until something claims it; now that - // something has, drop it so the cleanup task doesn't delete a file in use. - runBlocking { - table.deleteManyIgnoringOld(Condition { it.file eq file.serverFile }) - } - } - } - }, - ) - } - - /** - * Registers [serializer] as the contextual serializer for ServerFile so that endpoints and tests can - * encode/decode values without having to pass a serializer explicitly. - */ - override val externalSerialization: Runtime = Runtime.Cached { - SerializersModule { - contextual(ServerFile::class, serializer()) - } - } - - /** - * GET handler to prepare an upload. Returns [UploadInformation] containing the presigned upload URL and - * the token to reference the file in a subsequent call. - */ - public val endpoint: ApiHttpHandler?, Unit, UploadInformation> = - path.get bind ApiHttpHandler( - auth = authOptions, - summary = "Upload File for Request", - description = "Upload a file to make a request later. Times out in $expiration.", - errorCases = listOf(), - implementation = { _: Unit -> - val key = "${Uuid.random()}.file" - // With no scanners there is nothing to promote, so the client uploads straight to the - // ready location and its token is born scanned. - val nothingToScan = fileScanner().isEmpty() - val target = (if (nothingToScan) ready() else jail()).then(key) - uploadForNextRequestTable().insertOne( - UploadForNextRequest(expires = now().plus(expiration), file = target.serverFile) - ) - UploadInformation( - uploadUrl = target.uploadUrl(expiration), - futureCallToken = tokens().sign( - if (nothingToScan) UploadToken.Scanned(key) else UploadToken.Unscanned(key), - expiration, - ) - ) - } - ) - - private val fileScanFailedError = LSError( - http = HttpStatus.BadRequest.code, - detail = "file-scan-failed", - message = "The uploaded file was rejected by a file scanner.", - ) - - /** - * POST handler to verify a previously uploaded file, scanning it and promoting it to the ready - * location. Returns a token that can be decoded as a ServerFile in a later request. - */ - public val verify: ApiHttpHandler?, String, String> = - path.path("verify").post bind ApiHttpHandler( - auth = authOptions, - summary = "Verify uploaded file", - description = "Scans an uploaded file and moves it out of jail so later requests can use it.", - errorCases = listOf(fileScanFailedError), - implementation = { token: String -> - val parsed = tokens().parseOrNull(token) - ?: throw IllegalArgumentException("Not an upload token.") - when (parsed) { - // Already verified. Returning the token unchanged makes a retry safe. - is UploadToken.Scanned -> token - - is UploadToken.Unscanned -> { - // Promote under a fresh server-chosen key rather than reusing the client's. The - // jail stays writable through the presigned upload URL for the whole expiration - // window, so a client that re-uploads and verifies again would otherwise - // overwrite - or, when the rescan fails, delete - a file it had already had - // certified and handed out. Distinct keys make every certified file immutable. - val promotedKey = "${Uuid.random()}.file" - val safe = ready().then(promotedKey) - - // Record the file before creating it. The cleanup task collects by row, so - // inserting first means a crash anywhere below leaves a tracked file rather - // than an orphan nothing will ever delete. - uploadForNextRequestTable().insertOne( - UploadForNextRequest(expires = now().plus(expiration), file = safe.serverFile) - ) - - // Copy first, then scan the copy - never scan the jail file in place, because - // the client could swap the bytes afterwards through that same upload URL. - // Nothing can write to the ready location, so once copied the bytes are frozen - // and the scan below covers exactly what will later be served. - jail().then(parsed.key).copyTo(safe) - try { - fileScanner().scan(safe) - } catch (cancellation: CancellationException) { - // The cleanup below is suspend work, which fails immediately in a cancelled - // scope and would only bury the cancellation under a suppressed exception. - // The row inserted above already guarantees the file gets collected. - throw cancellation - } catch (e: Exception) { - // Nothing can reference an unscanned ready file - only the line below mints - // a Scanned token, and promotedKey is unguessable - so this is prompt - // hygiene rather than the thing keeping us safe. Suppress rather than mask: - // the scan failure is the error worth reporting. - try { - safe.delete() - } catch (cleanupFailure: Exception) { - e.addSuppressed(cleanupFailure) - } - // A scanner rejecting the file is the client's fault, not ours. - if (e is FileScanException) throw BadRequestException( - detail = fileScanFailedError.detail, - message = e.message ?: fileScanFailedError.message, - cause = e, - ) - throw e - } - - // The jail copy is deliberately left in place: its own row expires and the - // cleanup task collects it, and leaving it lets a client that lost our response - // retry without re-uploading. - tokens().sign(UploadToken.Scanned(promotedKey), expiration) - } - } - } - ) - - /** - * Daily cleanup of expired uploads. Removes database entries and attempts to delete the associated file. - */ - public val cleanupSchedule: ScheduledTask = path.path("cleanupUploads") bind ScheduledTask(frequency = 1.days) { - uploadForNextRequestTable().deleteMany(Condition { it.expires lt now() }).forEach { - try { - it.file.externalFile.delete() - } catch (e: Exception) { - e.printStackTrace() - } - } - } - - /* - TODO(API): - - Consider making expiration configurable per-request to support large uploads with client-chosen windows (within limits). - - Provide hooks for custom quarantine/jail policies beyond simple FileScanner list. - - Expose a type-safe wrapper for futureCallToken instead of a raw String on the wire. - */ -} diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt new file mode 100644 index 000000000..f85512162 --- /dev/null +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt @@ -0,0 +1,74 @@ +package com.lightningkite.lightningserver.files + +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.http.get +import com.lightningkite.lightningserver.http.post +import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.typed.ApiHttpHandler +import com.lightningkite.lightningserver.typed.explicitApiHttpHandler +import com.lightningkite.lightningserver.typed.sdk.* +import com.lightningkite.lightningserver.typed.sdk.SdkModule.Companion.defaultInfo +import com.lightningkite.services.database.HasId +import com.lightningkite.services.files.DirectServerFileSerializer +import com.lightningkite.services.files.ServerFile + +/** + * Upload endpoints that store files under [folder], for callers passing [authOptions]. + * + * Tokens, the ServerFile serializer and cleanup come from the shared [basis], so a file uploaded here + * is used in later requests like any other upload. Declare one of these wherever a feature accepts + * uploads, and put the feature's permission check in [authOptions], e.g. + * `UserAuth.require { it.fetch().canUploadDocuments }`. + * + * @param folder The path under the basis's jail and ready locations, such as `"users/avatars"`. + */ +public class UploadEndpoints( + public val basis: UploadBasis, + public val folder: String, + public val authOptions: AuthRequirement<*>, +) : ServerBuilder() { + init { + require(folder.isNotBlank() && !folder.startsWith('/') && !folder.endsWith('/')) { + "Upload folder must be a relative path without leading or trailing slashes; got '$folder'." + } + sdkSettings.clientInterface = ClientFileUploadEndpoints::class.info() + sdkSettings.defaultInfo = SdkModule.Info( + interfaceName = "FileUploadEndpoints", + valueName = "files" + ) + } + + /** + * GET handler to prepare an upload. Returns an [UploadTarget] containing the presigned upload URL and + * the [UnverifiedUploadToken] to pass to [verify]. + */ + public val upload: ApiHttpHandler?, Unit, UploadTarget> = + path.get bind ApiHttpHandler( + auth = authOptions, + summary = "Get File Upload URL", + functionName = "getFileUploadUrl", + description = "Returns a URL to PUT a file to, and a token that refers to that file. Send the token to verify, " + + "then use the result as a file in a later request. Both expire in ${basis.expiration}.", + errorCases = listOf(), + implementation = { _: Unit -> basis.prepare(folder) } + ) + + /** + * POST handler to verify a file uploaded through [upload], scanning it and promoting it to the ready + * location. Returns a [ServerFile] to send in a later request. + */ + public val verify: ApiHttpHandler?, UnverifiedUploadToken, ServerFile> = + path.path("verify").post bind explicitApiHttpHandler( + auth = authOptions, + inputType = UnverifiedUploadToken.serializer(), + // Claude: the location is the scanned token; the contextual serializer would send a signed URL instead, + // which the server would never claim, so cleanup would delete the file. + outputType = DirectServerFileSerializer, + summary = "Verify uploaded file", + functionName = "verifyUpload", + description = "Scans an uploaded file and moves it out of jail so later requests can use it.", + errorCases = listOf(basis.fileScanFailedError), + implementation = { upload: UnverifiedUploadToken -> basis.verify(folder, upload) } + ) +} diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt new file mode 100644 index 000000000..95ffefb6e --- /dev/null +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt @@ -0,0 +1,25 @@ +package com.lightningkite.lightningserver.files + +import com.lightningkite.services.data.Queryable +import com.lightningkite.services.database.HasId +import com.lightningkite.services.files.ServerFile +import kotlin.time.Instant +import kotlin.uuid.Uuid + +/** + * Record for tracking a prepared upload and guarding against reuse. + * Stored in the database to enable cleanup and single-use semantics. + * + * **Do not expose this table through a REST or model endpoint.** Between preparation and verification + * [file] names a file in the upload jail, which has not been scanned. Serializing one hands a client a + * signed URL that [com.lightningkite.services.files.ExternalServerFileSerializer] will accept straight + * back as a usable `ServerFile`, bypassing scanning entirely. + */ +@Queryable +public data class UploadForNextRequest( + override val _id: Uuid = Uuid.random(), + /** The file location (as a ServerFile URL) associated with this prepared upload. */ + val file: ServerFile, + /** Expiration time after which the upload is considered invalid/garbage. */ + val expires: Instant, +) : HasId diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadToken.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadToken.kt index 8e47f06a3..0066a737e 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadToken.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadToken.kt @@ -9,7 +9,7 @@ import kotlin.time.Duration import kotlin.time.Instant /** - * A reference to a file uploaded through [UploadEarlyEndpoint]. + * A reference to a file uploaded through [GlobalUploadEndpoints]. * * Which variant a token carries is the whole of the upload flow's safety: only [Scanned] names a file * that may be used, and only the verify endpoint mints one. @@ -36,14 +36,14 @@ public sealed interface UploadToken { } /** - * Mints and checks the tokens [UploadEarlyEndpoint] hands to clients. + * Mints and checks the tokens [GlobalUploadEndpoints] hands to clients. * * A token is `?useUntil=&token=`, signed with a key derived from * the server's secret basis. Clients treat it as opaque; the signature is what stops one from naming a * file it was not given, or from promoting its own upload to [UploadToken.Scanned]. * * @param signer Signs and verifies tokens. Derive it from the secret basis rather than supplying a - * bare key - see [UploadEarlyEndpoint]. + * bare key - see [GlobalUploadEndpoints]. * @param clock Source of truth for expiration checks. */ public class UploadTokens( diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpointsTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpointsTest.kt index 9f055ce06..8127fc560 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpointsTest.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpointsTest.kt @@ -26,7 +26,7 @@ class FileSystemEndpointsTest { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) val served = path.path("files") include FileSystemEndpoints(files) - val uploadEarly = path.path("upload") include UploadEarlyEndpoint( + val uploadEarly = path.path("upload") include GlobalUploadEndpoints( files = files, database = database, fileScanner = { listOf() } diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/FilesModuleReviewTests.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/FilesModuleReviewTests.kt index c889526f3..f6c098c52 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/FilesModuleReviewTests.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/FilesModuleReviewTests.kt @@ -22,7 +22,7 @@ class FilesModuleReviewTests { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) val served = path.path("files") include FileSystemEndpoints(files) - val uploadEarly = path.path("upload") include UploadEarlyEndpoint( + val uploadEarly = path.path("upload") include GlobalUploadEndpoints( files = files, database = database, fileScanner = { listOf() } diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt new file mode 100644 index 000000000..303757ac0 --- /dev/null +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt @@ -0,0 +1,135 @@ +package com.lightningkite.lightningserver.files + +import com.lightningkite.lightningserver.auth.noAuth +import com.lightningkite.lightningserver.definition.Runtime +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.runtime.Engine +import com.lightningkite.lightningserver.runtime.test.testBlocking +import com.lightningkite.lightningserver.serialization.registerBasicMediaTypeCoders +import com.lightningkite.lightningserver.settings.set +import com.lightningkite.lightningserver.typed.sdk.FetcherSdk +import com.lightningkite.lightningserver.typed.sdk.SDK.writeUsingDefaultSettings +import com.lightningkite.lightningserver.typed.test +import com.lightningkite.lightningserver.http.HttpHandler +import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.runtime.test.test +import com.lightningkite.services.kfile.KFile +import com.lightningkite.services.SettingContext +import com.lightningkite.services.data.HealthStatus +import com.lightningkite.services.data.MediaType +import com.lightningkite.services.data.TypedData +import com.lightningkite.services.database.Database +import com.lightningkite.services.files.* +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.modules.serializersModuleOf +import kotlin.test.* +import kotlin.uuid.Uuid + +private class AcceptingScanner(override val context: SettingContext) : FileScanner { + override val name: String = "accepting-scanner" + override suspend fun scan(file: ExternalFile) {} + override suspend fun healthCheck(): HealthStatus = HealthStatus(HealthStatus.Level.OK) +} + +class PathedUploadEndpointsTest { + + object Server : ServerBuilder() { + val files = setting("files", ExternalFileSystem.Settings()) + val database = setting("database", Database.Settings()) + val uploads = path.path("uploads") include UploadBasis( + files = files, + database = database, + fileScanner = Runtime { listOf(AcceptingScanner(contextOf())) }, + ) + val avatars = path.path("avatars").path("upload") include UploadEndpoints(uploads, "users/avatars", noAuth) + val documents = path.path("documents").path("upload") include UploadEndpoints(uploads, "documents", noAuth) + + init { + registerBasicMediaTypeCoders() + } + } + + @Test + fun uploadsLandInTheirFolder(): Unit = Server.testBlocking(settings = { + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + val prepare = avatars.upload.test(null, Unit) + assertTrue(prepare.uploadUrl.contains("upload-jail/users/avatars/"), "Upload should target the folder in jail: ${prepare.uploadUrl}") + val token = assertIs(uploads.tokens().parseOrNull(prepare.token.raw)) + assertTrue(token.key.startsWith("users/avatars/")) + } + + @Test + fun verifyKeepsTheFolderAndTheResultIsUsable(): Unit = Server.testBlocking(settings = { + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + val prepare = avatars.upload.test(null, Unit) + val key = uploads.tokens().parseOrNull(prepare.token.raw)!!.key + files().root.then("upload-jail").then(key).put(TypedData.text("hello", MediaType.Text.Plain)) + + val verified = avatars.verify.test(null, prepare.token) + + val promoted = assertIs(uploads.tokens().parseOrNull(verified.location)).key + assertTrue(promoted.startsWith("users/avatars/"), "Promotion must keep the folder: $promoted") + assertNotEquals(key, promoted) + val ser = uploads.serializer() + val resolved = Json { serializersModule = serializersModuleOf(ser) }.decodeFromJsonElement(ser, JsonPrimitive(verified.location)) + assertEquals("hello", resolved.externalFile.get()!!.text()) + } + + @Test + fun verifyRejectsAnotherFoldersToken(): Unit = Server.testBlocking(settings = { + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + val prepare = avatars.upload.test(null, Unit) + val key = uploads.tokens().parseOrNull(prepare.token.raw)!!.key + files().root.then("upload-jail").then(key).put(TypedData.text("hello", MediaType.Text.Plain)) + + assertFailsWith { documents.verify.test(null, prepare.token) } + } + + @Test + fun folderMustBeRelative() { + assertFailsWith { UploadEndpoints(Server.uploads, "/avatars", noAuth) } + assertFailsWith { UploadEndpoints(Server.uploads, "avatars/", noAuth) } + assertFailsWith { UploadEndpoints(Server.uploads, "", noAuth) } + } + + @Test + fun sdkUsesTheUploadClient() { + val out = "build/testfiles/sdk-${Uuid.random()}" + FetcherSdk("com.example").writeUsingDefaultSettings(Server, KFile(out)) + val liveApi = java.io.File(out).walk().first { it.name == "LiveApi.kt" }.readText() + assertTrue("LiveClientFileUploadEndpoints(fetcher, \"avatars/upload\"" in liveApi, liveApi) + } + + /** The deprecated client methods decode the same JSON, so the typed tokens must not change the wire format. */ + @Suppress("DEPRECATION") + @Test + fun uploadTargetKeepsTheOldWireFormat() { + val target = UploadTarget("https://example.com/put", UnverifiedUploadToken("future:a.file")) + val old = Json.decodeFromString(UploadInformation.serializer(), Json.encodeToString(UploadTarget.serializer(), target)) + assertEquals(UploadInformation("https://example.com/put", "future:a.file"), old) + } + + /** Over HTTP, verify must send the scanned token itself; a signed URL would never be claimed, so cleanup would delete the file. */ + @Test + fun verifySendsTheTokenNotAUrl(): Unit = Server.testBlocking(settings = { + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + val prepare = avatars.upload.test(null, Unit) + val key = uploads.tokens().parseOrNull(prepare.token.raw)!!.key + files().root.then("upload-jail").then(key).put(TypedData.text("hello", MediaType.Text.Plain)) + + val response = (avatars.verify as HttpHandler).test( + body = TypedData.text(Json.encodeToString(UnverifiedUploadToken.serializer(), prepare.token), MediaType.Application.Json) + ) + val sent = Json.decodeFromString(response.body!!.text()) + assertIs(uploads.tokens().parseOrNull(sent), "Expected a scanned token, got $sent") + } +} diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpointTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpointTest.kt index 301f427e9..43c95c183 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpointTest.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyEndpointTest.kt @@ -31,7 +31,7 @@ class UploadEarlyEndpointTest { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) val served = path.path("files") include FileSystemEndpoints(files) - val uploadEarly = path.path("upload") include UploadEarlyEndpoint( + val uploadEarly = path.path("upload") include GlobalUploadEndpoints( files = files, database = database, fileScanner = { listOf() } @@ -129,11 +129,11 @@ class UploadEarlyEndpointTest { body = TypedData.text("Hello world!", MediaType.Text.Plain) ) } - val ready = Server.uploadEarly.verify.test(null, prepare.futureCallToken) + val ready = Server.uploadEarly.verify.test(null, prepare.token) val clientSideServerFile = Server.consume.test( body = TypedData.text( - Json.encodeToString(ServerFile(ready)), + Json.encodeToString(ready), MediaType.Application.Json ) ) diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyNoScannerTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyNoScannerTest.kt index 5f850609d..a0419b8bb 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyNoScannerTest.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyNoScannerTest.kt @@ -27,7 +27,7 @@ class UploadEarlyNoScannerTest { object Server : ServerBuilder() { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) - val uploadEarly = path.path("upload") include UploadEarlyEndpoint( + val uploadEarly = path.path("upload") include GlobalUploadEndpoints( files = files, database = database, fileScanner = { listOf() }, @@ -46,7 +46,7 @@ class UploadEarlyNoScannerTest { val prepare = uploadEarly.endpoint.test(null, Unit) assertTrue(prepare.uploadUrl.contains("uploaded"), "Upload should target ready: ${prepare.uploadUrl}") assertFalse(prepare.uploadUrl.contains("upload-jail"), "Nothing to jail when nothing scans") - assertIs(uploadEarly.tokens().parseOrNull(prepare.futureCallToken)) + assertIs(uploadEarly.tokens().parseOrNull(prepare.token.raw)) } /** With nothing to scan there is nothing for verify to do, so a client may call it or not. */ @@ -56,7 +56,7 @@ class UploadEarlyNoScannerTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - assertEquals(prepare.futureCallToken, uploadEarly.verify.test(null, prepare.futureCallToken)) + assertEquals(prepare.token.raw, uploadEarly.verify.test(null, prepare.token).location) } @Test @@ -65,12 +65,12 @@ class UploadEarlyNoScannerTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().root.then("uploaded").then(key).put(TypedData.text("hello", MediaType.Text.Plain)) val ser = uploadEarly.serializer() val resolved = Json { serializersModule = serializersModuleOf(ser) } - .decodeFromJsonElement(ser, JsonPrimitive(prepare.futureCallToken)) + .decodeFromJsonElement(ser, JsonPrimitive(prepare.token.raw)) assertEquals("hello", resolved.externalFile.get()!!.text()) } } diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyScanningTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyScanningTest.kt index a9668eca2..3656804fc 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyScanningTest.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlyScanningTest.kt @@ -4,7 +4,6 @@ import com.lightningkite.lightningserver.BadRequestException import com.lightningkite.lightningserver.definition.Runtime import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.runtime.Engine -import com.lightningkite.lightningserver.runtime.serverRuntime import com.lightningkite.lightningserver.runtime.test.testBlocking import com.lightningkite.lightningserver.serialization.registerBasicMediaTypeCoders import com.lightningkite.lightningserver.settings.set @@ -57,7 +56,7 @@ class UploadEarlyScanningTest { object Server : ServerBuilder() { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) - val uploadEarly = path.path("upload") include UploadEarlyEndpoint( + val uploadEarly = path.path("upload") include GlobalUploadEndpoints( files = files, database = database, fileScanner = Runtime { listOf(ControlledScanner(contextOf())) }, @@ -82,7 +81,7 @@ class UploadEarlyScanningTest { prepare.uploadUrl.contains("upload-jail"), "Upload should be directed at the jail: ${prepare.uploadUrl}" ) - assertIs(uploadEarly.tokens().parseOrNull(prepare.futureCallToken)) + assertIs(uploadEarly.tokens().parseOrNull(prepare.token.raw)) } /** @@ -95,11 +94,11 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("hello", MediaType.Text.Plain)) assertFailsWith { - decode(uploadEarly.serializer(), prepare.futureCallToken) + decode(uploadEarly.serializer(), prepare.token.raw) } } @@ -109,17 +108,17 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("hello", MediaType.Text.Plain)) - val verified = uploadEarly.verify.test(null, prepare.futureCallToken) + val verified = uploadEarly.verify.test(null, prepare.token) - val promoted = assertIs(uploadEarly.tokens().parseOrNull(verified)).key + val promoted = assertIs(uploadEarly.tokens().parseOrNull(verified.location)).key assertNotEquals(key, promoted, "Promotion must not reuse the client's jail key") assertEquals("hello", files().promoted(promoted).get()!!.text()) assertEquals( files().promoted(promoted).serverFile.location, - decode(uploadEarly.serializer(), verified).location + decode(uploadEarly.serializer(), verified.location).location ) } @@ -133,10 +132,10 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("hello", MediaType.Text.Plain)) - uploadEarly.verify.test(null, prepare.futureCallToken) + uploadEarly.verify.test(null, prepare.token) val scanned = ScanControl.scanned.single().path.toString() assertTrue(scanned.contains("uploaded"), "Scanner should see the promoted copy, got: $scanned") @@ -157,7 +156,7 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key val jailed = files().jailed(key) jailed.put(TypedData.text("benign", MediaType.Text.Plain)) @@ -165,15 +164,15 @@ class UploadEarlyScanningTest { // rewrite the jail at any moment - including mid-scan. ScanControl.behavior = { jailed.put(TypedData.text("malicious", MediaType.Text.Plain)) } - val verified = uploadEarly.verify.test(null, prepare.futureCallToken) - val promoted = uploadEarly.tokens().parseOrNull(verified)!!.key + val verified = uploadEarly.verify.test(null, prepare.token) + val promoted = uploadEarly.tokens().parseOrNull(verified.location)!!.key assertEquals( "benign", files().promoted(promoted).get()!!.text(), "The promoted file must be the bytes that were scanned" ) - assertEquals("benign", decode(uploadEarly.serializer(), verified).externalFile.get()!!.text()) + assertEquals("benign", decode(uploadEarly.serializer(), verified.location).externalFile.get()!!.text()) assertEquals("malicious", jailed.get()!!.text(), "The mid-scan swap must actually have landed") } @@ -184,10 +183,10 @@ class UploadEarlyScanningTest { }) { ScanControl.behavior = { throw FileScanException("infected") } val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("malicious", MediaType.Text.Plain)) - assertFailsWith { uploadEarly.verify.test(null, prepare.futureCallToken) } + assertFailsWith { uploadEarly.verify.test(null, prepare.token) } assertEquals( emptyList(), @@ -208,12 +207,12 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("benign", MediaType.Text.Plain)) - val first = uploadEarly.tokens().parseOrNull(uploadEarly.verify.test(null, prepare.futureCallToken))!!.key + val first = uploadEarly.tokens().parseOrNull(uploadEarly.verify.test(null, prepare.token).location)!!.key files().jailed(key).put(TypedData.text("second", MediaType.Text.Plain)) - val second = uploadEarly.tokens().parseOrNull(uploadEarly.verify.test(null, prepare.futureCallToken))!!.key + val second = uploadEarly.tokens().parseOrNull(uploadEarly.verify.test(null, prepare.token).location)!!.key assertNotEquals(first, second, "Each verify must promote to its own file") assertEquals("benign", files().promoted(first).get()!!.text()) @@ -230,13 +229,13 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("benign", MediaType.Text.Plain)) - val certified = uploadEarly.tokens().parseOrNull(uploadEarly.verify.test(null, prepare.futureCallToken))!!.key + val certified = uploadEarly.tokens().parseOrNull(uploadEarly.verify.test(null, prepare.token).location)!!.key ScanControl.behavior = { throw FileScanException("infected") } files().jailed(key).put(TypedData.text("malicious", MediaType.Text.Plain)) - assertFailsWith { uploadEarly.verify.test(null, prepare.futureCallToken) } + assertFailsWith { uploadEarly.verify.test(null, prepare.token) } assertEquals("benign", files().promoted(certified).get()!!.text(), "The certified file must survive") } @@ -248,11 +247,11 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key files().jailed(key).put(TypedData.text("hello", MediaType.Text.Plain)) - val verified = uploadEarly.verify.test(null, prepare.futureCallToken) + val verified = uploadEarly.verify.test(null, prepare.token) - assertEquals(verified, uploadEarly.verify.test(null, verified)) + assertEquals(verified, uploadEarly.verify.test(null, UnverifiedUploadToken(verified.location))) assertEquals(1, ScanControl.scanned.size, "Re-verifying must not scan again") } @@ -262,8 +261,8 @@ class UploadEarlyScanningTest { database set Database.Settings() }) { val prepare = uploadEarly.endpoint.test(null, Unit) - val key = uploadEarly.tokens().parseOrNull(prepare.futureCallToken)!!.key - val forged = prepare.futureCallToken.replace(key, "someone-elses.file") + val key = uploadEarly.tokens().parseOrNull(prepare.token.raw)!!.key + val forged = UnverifiedUploadToken(prepare.token.raw.replace(key, "someone-elses.file")) assertFailsWith { uploadEarly.verify.test(null, forged) } } } @@ -281,7 +280,7 @@ class UploadEarlyUnsignedFileSystemTest { object Server : ServerBuilder() { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) - val uploadEarly = path.path("upload") include UploadEarlyEndpoint( + val uploadEarly = path.path("upload") include GlobalUploadEndpoints( files = files, database = database, fileScanner = Runtime { listOf(ControlledScanner(contextOf())) }, diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlySdkTests.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlySdkTests.kt index 32d8ae7a9..e508b41d5 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlySdkTests.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/UploadEarlySdkTests.kt @@ -20,7 +20,7 @@ class UploadEarlySdkTests { val database = setting("database", Database.Settings()) val files = setting("files", ExternalFileSystem.Settings()) - val uploadEarly = path.path("upload") module UploadEarlyEndpoint( + val uploadEarly = path.path("upload") module GlobalUploadEndpoints( files = files, database = database, fileScanner = Runtime.Constant(emptyList()) diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/Api.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/Api.kt index e26bd6e1a..8b3f1b7ac 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/Api.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/Api.kt @@ -8,7 +8,7 @@ interface Api { fun withHeaderCalculator(calculator: suspend () -> List>): Api = withMetadata { clear(); for ((name, value) in calculator()) append(name, value) } - val uploadEarlyEndpoint: com.lightningkite.lightningserver.files.ClientUploadEarlyEndpoints + val globalUpload: com.lightningkite.lightningserver.files.ClientFileUploadEndpoints val module: com.lightningkite.lightningserver.typed.ClientModelRestEndpoints } diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/LiveApi.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/LiveApi.kt index c7e2c01f0..96e05a716 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/LiveApi.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/generated/LiveApi.kt @@ -12,7 +12,7 @@ class LiveApi(val fetcher: Fetcher) : Api { override fun withMetadata(block: suspend RequestMetadata.() -> Unit): LiveApi = LiveApi(fetcher.withMetadata(block)) - override val uploadEarlyEndpoint = com.lightningkite.lightningserver.files.LiveClientUploadEarlyEndpoints(fetcher, "upload", ) + override val globalUpload = com.lightningkite.lightningserver.files.LiveClientFileUploadEndpoints(fetcher, "upload", ) override val module = com.lightningkite.lightningserver.typed.LiveClientModelRestEndpoints(fetcher, "module/rest", com.lightningkite.lightningserver.files.UploadEarlySdkTests.Model.serializer(), kotlin.uuid.Uuid.serializer()) } From cdcdbf61253644a19b08c4095f9c21424b66795f Mon Sep 17 00:00:00 2001 From: iHoonter Date: Thu, 5 Nov 2026 22:44:37 -0700 Subject: [PATCH 2/4] More tests and made folder paths dynamic --- docs-guide/drafts/files.md | 2 +- .../files/FileSystemEndpoints.kt | 2 +- .../{UploadBasis.kt => FileUploadBasis.kt} | 136 ++++++++---------- .../files/GlobalUploadEndpoints.kt | 12 +- .../lightningserver/files/UploadEndpoints.kt | 61 +++++--- .../files/UploadForNextRequest.kt | 9 +- .../files/PathedUploadEndpointsTest.kt | 87 ++++++++++- 7 files changed, 202 insertions(+), 107 deletions(-) rename files/src/main/kotlin/com/lightningkite/lightningserver/files/{UploadBasis.kt => FileUploadBasis.kt} (66%) diff --git a/docs-guide/drafts/files.md b/docs-guide/drafts/files.md index c6fbb6b61..70833f9b6 100644 --- a/docs-guide/drafts/files.md +++ b/docs-guide/drafts/files.md @@ -82,7 +82,7 @@ object FileServer : ServerBuilder() { | `jailFilePath` | `"upload-jail"` | subdirectory for freshly-uploaded, unscanned files | | `filePath` | `"uploaded"` | subdirectory for scanned, ready-to-use files | | `expiration` | `1.days` | how long upload tokens remain valid | -| `authOptions` | `noAuth` | require authentication on the upload endpoint | +| `auth` | `noAuth` | require authentication on the upload endpoint | ## The Upload-Early Flow diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpoints.kt index 4bd3c9960..1db89625b 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpoints.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileSystemEndpoints.kt @@ -164,7 +164,7 @@ public class FileSystemEndpoints( try { kotlinx.parseUploadUrl(it.externalUrl())!!.put(it.body!!) } catch (e: Exception) { - throw BadRequestException("Invalid file Upload URL") + throw BadRequestException("Invalid file Upload URL", cause = e) } HttpResponse(status = HttpStatus.NoContent) diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt similarity index 66% rename from files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt rename to files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt index 87138a309..c81957daf 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadBasis.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt @@ -2,8 +2,6 @@ package com.lightningkite.lightningserver.files import com.lightningkite.lightningserver.BadRequestException import com.lightningkite.lightningserver.LSError -import com.lightningkite.lightningserver.auth.AuthRequirement -import com.lightningkite.lightningserver.auth.noAuth import com.lightningkite.lightningserver.definition.* import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.encryption.Signer @@ -26,11 +24,11 @@ import kotlin.uuid.Uuid * Holds what every early upload shares: the tokens, the ServerFile serializer, the tracking table and * its cleanup. It declares no endpoints of its own; [UploadEndpoints] modules declare those. * - * Include it once, then give each place that accepts uploads its own [UploadEndpoints] with [uploadEndpoints]: + * Include it once, then give each place that accepts uploads its own [UploadEndpoints]: * ```kotlin * val uploads = path.path("uploads") include UploadBasis(files, database, fileScanner = { listOf() }) - * val avatarUpload = path.path("users").path("avatar-upload") include - * uploads.uploadEndpoints("users/avatars", UserAuth.require()) + * val avatarUpload = path.path("users").path("avatar-upload") module + * UploadEndpoints(uploads, "users/avatars", UserAuth.require()) * ``` * * Flow: @@ -52,7 +50,7 @@ import kotlin.uuid.Uuid * - Upload tokens are time-limited by [expiration]. Ensure your client uses them promptly. * - This installs the contextual ServerFile serializer, so a server should include only one basis. */ -public class UploadBasis( +public class FileUploadBasis( public val files: Runtime, public val database: Runtime, public val fileScanner: Runtime>, @@ -178,73 +176,70 @@ public class UploadBasis( } /** - * Scans the file [upload] names and promotes it to the ready location, keeping it in [folder]. + * Scans the file [upload] names and promotes it to the ready location, keeping it in the folder it was uploaded to. * * Returns a [ServerFile] whose location is the scanned token, not a URL, so it must be encoded with * [DirectServerFileSerializer]; the contextual serializer resolves it only when a later request sends it back. */ context(_: ServerRuntime) - internal suspend fun verify(folder: String, upload: UnverifiedUploadToken): ServerFile { - val parsed = tokens().parseOrNull(upload.raw) - ?: throw IllegalArgumentException("Not an upload token.") - if (parsed.key.substringBeforeLast('/', "") != folder) - throw IllegalArgumentException("This token was issued for a different upload endpoint.") - return when (parsed) { - // Already verified. Returning the token unchanged makes a retry safe. - is UploadToken.Scanned -> ServerFile(upload.raw) + internal suspend fun verify(upload: UnverifiedUploadToken): ServerFile = when ( + val parsed = tokens().parseOrNull(upload.raw) ?: throw IllegalArgumentException("Not an upload token.") + ) { + // Already verified. Returning the token unchanged makes a retry safe. + is UploadToken.Scanned -> ServerFile(upload.raw) - is UploadToken.Unscanned -> { - // Promote under a fresh server-chosen key rather than reusing the client's. The - // jail stays writable through the presigned upload URL for the whole expiration - // window, so a client that re-uploads and verifies again would otherwise - // overwrite - or, when the rescan fails, delete - a file it had already had - // certified and handed out. Distinct keys make every certified file immutable. - val promotedKey = newKey(folder) - val safe = ready().then(promotedKey) + is UploadToken.Unscanned -> { + // Promote under a fresh server-chosen key rather than reusing the client's. The + // jail stays writable through the presigned upload URL for the whole expiration + // window, so a client that re-uploads and verifies again would otherwise + // overwrite - or, when the rescan fails, delete - a file it had already had + // certified and handed out. Distinct keys make every certified file immutable. + // Claude: the token is signed, so its folder is one this server chose; keep it. + val promotedKey = newKey(parsed.key.substringBeforeLast('/', "")) + val safe = ready().then(promotedKey) - // Record the file before creating it. The cleanup task collects by row, so - // inserting first means a crash anywhere below leaves a tracked file rather - // than an orphan nothing will ever delete. - uploadForNextRequestTable().insertOne( - UploadForNextRequest(expires = now().plus(expiration), file = safe.serverFile) - ) + // Record the file before creating it. The cleanup task collects by row, so + // inserting first means a crash anywhere below leaves a tracked file rather + // than an orphan nothing will ever delete. + uploadForNextRequestTable().insertOne( + UploadForNextRequest(expires = now().plus(expiration), file = safe.serverFile) + ) - // Copy first, then scan the copy - never scan the jail file in place, because - // the client could swap the bytes afterwards through that same upload URL. - // Nothing can write to the ready location, so once copied the bytes are frozen - // and the scan below covers exactly what will later be served. - jail().then(parsed.key).copyTo(safe) + // Copy first, then scan the copy - never scan the jail file in place, because + // the client could swap the bytes afterwards through that same upload URL. + // Nothing can write to the ready location, so once copied the bytes are frozen + // and the scan below covers exactly what will later be served. + jail().then(parsed.key).copyTo(safe) + try { + fileScanner().scan(safe) + } catch (cancellation: CancellationException) { + // The cleanup below is suspend work, which fails immediately in a cancelled + // scope and would only bury the cancellation under a suppressed exception. + // The row inserted above already guarantees the file gets collected. + throw cancellation + } catch (e: Exception) { + // Nothing can reference an unscanned ready file - only the line below mints + // a Scanned token, and promotedKey is unguessable - so this is prompt + // hygiene rather than the thing keeping us safe. Suppress rather than mask: + // the scan failure is the error worth reporting. try { - fileScanner().scan(safe) - } catch (cancellation: CancellationException) { - // The cleanup below is suspend work, which fails immediately in a cancelled - // scope and would only bury the cancellation under a suppressed exception. - // The row inserted above already guarantees the file gets collected. - throw cancellation - } catch (e: Exception) { - // Nothing can reference an unscanned ready file - only the line below mints - // a Scanned token, and promotedKey is unguessable - so this is prompt - // hygiene rather than the thing keeping us safe. Suppress rather than mask: - // the scan failure is the error worth reporting. - try { - safe.delete() - } catch (cleanupFailure: Exception) { - e.addSuppressed(cleanupFailure) - } - // A scanner rejecting the file is the client's fault, not ours. - if (e is FileScanException) throw BadRequestException( - detail = fileScanFailedError.detail, - message = e.message ?: fileScanFailedError.message, - cause = e, - ) - throw e + safe.delete() + } catch (cleanupFailure: Exception) { + e.addSuppressed(cleanupFailure) } - - // The jail copy is deliberately left in place: its own row expires and the - // cleanup task collects it, and leaving it lets a client that lost our response - // retry without re-uploading. - ServerFile(tokens().sign(UploadToken.Scanned(promotedKey), expiration)) + // A scanner rejecting the file is the client's fault, not ours. + if (e is FileScanException) throw BadRequestException( + detail = fileScanFailedError.detail, + message = e.message ?: fileScanFailedError.message, + cause = e, + ) + throw e } + + // The jail copy is deliberately left in place: its own row expires and the + // cleanup task collects it, and leaving it lets a client that lost our response + // retry without re-uploading. + ServerFile(tokens().sign(UploadToken.Scanned(promotedKey), expiration)) } } @@ -252,7 +247,7 @@ public class UploadBasis( * Daily cleanup of expired uploads. Removes database entries and attempts to delete the associated file. */ public val cleanupSchedule: ScheduledTask = path.path("cleanupUploads") bind ScheduledTask(frequency = 1.days) { - uploadForNextRequestTable().deleteMany(Condition { it.expires lt now() }).forEach { + uploadForNextRequestTable().deleteMany(UploadForNextRequest.expires lt now()).forEach { try { it.file.externalFile.delete() } catch (e: Exception) { @@ -260,19 +255,4 @@ public class UploadBasis( } } } - - /** - * Returns a [UploadEndpoints] module that stores uploads under [folder] using this basis. - * - * The module still has to be included at a path: - * ```kotlin - * val avatarUpload = path.path("avatar-upload") include Server.uploads.uploadEndpoints("users/avatars", UserAuth.require()) - * ``` - * - * [auth] defaults to [noAuth], which lets anyone upload; pass a requirement unless that is intended. - * - * @throws IllegalArgumentException if [folder] is blank or starts or ends with `/`. - */ - public fun uploadEndpoints(folder: String, auth: AuthRequirement<*> = noAuth): UploadEndpoints = - UploadEndpoints(this, folder, auth) } diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt index 0cd0d11c0..8da7cb1a9 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt @@ -21,8 +21,8 @@ public typealias UploadEarlyEndpoint = GlobalUploadEndpoints /** * Provides a single endpoint pair for early file upload, storing every file at the root of [filePath]. * - * See [UploadBasis] for the flow and its gotchas. To give each feature its own folder and permission - * check instead, include an [UploadBasis] and declare a [UploadEndpoints] per feature. + * See [FileUploadBasis] for the flow and its gotchas. To give each feature its own folder and permission + * check instead, include an [FileUploadBasis] and declare a [UploadEndpoints] per feature. */ public class GlobalUploadEndpoints( public val files: Runtime, @@ -38,7 +38,7 @@ public class GlobalUploadEndpoints( sdkSettings.clientInterface = ClientFileUploadEndpoints::class.info() } - public val basis: UploadBasis = path include UploadBasis( + public val basis: FileUploadBasis = path include FileUploadBasis( files = files, database = database, fileScanner = fileScanner, @@ -51,7 +51,7 @@ public class GlobalUploadEndpoints( /** Mints and checks the tokens this endpoint hands to clients. */ public val tokens: Runtime get() = basis.tokens - /** Contextual serializer used for ServerFile values; see [UploadBasis.serializer]. */ + /** Contextual serializer used for ServerFile values; see [FileUploadBasis.serializer]. */ public val serializer: Runtime get() = basis.serializer /** @@ -83,9 +83,9 @@ public class GlobalUploadEndpoints( functionName = "verifyUpload", description = "Scans an uploaded file and moves it out of jail so later requests can use it.", errorCases = listOf(basis.fileScanFailedError), - implementation = { upload: UnverifiedUploadToken -> basis.verify(folder = "", upload) } + implementation = { upload: UnverifiedUploadToken -> basis.verify(upload) } ) - /** Daily cleanup of expired uploads; see [UploadBasis.cleanupSchedule]. */ + /** Daily cleanup of expired uploads; see [FileUploadBasis.cleanupSchedule]. */ public val cleanupSchedule: ScheduledTask get() = basis.cleanupSchedule } diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt index f85512162..a145c4ca6 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt @@ -1,11 +1,14 @@ package com.lightningkite.lightningserver.files import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.auth.noAuth import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.http.get import com.lightningkite.lightningserver.http.post import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.runtime.ServerRuntime import com.lightningkite.lightningserver.typed.ApiHttpHandler +import com.lightningkite.lightningserver.typed.AuthAccess import com.lightningkite.lightningserver.typed.explicitApiHttpHandler import com.lightningkite.lightningserver.typed.sdk.* import com.lightningkite.lightningserver.typed.sdk.SdkModule.Companion.defaultInfo @@ -14,24 +17,40 @@ import com.lightningkite.services.files.DirectServerFileSerializer import com.lightningkite.services.files.ServerFile /** - * Upload endpoints that store files under [folder], for callers passing [authOptions]. + * Creates upload endpoints that store every file under the fixed [folder]. + * + * @throws IllegalArgumentException if [folder] is not a valid relative path. + */ +public fun ?> UploadEndpoints( + basis: FileUploadBasis, + folder: String, + auth: AuthRequirement +): UploadEndpoints { + require(isValidFolder(folder)) { invalidFolderMessage(folder) } + return UploadEndpoints(basis, auth, { folder }) +} + +/** + * Upload endpoints that store files under the folder [folder] returns, for callers passing [auth]. * * Tokens, the ServerFile serializer and cleanup come from the shared [basis], so a file uploaded here * is used in later requests like any other upload. Declare one of these wherever a feature accepts - * uploads, and put the feature's permission check in [authOptions], e.g. + * uploads, and put the feature's permission check in [auth], e.g. * `UserAuth.require { it.fetch().canUploadDocuments }`. * - * @param folder The path under the basis's jail and ready locations, such as `"users/avatars"`. + * [folder] runs on every upload, so it can sort files by who is uploading: + * ```kotlin + * UploadEndpoints(uploads, UserAuth.require()) { "users/${auth.rawId}/avatars" } + * ``` + * It must return a relative path such as `"users/avatars"`: not blank, no leading or trailing `/`, and no + * empty, `.` or `..` segments. Anything else fails the upload with an [IllegalStateException]. */ -public class UploadEndpoints( - public val basis: UploadBasis, - public val folder: String, - public val authOptions: AuthRequirement<*>, +public class UploadEndpoints?>( + public val basis: FileUploadBasis, + public val auth: AuthRequirement, + private val folder: suspend context(ServerRuntime) AuthAccess.() -> String, ) : ServerBuilder() { init { - require(folder.isNotBlank() && !folder.startsWith('/') && !folder.endsWith('/')) { - "Upload folder must be a relative path without leading or trailing slashes; got '$folder'." - } sdkSettings.clientInterface = ClientFileUploadEndpoints::class.info() sdkSettings.defaultInfo = SdkModule.Info( interfaceName = "FileUploadEndpoints", @@ -43,24 +62,28 @@ public class UploadEndpoints( * GET handler to prepare an upload. Returns an [UploadTarget] containing the presigned upload URL and * the [UnverifiedUploadToken] to pass to [verify]. */ - public val upload: ApiHttpHandler?, Unit, UploadTarget> = + public val upload: ApiHttpHandler = path.get bind ApiHttpHandler( - auth = authOptions, + auth = auth, summary = "Get File Upload URL", functionName = "getFileUploadUrl", description = "Returns a URL to PUT a file to, and a token that refers to that file. Send the token to verify, " + "then use the result as a file in a later request. Both expire in ${basis.expiration}.", errorCases = listOf(), - implementation = { _: Unit -> basis.prepare(folder) } + implementation = { _: Unit -> + val folder = folder() + check(isValidFolder(folder)) { invalidFolderMessage(folder) } + basis.prepare(folder) + } ) /** * POST handler to verify a file uploaded through [upload], scanning it and promoting it to the ready * location. Returns a [ServerFile] to send in a later request. */ - public val verify: ApiHttpHandler?, UnverifiedUploadToken, ServerFile> = + public val verify: ApiHttpHandler = path.path("verify").post bind explicitApiHttpHandler( - auth = authOptions, + auth = auth, inputType = UnverifiedUploadToken.serializer(), // Claude: the location is the scanned token; the contextual serializer would send a signed URL instead, // which the server would never claim, so cleanup would delete the file. @@ -69,6 +92,12 @@ public class UploadEndpoints( functionName = "verifyUpload", description = "Scans an uploaded file and moves it out of jail so later requests can use it.", errorCases = listOf(basis.fileScanFailedError), - implementation = { upload: UnverifiedUploadToken -> basis.verify(folder, upload) } + implementation = { upload: UnverifiedUploadToken -> basis.verify(upload) } ) } + +private fun isValidFolder(folder: String): Boolean = + folder.split('/').none { it.isBlank() || it == "." || it == ".." } + +private fun invalidFolderMessage(folder: String): String = + "Upload folder must be a relative path with no empty, '.' or '..' segments; got '$folder'." diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt index 95ffefb6e..5042f7c17 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadForNextRequest.kt @@ -1,5 +1,6 @@ package com.lightningkite.lightningserver.files +import com.lightningkite.services.data.Index import com.lightningkite.services.data.Queryable import com.lightningkite.services.database.HasId import com.lightningkite.services.files.ServerFile @@ -18,8 +19,12 @@ import kotlin.uuid.Uuid @Queryable public data class UploadForNextRequest( override val _id: Uuid = Uuid.random(), - /** The file location (as a ServerFile URL) associated with this prepared upload. */ - val file: ServerFile, + /** + * The file location (as a ServerFile URL) associated with this prepared upload. + * + * Indexed because the ServerFile serializer deletes the row by this field each time a request claims an upload. + */ + @Index val file: ServerFile, /** Expiration time after which the upload is considered invalid/garbage. */ val expires: Instant, ) : HasId diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt index 303757ac0..c02e0c17e 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt @@ -1,5 +1,6 @@ package com.lightningkite.lightningserver.files +import com.lightningkite.lightningserver.HttpMethod import com.lightningkite.lightningserver.auth.noAuth import com.lightningkite.lightningserver.definition.Runtime import com.lightningkite.lightningserver.definition.builder.ServerBuilder @@ -11,8 +12,16 @@ import com.lightningkite.lightningserver.typed.sdk.FetcherSdk import com.lightningkite.lightningserver.typed.sdk.SDK.writeUsingDefaultSettings import com.lightningkite.lightningserver.typed.test import com.lightningkite.lightningserver.http.HttpHandler +import com.lightningkite.lightningserver.http.QueryParameters +import com.lightningkite.lightningserver.http.HttpRequest +import com.lightningkite.lightningserver.http.PathSegments +import com.lightningkite.lightningserver.http.post import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.pathing.RawHttpEndpoint +import com.lightningkite.lightningserver.runtime.handleRoot +import com.lightningkite.lightningserver.runtime.test.TestRunner import com.lightningkite.lightningserver.runtime.test.test +import com.lightningkite.lightningserver.typed.ApiHttpHandler import com.lightningkite.services.kfile.KFile import com.lightningkite.services.SettingContext import com.lightningkite.services.data.HealthStatus @@ -37,13 +46,25 @@ class PathedUploadEndpointsTest { object Server : ServerBuilder() { val files = setting("files", ExternalFileSystem.Settings()) val database = setting("database", Database.Settings()) - val uploads = path.path("uploads") include UploadBasis( + val uploads = path.path("uploads") include FileUploadBasis( files = files, database = database, fileScanner = Runtime { listOf(AcceptingScanner(contextOf())) }, ) + val fileEndpoints = path.path("files") include FileSystemEndpoints(files) val avatars = path.path("avatars").path("upload") include UploadEndpoints(uploads, "users/avatars", noAuth) val documents = path.path("documents").path("upload") include UploadEndpoints(uploads, "documents", noAuth) + var nextFolder = "dynamic/first" + val dynamic = path.path("dynamic").path("upload") include UploadEndpoints(uploads, noAuth) { nextFolder } + + val echo = path.path("echo").post bind ApiHttpHandler( + summary = "Echo File", + description = "Echo a ServerFile so it is marked as used and given a real url", + auth = noAuth, + implementation = { file: ServerFile -> + file + } + ) init { registerBasicMediaTypeCoders() @@ -81,7 +102,7 @@ class PathedUploadEndpointsTest { } @Test - fun verifyRejectsAnotherFoldersToken(): Unit = Server.testBlocking(settings = { + fun verifyKeepsTheTokensFolderWhicheverModuleVerifies(): Unit = Server.testBlocking(settings = { files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") database set Database.Settings() }) { @@ -89,7 +110,66 @@ class PathedUploadEndpointsTest { val key = uploads.tokens().parseOrNull(prepare.token.raw)!!.key files().root.then("upload-jail").then(key).put(TypedData.text("hello", MediaType.Text.Plain)) - assertFailsWith { documents.verify.test(null, prepare.token) } + val verified = documents.verify.test(null, prepare.token) + val promoted = uploads.tokens().parseOrNull(verified.location)!!.key + assertTrue(promoted.startsWith("users/avatars/"), "The file must stay where it was uploaded: $promoted") + } + + @Test + fun dynamicFolderIsComputedPerUpload(): Unit = Server.testBlocking(settings = { + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + Server.nextFolder = "dynamic/first" + val first = uploads.tokens().parseOrNull(dynamic.upload.test(null, Unit).token.raw)!!.key + Server.nextFolder = "dynamic/second" + val second = uploads.tokens().parseOrNull(dynamic.upload.test(null, Unit).token.raw)!!.key + assertTrue(first.startsWith("dynamic/first/"), first) + assertTrue(second.startsWith("dynamic/second/"), second) + } + + @Test + fun normalUse(): Unit = Server.testBlocking({ + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + val upload = avatars.upload.test(null, Unit) + val path = PathSegments.parse(upload.uploadUrl.substringBefore('?').substringAfter("/files/")) + fileEndpoints.upload.test( + trailingWildcard = path, + queryParameters = QueryParameters.parse(upload.uploadUrl.substringAfter('?')), + body = TypedData.text("trogdor", MediaType.Text.Plain) + ) + val fileToken = avatars.verify.test(null, upload.token) + // Claude: raw HTTP, because .test(auth, input) encodes the token with the server's outgoing serializer + val used = (echo as HttpHandler) + .test( + body = TypedData.text(Json.encodeToString(DirectServerFileSerializer, fileToken), MediaType.Application.Json) + ) + .let { + Json.decodeFromString(DirectServerFileSerializer, it.body!!.text()) + } + + println("Unverified Token: ${upload.token}") + println("Verified Token: $fileToken") + println("Used File: $used") + + val fetched = fileEndpoints.fetch.test( + trailingWildcard = PathSegments.parse(used.location.substringBefore('?').substringAfter("/files/")), + queryParameters = QueryParameters.parse(used.location.substringAfter('?')), + ) + assertEquals("trogdor", fetched.body!!.text()) + } + + @Test + fun invalidDynamicFolderFailsTheUpload(): Unit = Server.testBlocking(settings = { + files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") + database set Database.Settings() + }) { + for (bad in listOf("../escape", "a/../b", "a//b", "/abs", "trailing/", "", "./a")) { + Server.nextFolder = bad + assertFailsWith(bad) { dynamic.upload.test(null, Unit) } + } } @Test @@ -97,6 +177,7 @@ class PathedUploadEndpointsTest { assertFailsWith { UploadEndpoints(Server.uploads, "/avatars", noAuth) } assertFailsWith { UploadEndpoints(Server.uploads, "avatars/", noAuth) } assertFailsWith { UploadEndpoints(Server.uploads, "", noAuth) } + assertFailsWith { UploadEndpoints(Server.uploads, "a/../b", noAuth) } } @Test From 2ae46eca52042df234cc6799402741c85780ab69 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Fri, 6 Nov 2026 10:32:59 -0700 Subject: [PATCH 3/4] Better error messages on failed file cleanup --- .../lightningkite/lightningserver/files/FileUploadBasis.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt index c81957daf..820ba2d4f 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt @@ -13,6 +13,7 @@ import com.lightningkite.lightningserver.runtime.now import com.lightningkite.lightningserver.typed.registerTable import com.lightningkite.services.database.* import com.lightningkite.services.files.* +import io.github.oshai.kotlinlogging.KotlinLogging import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking import kotlinx.serialization.modules.SerializersModule @@ -20,6 +21,8 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.days import kotlin.uuid.Uuid +private val logger = KotlinLogging.logger {} + /** * Holds what every early upload shares: the tokens, the ServerFile serializer, the tracking table and * its cleanup. It declares no endpoints of its own; [UploadEndpoints] modules declare those. @@ -251,7 +254,8 @@ public class FileUploadBasis( try { it.file.externalFile.delete() } catch (e: Exception) { - e.printStackTrace() + // TODO: Should this re-add the file to the table? + logger.error(e) { "Failed to delete file during cleanup: ${it.file.location.substringBefore("?")}" } } } } From 6073497338ac673dfa1948c5e0e899dcbe7e45d5 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Fri, 6 Nov 2026 21:06:49 -0700 Subject: [PATCH 4/4] Updated FileUploadBasis to better work with custom upload endpoints --- .../lightningserver/files/FileUploadBasis.kt | 32 +++++++++++++---- .../files/GlobalUploadEndpoints.kt | 3 ++ .../lightningserver/files/UploadEndpoints.kt | 34 +++++++++++-------- .../files/PathedUploadEndpointsTest.kt | 6 ++-- gradle/libs.versions.toml | 2 +- 5 files changed, 52 insertions(+), 25 deletions(-) diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt index 820ba2d4f..228e656b5 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/FileUploadBasis.kt @@ -11,6 +11,7 @@ import com.lightningkite.lightningserver.runtime.ServerRuntime import com.lightningkite.lightningserver.runtime.engine import com.lightningkite.lightningserver.runtime.now import com.lightningkite.lightningserver.typed.registerTable +import com.lightningkite.services.data.Unsafe import com.lightningkite.services.database.* import com.lightningkite.services.files.* import io.github.oshai.kotlinlogging.KotlinLogging @@ -156,9 +157,19 @@ public class FileUploadBasis( private fun newKey(folder: String): String = if (folder.isEmpty()) "${Uuid.random()}.file" else "$folder/${Uuid.random()}.file" - /** Returns an upload URL and token for a new file under [folder]. */ + /** + * Returns an upload URL and token for a new file under [folder], for building custom upload endpoints. + * + * This does not authorize the caller, so prefer [UploadEndpoints], which does. A caller must authorize + * the request itself, and must choose [folder] on the server: it is signed into the token and [verify] + * trusts it, so a folder taken from the client lets the client place files anywhere in storage. + * + * @throws IllegalArgumentException if [folder] is not a valid folder; see [requireValidRelativeFolderPath]. + */ + @Unsafe("The caller must authorize the request, and the folder must be chosen by the server") context(_: ServerRuntime) - internal suspend fun prepare(folder: String): UploadTarget { + public suspend fun prepare(folder: String): UploadTarget { + requireValidRelativeFolderPath(folder) val key = newKey(folder) // With no scanners there is nothing to promote, so the client uploads straight to the // ready location and its token is born scanned. @@ -179,14 +190,21 @@ public class FileUploadBasis( } /** - * Scans the file [upload] names and promotes it to the ready location, keeping it in the folder it was uploaded to. + * Scans the file [upload] names and promotes it to the ready location, keeping it in the folder it was + * uploaded to, for building custom verify endpoints. + * + * The returned [ServerFile]'s location is the scanned token, not a URL, so it **must** be encoded with + * [DirectServerFileSerializer], e.g. as the `outputType` of an `explicitApiHttpHandler`. The contextual + * serializer would send a signed URL instead: the client could use it, but the server never claims + * the upload, so the cleanup task deletes the file once [expiration] passes. Retrying with an already + * verified token returns it unchanged. * - * Returns a [ServerFile] whose location is the scanned token, not a URL, so it must be encoded with - * [DirectServerFileSerializer]; the contextual serializer resolves it only when a later request sends it back. + * @throws BadRequestException if [upload] is not a token this basis issued, or a file scanner rejects the file. */ + @Unsafe("The returned ServerFile must be serialized with DirectServerFileSerializer") context(_: ServerRuntime) - internal suspend fun verify(upload: UnverifiedUploadToken): ServerFile = when ( - val parsed = tokens().parseOrNull(upload.raw) ?: throw IllegalArgumentException("Not an upload token.") + public suspend fun verify(upload: UnverifiedUploadToken): ServerFile = when ( + val parsed = tokens().parseOrNull(upload.raw) ?: throw BadRequestException("Not an upload token.") ) { // Already verified. Returning the token unchanged makes a retry safe. is UploadToken.Scanned -> ServerFile(upload.raw) diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt index 8da7cb1a9..11c954b33 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/GlobalUploadEndpoints.kt @@ -10,6 +10,7 @@ import com.lightningkite.lightningserver.pathing.PathSpec0 import com.lightningkite.lightningserver.typed.ApiHttpHandler import com.lightningkite.lightningserver.typed.explicitApiHttpHandler import com.lightningkite.lightningserver.typed.sdk.* +import com.lightningkite.services.data.Unsafe import com.lightningkite.services.database.* import com.lightningkite.services.files.* import kotlin.time.Duration @@ -58,6 +59,7 @@ public class GlobalUploadEndpoints( * GET handler to prepare an upload. Returns an [UploadTarget] containing the presigned upload URL and * the [UnverifiedUploadToken] to pass to [verify]. */ + @OptIn(Unsafe::class) // SAFETY: authOptions is required above and the folder is the root. public val endpoint: ApiHttpHandler?, Unit, UploadTarget> = path.get bind ApiHttpHandler( auth = authOptions, @@ -72,6 +74,7 @@ public class GlobalUploadEndpoints( * POST handler to verify a previously uploaded file, scanning it and promoting it to the ready * location. Returns a [ServerFile] to send in a later request. */ + @OptIn(Unsafe::class) // SAFETY: the output is encoded with DirectServerFileSerializer. public val verify: ApiHttpHandler?, UnverifiedUploadToken, ServerFile> = path.path("verify").post bind explicitApiHttpHandler( auth = authOptions, diff --git a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt index a145c4ca6..f2e73f4b9 100644 --- a/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt +++ b/files/src/main/kotlin/com/lightningkite/lightningserver/files/UploadEndpoints.kt @@ -1,7 +1,6 @@ package com.lightningkite.lightningserver.files import com.lightningkite.lightningserver.auth.AuthRequirement -import com.lightningkite.lightningserver.auth.noAuth import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.http.get import com.lightningkite.lightningserver.http.post @@ -12,6 +11,7 @@ import com.lightningkite.lightningserver.typed.AuthAccess import com.lightningkite.lightningserver.typed.explicitApiHttpHandler import com.lightningkite.lightningserver.typed.sdk.* import com.lightningkite.lightningserver.typed.sdk.SdkModule.Companion.defaultInfo +import com.lightningkite.services.data.Unsafe import com.lightningkite.services.database.HasId import com.lightningkite.services.files.DirectServerFileSerializer import com.lightningkite.services.files.ServerFile @@ -19,15 +19,15 @@ import com.lightningkite.services.files.ServerFile /** * Creates upload endpoints that store every file under the fixed [folder]. * - * @throws IllegalArgumentException if [folder] is not a valid relative path. + * @throws IllegalArgumentException if [folder] is not a valid folder; see [requireValidRelativeFolderPath]. */ public fun ?> UploadEndpoints( basis: FileUploadBasis, folder: String, auth: AuthRequirement ): UploadEndpoints { - require(isValidFolder(folder)) { invalidFolderMessage(folder) } - return UploadEndpoints(basis, auth, { folder }) + requireValidRelativeFolderPath(folder) + return UploadEndpoints(basis, auth) { folder } } /** @@ -42,8 +42,8 @@ public fun ?> UploadEndpoints( * ```kotlin * UploadEndpoints(uploads, UserAuth.require()) { "users/${auth.rawId}/avatars" } * ``` - * It must return a relative path such as `"users/avatars"`: not blank, no leading or trailing `/`, and no - * empty, `.` or `..` segments. Anything else fails the upload with an [IllegalStateException]. + * It must return a valid folder (see [requireValidRelativeFolderPath]); anything else fails the upload with an + * [IllegalArgumentException]. */ public class UploadEndpoints?>( public val basis: FileUploadBasis, @@ -62,6 +62,7 @@ public class UploadEndpoints?>( * GET handler to prepare an upload. Returns an [UploadTarget] containing the presigned upload URL and * the [UnverifiedUploadToken] to pass to [verify]. */ + @OptIn(Unsafe::class) // SAFETY: auth is required above and the folder comes from server code, not the client. public val upload: ApiHttpHandler = path.get bind ApiHttpHandler( auth = auth, @@ -71,9 +72,7 @@ public class UploadEndpoints?>( "then use the result as a file in a later request. Both expire in ${basis.expiration}.", errorCases = listOf(), implementation = { _: Unit -> - val folder = folder() - check(isValidFolder(folder)) { invalidFolderMessage(folder) } - basis.prepare(folder) + basis.prepare(folder()) } ) @@ -81,6 +80,7 @@ public class UploadEndpoints?>( * POST handler to verify a file uploaded through [upload], scanning it and promoting it to the ready * location. Returns a [ServerFile] to send in a later request. */ + @OptIn(Unsafe::class) // SAFETY: the output is encoded with DirectServerFileSerializer. public val verify: ApiHttpHandler = path.path("verify").post bind explicitApiHttpHandler( auth = auth, @@ -96,8 +96,14 @@ public class UploadEndpoints?>( ) } -private fun isValidFolder(folder: String): Boolean = - folder.split('/').none { it.isBlank() || it == "." || it == ".." } - -private fun invalidFolderMessage(folder: String): String = - "Upload folder must be a relative path with no empty, '.' or '..' segments; got '$folder'." +/** + * Throws an [IllegalArgumentException] if [folder] is not a valid upload folder. + * + * A valid folder is either `""`, meaning the root, or a relative path such as `"users/avatars"`: no leading or + * trailing `/`, and no blank, `.` or `..` segments. + */ +public fun requireValidRelativeFolderPath(folder: String) { + require(folder.isEmpty() || folder.split('/').none { it.isBlank() || it == "." || it == ".." }) { + "Upload folder must be \"\" or a relative path with no empty, '.' or '..' segments; got '$folder'." + } +} diff --git a/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt b/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt index c02e0c17e..c01c7363f 100644 --- a/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt +++ b/files/src/test/kotlin/com/lightningkite/lightningserver/files/PathedUploadEndpointsTest.kt @@ -166,9 +166,9 @@ class PathedUploadEndpointsTest { files set ExternalFileSystem.Settings("file://build/testfiles/${Uuid.random()}?serveUrl=http://localhost:8080/files") database set Database.Settings() }) { - for (bad in listOf("../escape", "a/../b", "a//b", "/abs", "trailing/", "", "./a")) { + for (bad in listOf("../escape", "a/../b", "a//b", "/abs", "trailing/", " ", "./a")) { Server.nextFolder = bad - assertFailsWith(bad) { dynamic.upload.test(null, Unit) } + assertFailsWith(bad) { dynamic.upload.test(null, Unit) } } } @@ -176,7 +176,7 @@ class PathedUploadEndpointsTest { fun folderMustBeRelative() { assertFailsWith { UploadEndpoints(Server.uploads, "/avatars", noAuth) } assertFailsWith { UploadEndpoints(Server.uploads, "avatars/", noAuth) } - assertFailsWith { UploadEndpoints(Server.uploads, "", noAuth) } + assertFailsWith { UploadEndpoints(Server.uploads, " ", noAuth) } assertFailsWith { UploadEndpoints(Server.uploads, "a/../b", noAuth) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ad2368cb3..ae770e03d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -28,7 +28,7 @@ oneTimePass = "3.0.0" orgCrac = "0.1.3" proguard = "7.10.0" scrimage = "4.6.8" -serviceAbstractions = "1.4.0-prerelease-136-d4718aad" +serviceAbstractions = "1.4.0-prerelease-146-9087ba12" vanniktechMavenPublish = "0.37.0" webauthn4jCore = "0.31.10.RELEASE"