Skip to content

release: v0.0.11 — audit fixes from Cora scan (#221-#231) - #234

Merged
ajianaz merged 1 commit into
developfrom
fix/v0.0.11-audit-fixes
Jun 7, 2026
Merged

ajianaz merged 1 commit into
developfrom
fix/v0.0.11-audit-fixes

Conversation

@ajianaz

@ajianaz ajianaz commented Jun 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

v0.0.11 release — comprehensive fixes from Cora full-project security scan. Closes #221, #222, #225, #226, #228, #229, #231.

Critical Fixes

High Priority Fixes

Medium Priority Fixes

Low Priority Fixes

Other Changes

Test Results

  • 101 tests pass
  • Clippy clean
  • Format clean
  • Cora review: No issues found

Summary by CodeRabbit

  • New Features

    • Added security scanning CI workflow with vulnerability detection
    • Improved error handling with explicit messages for missing CLI arguments
  • Bug Fixes

    • Fixed timestamp calculation inconsistencies for memory aging queries
    • Improved tag operation namespace handling consistency
    • Implemented atomic model file writes to prevent corruption
    • Enhanced path validation for safer /forget operations
    • Improved query parameter parsing robustness
    • Added validation for memory type inputs
    • Strengthened home directory resolution with better error handling
  • Changed

    • Updated security dependency (quinn-proto) for CVE fix

CRITICAL:
- Fix timestamp format mismatch — aging/pruning never worked (RFC3339 vs SQLite datetime)
- aging.rs + bulk.rs now compute cutoffs in Rust using chrono (#221)

HIGH:
- Fix namespace=None inconsistency in tag operations (#222)
- Atomic model file writes (.tmp + rename) (#225)
- uteke_home() returns Result instead of panic (#226)

MEDIUM:
- Exact path matching for DELETE /forget (#228)
- splitn(2,'=') for query param parsing (#228)
- Error on missing --host/--port value (#228)
- Generic 404 message, no path reflection (#228)
- Index lock acquired before SQLite delete in forget() (#231)

LOW:
- Validate memory_type against known variants (#229)

Other:
- Security scanning workflow (cargo audit + Trivy) (#177)
- Error::Generic variant for general errors
- quinn-proto 0.11.12 -> 0.11.14 (CVE-2026-31812)
- Version bump to 0.0.11
- CHANGELOG updated
@ajianaz ajianaz added rust Pull requests that update rust code ci/cd labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This release hardens error handling, file safety, and query logic. uteke_home() now returns Result for safer home-directory resolution; atomic downloads prevent partial model files; timestamp comparisons move from SQLite datetime() to Rust chrono for consistency; tag/namespace queries become explicit; and server request handling gains stricter CLI validation and routing specificity.

Changes

Error Handling and Core API Updates

Layer / File(s) Summary
Error::Generic variant and constructor
crates/uteke-core/src/error.rs
New Error::Generic(String) variant with display formatting and Error::generic() constructor.
uteke_home() returns Result
crates/uteke-core/src/lib.rs
uteke_home() changes from panicking to returning Result<PathBuf, Error>, reading UTEKE_HOME env var first and falling back to dirs::home_dir() with error handling; test updated for new return type.
Callers handle uteke_home() Result
crates/uteke-core/src/maintenance.rs, crates/uteke-server/src/main.rs
doctor(), server startup, and config loading now match on uteke_home() result to proceed or fail gracefully.

File and Data Integrity

Layer / File(s) Summary
Atomic embedding model downloads
crates/uteke-core/src/embed/engine.rs
EmbeddingEngine::new() cleans leftover .tmp files before downloads; download_hf_file() writes to .tmp then renames atomically to final destination with new clean_tmp_files() helper.
Timestamp cutoff computation in Rust
crates/uteke-core/src/memory/aging.rs, crates/uteke-core/src/memory/bulk.rs
find_aged, cleanup_aged, prune_ttl, and find_deprecated_for_prune compute RFC3339 cutoff timestamps in Rust using chrono::Utc::now() and bind cutoff as query parameters instead of relying on SQLite datetime('now', ...).

Query Logic Refinement

Layer / File(s) Summary
Explicit namespace handling in tag operations
crates/uteke-core/src/memory/tags.rs
tags_with_counts, rename_tag, delete_tag, and count_by_tag replace DEFAULT_NAMESPACE fallback with match-based SQL selection; branches run namespace-filtered or unfiltered queries based on whether namespace is provided.
Memory type validation and lock ordering
crates/uteke-core/src/operations.rs
remember_typed validates memory_type against known variants; forget acquires vector index lock before deleting from store to reduce inconsistency window.

Server Request and CLI Handling

Layer / File(s) Summary
DELETE /forget routing and query parsing
crates/uteke-server/src/main.rs
/forget route matches explicitly with optional query string; query param parsing uses splitn(2, '=') for safe key/value extraction; catch-all 404 returns generic message instead of requested path.
CLI argument validation
crates/uteke-server/src/main.rs
Added explicit error handling when --host or --port flags lack following values; process exits with error message.

Release Documentation

Layer / File(s) Summary
Version bump and changelog
Cargo.toml, CHANGELOG.md
Workspace version incremented to 0.0.11; changelog documents fixes, additions (security CI workflow, quinn-proto CVE fix, Error::Generic), and changed behaviors.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • ajianaz/uteke#226: Directly related; this PR fully implements the conversion of uteke_home() from panicking to returning Result<PathBuf, Error> and updates all callers.
  • ajianaz/uteke#229: Directly related; this PR implements the requested memory-type validation in remember_typed using MemoryType::from_str_opt.
  • ajianaz/uteke#221: Directly related; this PR addresses the timestamp format mismatch by moving cutoff computation from SQLite datetime() expressions to Rust chrono::Utc::now() across aging and bulk memory modules.

Possibly related PRs

  • ajianaz/uteke#220: Both PRs include the same security scanning GitHub Actions workflow and quinn-proto version bump.
  • ajianaz/uteke#186: This PR directly refactors methods (find_aged, cleanup_aged, prune_ttl, find_deprecated_for_prune, namespace-based tag queries) that were introduced in the earlier store-module split.
  • ajianaz/uteke#196: Both PRs adjust vector index lock timing around SQLite-backed memory operations in operations.rs.

Suggested labels

security

Poem

🐰 With atomicity and care we write,
Home directories no longer panic in fright,
Timestamps in Rust, not SQLite's whim,
And queries explicit, namespaces trim! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically identifies the main purpose as a release (v0.0.11) with audit fixes from a security scan, directly matching the PR's objective of releasing fixes from a Cora audit covering issues #221-#231.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/v0.0.11-audit-fixes

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 7, 2026

Copy link
Copy Markdown

🔍 Cora AI Code Review

❌ Blocked — critical issues found.

🔴 Error (1)

  • crates/uteke-core/src/embed/engine.rs:178 — std::fs::rename fails if the source and destination are on different filesystems. If the .tmp file is created in the same directory as the target (which it is here, via with_extension), this should be fine. However, the clean_tmp_files function only checks .tmp extension, which could accidentally delete unrelated .tmp files from other tools or processes.

Review powered by cora-cli · BYOK · MIT

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
crates/uteke-server/src/main.rs (1)

359-367: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle flag-like tokens as missing values for --host/--port.

On Line 361 and Line 370, the parser only checks bounds. Inputs like --host --port 9000 incorrectly treat --port as the host value instead of triggering the missing-value error path.

Proposed fix
         match args[i].as_str() {
             "--host" => {
                 i += 1;
-                if i < args.len() {
+                if i < args.len() && !args[i].starts_with('-') {
                     cli_host = Some(args[i].clone());
                 } else {
                     eprintln!("Error: --host requires a value");
                     std::process::exit(1);
                 }
             }
             "--port" => {
                 i += 1;
-                if i < args.len() {
+                if i < args.len() && !args[i].starts_with('-') {
                     cli_port = Some(args[i].parse().unwrap_or_else(|e| {
                         eprintln!("Invalid port: {e}");
                         std::process::exit(1);
                     }));
                 } else {
                     eprintln!("Error: --port requires a value");
                     std::process::exit(1);
                 }
             }

Also applies to: 368-379

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/uteke-server/src/main.rs` around lines 359 - 367, The current argument
parsing for the "--host" and "--port" branches (where cli_host and cli_port are
set) only checks index bounds and therefore treats flag-like tokens (e.g.,
"--port") as values; update both branches to additionally verify that args[i] is
not a flag (e.g., starts_with('-')) before accepting it as the value, and if it
is a flag-like token, emit the existing missing-value error and exit; locate the
"--host" and "--port" handling blocks in main.rs and add this extra check when
assigning cli_host and cli_port.
crates/uteke-core/src/operations.rs (1)

35-46: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Normalize memory_type after validation.

Line 36 accepts case-insensitive input, but Line 46 still passes the raw string through, so "Fact"/"FACT" will be stored verbatim later instead of the canonical lowercase values defined by MemoryType::as_str(). That leaves mixed memory_type values in storage even though this change is meant to constrain them to known variants.

Proposed fix
-        crate::memory::types::MemoryType::from_str_opt(memory_type).ok_or_else(|| {
-            Error::Validation(format!(
-                "Unknown memory type '{memory_type}'. Valid types: fact, procedure, preference, decision, context"
-            ))
-        })?;
+        let memory_type = crate::memory::types::MemoryType::from_str_opt(memory_type)
+            .ok_or_else(|| {
+                Error::Validation(format!(
+                    "Unknown memory type '{memory_type}'. Valid types: fact, procedure, preference, decision, context"
+                ))
+            })?
+            .as_str();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/uteke-core/src/operations.rs` around lines 35 - 46, After validating
memory_type via MemoryType::from_str_opt, convert it to the canonical lowercase
form (use the matched enum's MemoryType::as_str()) and pass that normalized
string into remember_precomputed instead of the original raw input; update the
code path around MemoryType::from_str_opt and the subsequent call to
remember_precomputed (the block that obtains embedding via
self.embedder.lock().map_err(...).embed(...)) so the normalized value is used.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@CHANGELOG.md`:
- Line 10: The changelog entry "## [0.0.11] — 2026-06-07" is using
reference-link style but the corresponding link definition is missing; add a
reference link definition for "[0.0.11]" at the bottom of CHANGELOG.md (and
add/update the "[Unreleased]" reference if your repo uses it) that points to the
release or compare URL for the 0.0.11 tag (e.g., a GitHub compare or release
URL), ensuring the identifier matches the heading exactly so the reference
resolves.

In `@crates/uteke-core/src/memory/aging.rs`:
- Around line 33-37: find_aged() and cleanup_aged() (in aging.rs) each compute
their own cutoff causing boundary races; change the API so the caller computes a
single cutoff once (e.g., in maintenance.rs) and passes it into both operations,
or add a shared helper (e.g., find_and_cleanup_aged_with_cutoff(cutoff: String)
or a helper that accepts chrono::DateTime<Utc>) that both preview (vector-index
removal via find_aged) and delete (cleanup_aged) call with the same cutoff;
update function signatures for find_aged and cleanup_aged to accept the cutoff
parameter and adjust callers in maintenance.rs to compute cutoff via
(chrono::Utc::now() - Duration::days(older_than_days)).to_rfc3339() (or pass
DateTime) and forward it to both operations.

In `@crates/uteke-core/src/memory/bulk.rs`:
- Around line 110-118: find_deprecated_for_prune() and prune_ttl() each compute
their own UTC cutoff which causes mismatched selection vs deletion around the
TTL boundary; compute a single cutoff once (e.g., let cutoff =
chrono::Utc::now() - chrono::Duration::days(ttl_days as i64) or its RFC3339
string) and thread that same value into both functions instead of having them
call Utc::now() internally—update the signatures of
find_deprecated_for_prune(...) and prune_ttl(...) to accept the cutoff
(DateTime<Utc> or &str) and change the call sites in maintenance.rs to compute
cutoff once and pass it into both calls so the IDs selected and the rows deleted
use the identical cutoff.

---

Outside diff comments:
In `@crates/uteke-core/src/operations.rs`:
- Around line 35-46: After validating memory_type via MemoryType::from_str_opt,
convert it to the canonical lowercase form (use the matched enum's
MemoryType::as_str()) and pass that normalized string into remember_precomputed
instead of the original raw input; update the code path around
MemoryType::from_str_opt and the subsequent call to remember_precomputed (the
block that obtains embedding via self.embedder.lock().map_err(...).embed(...))
so the normalized value is used.

In `@crates/uteke-server/src/main.rs`:
- Around line 359-367: The current argument parsing for the "--host" and
"--port" branches (where cli_host and cli_port are set) only checks index bounds
and therefore treats flag-like tokens (e.g., "--port") as values; update both
branches to additionally verify that args[i] is not a flag (e.g.,
starts_with('-')) before accepting it as the value, and if it is a flag-like
token, emit the existing missing-value error and exit; locate the "--host" and
"--port" handling blocks in main.rs and add this extra check when assigning
cli_host and cli_port.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 890c6b44-4131-423f-85b8-ccd7b6776375

📥 Commits

Reviewing files that changed from the base of the PR and between 6297968 and 34d6a84.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • CHANGELOG.md
  • Cargo.toml
  • crates/uteke-core/src/embed/engine.rs
  • crates/uteke-core/src/error.rs
  • crates/uteke-core/src/lib.rs
  • crates/uteke-core/src/maintenance.rs
  • crates/uteke-core/src/memory/aging.rs
  • crates/uteke-core/src/memory/bulk.rs
  • crates/uteke-core/src/memory/tags.rs
  • crates/uteke-core/src/operations.rs
  • crates/uteke-server/src/main.rs

Comment thread CHANGELOG.md

## [Unreleased]

## [0.0.11] — 2026-06-07

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add missing changelog reference links for the new heading.

## [0.0.11] uses reference-link style, but [0.0.11] (and typically [Unreleased]) link definitions are missing at the bottom, so this entry won’t resolve to a release URL.

Suggested patch
+[Unreleased]: https://github.com/ajianaz/uteke/compare/v0.0.11...HEAD
+[0.0.11]: https://github.com/ajianaz/uteke/releases/tag/v0.0.11
 [0.0.10]: https://github.com/ajianaz/uteke/releases/tag/v0.0.10
 [0.0.9]: https://github.com/ajianaz/uteke/releases/tag/v0.0.9
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CHANGELOG.md` at line 10, The changelog entry "## [0.0.11] — 2026-06-07" is
using reference-link style but the corresponding link definition is missing; add
a reference link definition for "[0.0.11]" at the bottom of CHANGELOG.md (and
add/update the "[Unreleased]" reference if your repo uses it) that points to the
release or compare URL for the 0.0.11 tag (e.g., a GitHub compare or release
URL), ensuring the identifier matches the heading exactly so the reference
resolves.

Comment on lines +33 to +37
// Compute cutoffs in Rust using chrono (RFC3339) to match stored timestamp format.
// SQLite datetime('now') returns a different format than our RFC3339 strings,
// causing lexicographic comparison to fail.
let cutoff =
(chrono::Utc::now() - chrono::Duration::days(older_than_days as i64)).to_rfc3339();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Share a single aging cutoff across preview and delete.

Lines 33-37 and Lines 77-78 now compute cutoff independently, but crates/uteke-core/src/maintenance.rs first calls find_aged() to collect IDs for vector-index removal and then calls cleanup_aged() to delete from SQLite. A record near the boundary can fall into only one of those two queries, which leaves SQLite and the vector index out of sync. Compute the cutoff once in the caller and pass it through both operations, or route both methods through a shared helper that accepts an explicit cutoff.

Also applies to: 77-78

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/uteke-core/src/memory/aging.rs` around lines 33 - 37, find_aged() and
cleanup_aged() (in aging.rs) each compute their own cutoff causing boundary
races; change the API so the caller computes a single cutoff once (e.g., in
maintenance.rs) and passes it into both operations, or add a shared helper
(e.g., find_and_cleanup_aged_with_cutoff(cutoff: String) or a helper that
accepts chrono::DateTime<Utc>) that both preview (vector-index removal via
find_aged) and delete (cleanup_aged) call with the same cutoff; update function
signatures for find_aged and cleanup_aged to accept the cutoff parameter and
adjust callers in maintenance.rs to compute cutoff via (chrono::Utc::now() -
Duration::days(older_than_days)).to_rfc3339() (or pass DateTime) and forward it
to both operations.

Comment on lines +110 to +118
// Compute cutoff in Rust (RFC3339) to match stored timestamp format.
let cutoff = (chrono::Utc::now() - chrono::Duration::days(ttl_days as i64)).to_rfc3339();
let deleted = self
.conn
.execute(
"DELETE FROM memories WHERE namespace = ?1
AND deprecated = 1
AND datetime(updated_at) < datetime('now', '-' || ?2 || ' days')",
params![ns, ttl_days],
AND updated_at < ?2",
params![ns, cutoff],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Use one TTL cutoff for both prune selection and prune deletion.

find_deprecated_for_prune() and prune_ttl() now generate their own Utc::now() cutoffs, but crates/uteke-core/src/maintenance.rs uses the first call’s IDs to clean the vector index after the second call deletes from SQLite. That makes the selected set and deleted set drift at the TTL boundary, which can orphan index entries or remove still-live IDs from the index. Please thread a single cutoff through both queries.

Also applies to: 131-143

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/uteke-core/src/memory/bulk.rs` around lines 110 - 118,
find_deprecated_for_prune() and prune_ttl() each compute their own UTC cutoff
which causes mismatched selection vs deletion around the TTL boundary; compute a
single cutoff once (e.g., let cutoff = chrono::Utc::now() -
chrono::Duration::days(ttl_days as i64) or its RFC3339 string) and thread that
same value into both functions instead of having them call Utc::now()
internally—update the signatures of find_deprecated_for_prune(...) and
prune_ttl(...) to accept the cutoff (DateTime<Utc> or &str) and change the call
sites in maintenance.rs to compute cutoff once and pass it into both calls so
the IDs selected and the rows deleted use the identical cutoff.

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

Labels

rust Pull requests that update rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 [CRITICAL] Timestamp format mismatch — aging/pruning never works

1 participant