Skip to content
Recommended solution · HC-8 · Rust

Upload Store Review

Three stages on a small Rust store for user uploads: keep every file inside its base directory, then make saves safe on a busy server (a size limit, an atomic write, honest content types), then hold a quota while many uploads arrive at once. The assistant's first version passes the happy path; the work is deciding what the store must refuse.

On this page

The codebase

The crate keeps the files users upload under one base directory. A web layer outside the crate calls save with the name the client sent, the type the client declared and the bytes, and later calls read, list and delete.

Each stage adds a read-only test file that fails on the code you start with, and hidden tests that run after Continue or Submit. Your own tests go in a file of your own and run with Test.

The assistant explains the code and Rust on request and makes the changes you direct.

Where things live

src/lib.rsThe public types and methods. Their signatures are fixed; fields and private code are yours.
src/store.rsThe paths, save, read, list and delete: where every stage's decision lands.
src/limits.rsAdded in stage 2: the size limit and the content type.
src/quota.rsAdded in stage 3: the quota.
src/candidate_tests.rsYour tests. Test runs them after the visible tests in tests/, which are read-only.

Rules that shape every fix

  • Keep the public API: the types, the methods and their signatures.
  • Build on the code you have rather than rewriting the crate.
  • Rust standard library only.

How to work each stage

  1. Press Test first and read which supplied test fails and why.
  2. Name the cause in the code before you ask for any change.
  3. Ask for your own tests first, each case with the answer the stage expects, and watch them fail.
  4. Decide the design yourself and say it whole: the rule, the mechanism, and what happens on every failure.
  5. Press Test again after the last change, then Continue or Submit.
Stage 1 · 01-stay-inside

Uploads stay inside the base directory

What the ticket asks

Two supplied tests fail on the code you start with: a client name that starts with two dots and a slash is written, read and deleted outside the base directory. Find out why and make the store stay inside its base.

A plain name is refused or accepted as it is, never repaired, and only a regular file under a name counts as a stored file.

Where to look

src/store.rsThe path for a name is built by joining the client's name to the base as given, and read and save open whatever sits there.
tests/store_test.rsThe two failing tests show the escape on save, read and delete.

What the stage pins down

Plain namesNot empty, at most 255 bytes, no slash, backslash or NUL byte, no leading dot. Anything else is InvalidName with the name as given, before the disk is touched.
Links and directoriesread and delete answer NotFound for anything that is not a regular file, save answers AlreadyExists, and neither the entry nor its target changes.

Where the generated store goes wrong

  • The name is joined to the base as given, so two dots, a separator or an absolute path leave the base.
  • Reading and creating a file follow a symlink planted under a name, so a read reaches its target and a save writes through it.

The fix

  1. Refuse a name that is not plain with one check that every method calls first.
  2. Look at the entry itself, without following it, before reading, deleting or saving.
src/store.rsOne name check, called by save, read and delete before any path is built.
+pub(crate) fn validate_name(name: &str) -> Result<(), StoreError> {+    let bytes = name.as_bytes();+    let plain = !bytes.is_empty()+        && bytes.len() <= MAX_NAME_BYTES+        && bytes[0] != b'.'+        && !bytes.iter().any(|&byte| byte == b'/' || byte == b'\\' || byte == 0);+    if plain {+        Ok(())+    } else {+        Err(StoreError::InvalidName(name.to_string()))+    }+}
src/store.rsread and delete look at the entry without following it; save refuses anything already there.
+        let metadata = fs::symlink_metadata(&path).map_err(|error| not_found_or_io(name, error))?;+        if !metadata.is_file() {+            return Err(StoreError::NotFound(name.to_string()));+        }

Tests that prove it

  • An absolute path, a backslash, a leading dot, an empty name and a NUL byte, each refused with the base left empty.
  • A 255-byte name stored, a 256-byte one refused, and ordinary names with dots and spaces kept.
  • A planted link refused by read, delete and save, with its target untouched.

The conversation

Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.

DirectionPrompt qualityVerificationCorrectnessCode quality

  1. Press Test. A supplied test fails: a name with two dots reaches outside the base.
  2. Your message 1

    Test fails at refuses_a_name_that_leaves_the_base (store/traversal_save): save("../outside.txt", ...) returns Ok and the file lands at <base>/../outside.txt, outside the base. The cause is path_for in src/store.rs: self.base.join(name) takes the client's name as given, so "..", a "/" or "\\", or an absolute path leaves the base. A second hazard: read uses fs::read and save uses File::create, both of which follow a symlink planted under a name. Before any change to store.rs, add tests inside the tests module of src/candidate_tests.rs, each on its own directory under std::env::temp_dir() that it removes at the end: (a) save("/etc/passwd", ..), save("a\\b.txt", ..), save(".hidden", ..), save("", ..) and save("a\0b", ..) are each Err(InvalidName(..)) carrying the name as given, and the base stays empty; (b) a 255-byte name of 'x' is stored and read back, a 256-byte one is Err(InvalidName); (c) save("a..b.txt", ..) and save("report 2026.pdf", ..) succeed and list shows both; (d) with std::os::unix::fs::symlink pointing <base>/link.txt at a file outside the base: read("link.txt") is Err(NotFound("link.txt")), delete("link.txt") is Err(NotFound("link.txt")) and the target still exists, save("link.txt", ..) is Err(AlreadyExists("link.txt")) and the target's bytes are unchanged. Don't change store.rs yet.

    Name the failing test and the cause in the code, then choose your own cases, each with the answer the stage expects, before any change.

    • Direction: Diagnosis, 8 points
    • Direction: Name rules owned, 8 points
    • Direction: Symlink rule, 8 points
    • Prompt quality: Named failing test, 5 points
    • Prompt quality: Contract examples, 7 points
    • Verification: Named cases, 8 points
  3. Press Test. Still red: your tests run after the supplied ones, which fail first.
    • Verification: Checks own, 6 points
  4. Your message 2

    Test fails at store_test::read_and_delete_refuse_a_name_that_leaves_the_base: for "<base>/../outside.txt holds \"secret\"; read \"../outside.txt\"; delete it; does the file still exist" it expected (Err(InvalidName("../outside.txt")), Err(InvalidName("../outside.txt")), true) and got (Ok([115, 101, 99, 114, 101, 116]), Ok(()), false). Now the fix, as I have decided it, keeping the public API: (1) Names are refused, never normalised: one validate_name(name: &str) -> Result<(), StoreError> in store.rs that save, read and delete call before building any path. It answers Err(InvalidName(name as given)) when the name is empty, longer than 255 bytes (bytes, not characters), starts with a dot (which covers "." and ".."), or contains a "/", a "\\" or a NUL byte; everything else is accepted, including "a..b.txt", spaces and non-ASCII. (2) Each method checks the entry itself, not what a link points at: read and delete look at it with fs::symlink_metadata and answer Err(NotFound(name)) unless it is a regular file, leaving a symlink or directory and its target untouched; save answers Err(AlreadyExists(name)) and writes nothing when anything other than a regular file sits under the name. Expected: save("../outside.txt") is Err(InvalidName("../outside.txt")) and nothing is written anywhere. Don't change the tests.

    Give the whole design: which names are refused, and what each method answers for a link or a directory.

    • Prompt quality: Specified fix, 8 points
  5. Press Test. Every test passes after the last change, your own included.
    • Verification: Run after last change, 6 points
  6. Continue. The stage closes. Scope, the hidden tests and code quality are judged on the final code.
    • Direction: Scope, 6 points
    • Correctness: Hidden tests, 20 points
    • Code quality: Code quality, 10 points

Where the stage lands

Measured when this conversation was played on the platform. A+ needs 92, S needs 95.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 2 · 02-limits

Limits, atomic writes, honest types

What the ticket asks

A new supplied test file fails on the code you start with: make save safe on a busy server. An upload over the limit is refused and read no further than needed, a half-written upload is never visible, and a failure leaves nothing behind.

The content type a stored file reports comes from its first bytes, the same from save and list.

Where to look

src/store.rssave copies the upload straight to its final name and checks the size after the whole copy.
src/limits.rsAdded by this stage: where the limit and the content type belong.

What the stage pins down

The limitMore than the limit is TooLarge and nothing is stored; exactly the limit is accepted; reading stops at most 64 KiB past it.
The writeA dot-prefixed temporary file in the base, moved into place in one step; nothing is listed or left behind on any failure, and a taken name is AlreadyExists.
The typePNG, JPEG, GIF and PDF by their signatures, anything else application/octet-stream; the declared type and the extension play no part.

Where the generated store goes wrong

  • The upload is copied under the client's name, so it is listed while it arrives and left behind when it fails.
  • The size is compared only after the whole copy, so a huge upload is read to the end.
  • The reported type comes from the declared type and the extension, not from the bytes.

The fix

  1. Read through a reader capped one byte past the limit and stop as soon as the count passes it.
  2. Write to a temporary file that a guard removes unless it is committed, then rename it into place.
  3. Sniff the first bytes as they stream, and sniff stored files the same way in list.
src/store.rsThe upload is read through a cap one byte past the limit, in fixed chunks.
+    let mut limited = data.take(limit.map_or(u64::MAX, |limit| limit.saturating_add(1)));+    let mut buffer = vec![0u8; CHUNK_BYTES];
src/store.rsA temporary file removes itself on every failure unless it was committed.
+impl Drop for TempFile {+    fn drop(&mut self) {+        if !self.committed {+            let _ = fs::remove_file(&self.path);+        }+    }+}
src/limits.rsThe type comes from the first bytes.
+pub fn sniff(head: &[u8]) -> &'static str {+    const PNG: &[u8] = &[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];+    const JPEG: &[u8] = &[0xff, 0xd8, 0xff];+    if head.starts_with(PNG) {+        "image/png"+    } else if head.starts_with(JPEG) {+        "image/jpeg"

Tests that prove it

  • The limit exactly and one byte past it, and a counting reader that shows how much of a large upload was read.
  • A reader that fails midway, leaving nothing behind and the name free.
  • A repeated name refused with the first file kept, and types that follow the bytes, not the name.

The conversation

Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.

DirectionPrompt qualityVerificationCorrectnessCode quality

  1. Press Test. The new supplied test file fails on the start code.
  2. Your message 1

    Stage 2: tests/limits_test.rs fails. The cause is in save: it copies the upload straight into File::create(final name) with io::copy and compares the size with max_bytes only after the whole copy, so a 512 KiB upload against a 256 KiB limit is read to the end, the file is listed while it is still arriving, and TooLarge or a reader error leaves it behind under the client's name. Before any change to src/, add stage-2 tests to src/candidate_tests.rs: (a) limit 1000: a Cursor of exactly 1000 bytes is stored with size 1000, a Cursor of 1001 bytes is Err(TooLarge { limit: 1000 }) and list shows only the first; (b) a counting reader of your own handing out 512 KiB against a 256 KiB limit: the result is TooLarge, at most 256 KiB + 64 KiB was handed out, and the base has no entries at all afterwards (dot files included); (c) a reader that returns Err(io::ErrorKind::Other) after 2500 bytes: save is Err(Io(..)), the base has no entries, and a second save of the same name with good bytes succeeds; (d) save("a.txt") twice: the second is Err(AlreadyExists("a.txt")) and read gives the first bytes; (e) the PNG signature followed by zeros saved as photo.txt declared text/plain reports image/png from save and from list, plain text saved as photo.png declared image/png reports application/octet-stream, and an empty upload reports application/octet-stream. Don't change store.rs or limits.rs yet.

    Name the cause in save, then choose your own cases for the limit, a failing upload, a taken name and the types.

    • Direction: Diagnosis, 7 points
    • Prompt quality: Contract examples, 4 points
    • Prompt quality: Failure follow-up, 3 points
    • Verification: Named cases, 8 points
  3. Press Test. Still red at the first supplied test.
    • Verification: Checks own, 6 points
  4. Your message 2

    Test fails at limits_test::a_failing_upload_leaves_nothing_behind: for "save partial.bin from an upload that fails after 2500 bytes; list; regular files in the base directory; read partial.bin" it expected ("Err(Io(..))", Ok([]), 0, Err(NotFound("partial.bin"))) and got ("Err(Io(..))", Ok(["partial.bin"]), 1, Ok(2500)). Here is the design I have decided, public API unchanged. (1) Stop reading at the limit: read through data.take(limit + 1) in a loop with a fixed 64 KiB buffer, count the bytes, and return Err(TooLarge { limit }) as soon as the count passes the limit; exactly limit bytes is accepted; nothing is stored. (2) Never visible while arriving: create a dot-prefixed temporary file in the base with OpenOptions::create_new (".upload-<pid>-<counter>.part" from an AtomicU64), write the chunks into it, and fs::rename it to the final name once every byte is written; a TempFile guard whose Drop removes it unless commit() was called, so TooLarge, a reader error and an I/O error leave nothing and the name stays free. (3) Before creating the temporary file, if symlink_metadata finds anything under the name answer Err(AlreadyExists(name)) and leave it untouched. (4) The type comes from the bytes, for save and list alike: sniff(head) in limits.rs returns image/png for 89 50 4E 47 0D 0A 1A 0A, image/jpeg for FF D8 FF, image/gif for GIF87a or GIF89a, application/pdf for %PDF-, and application/octet-stream for anything else, an empty upload included; the declared type and the extension are ignored, so remove declared_type and type_for_name. save keeps the first 16 bytes of the stream for the sniff; list reads the first 16 bytes of each regular file and skips any entry whose name fails validate_name. Don't change the tests.

    Decide the design yourself and give it whole: when reading stops, how the write stays invisible and clean, and where the type comes from.

    • Direction: Atomic write decided, 8 points
    • Direction: Bounded read decided, 5 points
    • Direction: Honest type decided, 5 points
    • Prompt quality: Specified fix, 8 points
    • Prompt quality: Type rules given, 5 points
  5. Press Test. Every test passes after the last change, your own included.
    • Verification: Run after last change, 6 points
  6. Continue. The stage closes. Scope, the hidden tests and code quality are judged on the final code.
    • Direction: Scope, 5 points
    • Correctness: Hidden tests, 20 points
    • Code quality: Code quality, 10 points

Where the stage lands

Measured when this conversation was played on the platform. A+ needs 92, S needs 95.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 3 · 03-quota

A quota that holds under concurrent uploads

What the ticket asks

A new supplied test file fails on the code you start with: make the quota hold when many uploads arrive at once.

Saves in flight count, a failed save gives back every byte it took, a delete gives back its file's bytes, and files already in the base count from the start.

Where to look

src/quota.rsAdded by this stage: the quota is recorded and never read.
src/store.rssave and delete, where the room is taken, settled and given back.

What the stage pins down

Room before the writesave takes room before it writes, so saves still in flight count; as many uploads succeed as fit and the rest are QuotaExceeded.
Given backA failed save returns every byte it took, a delete returns its file's bytes, and a stored file keeps only its own size.
Many threadsThe store stays Send and Sync: eight threads saving at once never pass the quota and never mix their bytes.

Where the generated store goes wrong

  • The quota is recorded and nothing reads it, so a save past it succeeds.
  • A check of the stored total made after the write, or without a reservation, lets saves in flight pass the quota together.

The fix

  1. Keep the used count behind a mutex in the store and reserve the limit under it before writing.
  2. Release the lock for the copy, settle the reservation to the stored size after the rename, and give it back through a guard on any failure.
  3. Count the files already in the base on first use, and give a deleted file's size back.
src/quota.rsA reservation gives its room back on drop unless it was settled.
+impl Drop for Reservation<'_> {+    fn drop(&mut self) {+        if self.amount > 0 {+            self.quota.give_back(self.amount);+        }+    }+}
src/quota.rsSettling keeps only the bytes actually stored.
+    pub(crate) fn settle(mut self, stored: u64) {+        let mut used = self.quota.used();+        *used = Some(used.unwrap_or(0).saturating_sub(self.amount).saturating_add(stored));+        self.amount = 0;+    }

Tests that prove it

  • Two saves fill the quota, a third is refused, and a delete makes room again.
  • A failed save followed by one that fits, and files already in the base counting.
  • Eight threads released together against a quota of four uploads: exactly four succeed and every file reads back as its own bytes.

The conversation

Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.

DirectionPrompt qualityVerificationCorrectnessCode quality

  1. Press Test. The new supplied test file fails on the start code.
  2. Your message 1

    Stage 3: tests/quota_test.rs fails at quota/past_quota: a third 1 KiB save against a 2 KiB quota succeeds. The cause: with_quota only records the total in self.quota and neither save nor delete ever reads it. Before any change to src/, add stage-3 tests to src/candidate_tests.rs: (a) limit 1 KiB, quota 2 KiB: a.bin and b.bin of 1 KiB are stored, c.bin is Err(QuotaExceeded { quota: 2048 }), and after delete("a.bin") c.bin is Ok with size 1024; (b) with 1 KiB of room left, a 1025-byte save is Err(TooLarge { limit: 1024 }) and a 1 KiB save right after it succeeds; (c) a base that already holds a 1 KiB file written before open, quota 2 KiB: one more 1 KiB save fits and a second is QuotaExceeded; (d) eight threads released by one std::sync::Barrier, each saving 1 KiB of its own byte value with limit 1 KiB and quota 4 KiB: exactly 4 Ok and 4 Err(QuotaExceeded { quota: 4096 }), list sums to 4096, and every stored file reads back as its own bytes. Don't change src/ yet.

    Name the cause, then choose your own cases, a threaded one included, each with the answer the stage expects.

    • Direction: Diagnosis, 5 points
    • Prompt quality: Contract examples, 5 points
    • Prompt quality: Concurrency stated, 4 points
    • Prompt quality: Failure follow-up, 3 points
    • Verification: Named cases, 8 points
  3. Press Test. Still red at the first supplied test.
    • Verification: Checks own, 6 points
  4. Your message 2

    Test fails at quota_test::concurrent_saves_stay_within_the_quota: for "30 rounds of: limit 1 KiB, quota 2 KiB; 4 threads save 1 KiB each at once; rounds whose (stored, QuotaExceeded, other errors, files whose b it expected [] and got [(1, (4, 0, [], [], Ok(4096))), (2, (4, 0, [], [], Ok(4096))), (3, (4, 0, [], [], Ok(4096))), (4, (4, 0, [], [], Ok(4096))), (5, (4, 0, [], . Saves run from several threads at once and the total must never pass the quota while they do, so here is the design I have decided, public API unchanged. In src/quota.rs keep a Quota { total, used: Mutex<Option<u64>> } where used is bytes stored plus bytes reserved by saves in flight (None until the files already in the base are counted), and make the field in lib.rs quota: Option<quota::Quota>, so UploadStore stays Send + Sync and we never re-sum the directory on every save. save takes room before writing: under the lock, reserve the limit (max_bytes), or return Err(QuotaExceeded { quota }) if used + limit would pass the total; release the lock before the copy (no file I/O under it); once the file is renamed into place, settle the reservation to the bytes stored. A Reservation guard whose Drop gives the room back unless settled covers every failure path (TooLarge, a reader error, AlreadyExists, an I/O error). delete gives the deleted file's size back. Files already in the base count: fill used lazily from list() on first use, and in delete take that count before removing the file so it is never subtracted twice. Don't change the tests.

    Decide where the count lives, when room is taken, settled and given back, and why, before the assistant writes it.

    • Direction: Reservation decided, 10 points
    • Direction: Accounting decided, 7 points
    • Direction: Concurrency structure, 3 points
    • Prompt quality: Specified fix, 8 points
  5. Press Test. Every test passes after the last change, your own included.
    • Verification: Run after last change, 6 points
  6. Submit. The last stage closes. Scope, the hidden tests and code quality are judged on the final code.
    • Direction: Scope, 5 points
    • Correctness: Hidden tests, 20 points
    • Code quality: Code quality, 10 points

Where the stage lands

Measured when this conversation was played on the platform. A+ needs 92, S needs 95.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Upload Store Review Solution — Rust Walkthrough | Hunicode