diff --git a/.gitea/workflows/test-and-lint.yaml b/.gitea/workflows/test-and-lint.yaml new file mode 100644 index 0000000..8cfbd4b --- /dev/null +++ b/.gitea/workflows/test-and-lint.yaml @@ -0,0 +1,31 @@ +name: Test and Lint + +on: + push: + branches: + - main + - "attempt/*" + pull_request: + branches: + - main + +jobs: + quality: + runs-on: fedora + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Build container image + run: make image + + - name: Check formatting (rustfmt) + run: make fmt-check + + - name: Check compilation and clippy + run: make check-all && make clippy-all + + - name: Run test suite progress report (attempt branches) + if: startsWith(github.ref, 'refs/heads/attempt/') + continue-on-error: true + run: make test-all diff --git a/Cargo.lock b/Cargo.lock index a775eaf..975cf18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,19 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "anstream" version = "1.0.0" @@ -110,12 +123,40 @@ dependencies = [ "tracing", ] +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + [[package]] name = "bytes" version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + [[package]] name = "clap" version = "4.6.10" @@ -147,7 +188,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -241,6 +282,13 @@ dependencies = [ "serde_json", ] +[[package]] +name = "eco05-sql-sqlite" +version = "0.1.0" +dependencies = [ + "rusqlite", +] + [[package]] name = "eng01-ai-code-audit" version = "0.1.0" @@ -261,6 +309,28 @@ version = "0.1.0" name = "eng05-testing-types-and-mutation" version = "0.1.0" +[[package]] +name = "eng06-security-appsec" +version = "0.1.0" + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + [[package]] name = "form_urlencoded" version = "1.2.3" @@ -294,6 +364,37 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + [[package]] name = "heck" version = "0.5.0" @@ -379,6 +480,17 @@ dependencies = [ "tower-service", ] +[[package]] +name = "incident-tracker" +version = "0.1.0" +dependencies = [ + "clap", + "rusqlite", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -391,12 +503,33 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "log" version = "0.4.35" @@ -456,6 +589,12 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -474,6 +613,32 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "ryu" version = "1.0.23" @@ -507,7 +672,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -546,6 +711,12 @@ dependencies = [ "serde", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "slab" version = "0.4.12" @@ -574,6 +745,17 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -608,7 +790,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -633,7 +815,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -696,12 +878,68 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -717,6 +955,26 @@ dependencies = [ "windows-link", ] +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 93c1cdc..16139a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "exercises/01-core/*", "exercises/02-engineering-2026/*", "exercises/03-ecosystems/*", + "projects/*", ] default-members = [ "exercises/01-core/*", diff --git a/Makefile b/Makefile index aa3cd4d..5f0738c 100644 --- a/Makefile +++ b/Makefile @@ -9,16 +9,17 @@ RUN_CONTAINER = $(ENGINE) run --rm \ -w /workspace \ $(IMAGE) -.PHONY: help image check check-all test test-all clippy clippy-all fmt fmt-check shell clean +.PHONY: help image check check-all test test-project test-all clippy clippy-all fmt fmt-check shell clean help: @echo "Dostępne komendy:" @echo " make image - Zbuduj obraz kontenera Rust (jednorazowo)" @echo " make check - Szybki check 01-core + 02-engineering-2026 (czyste std)" - @echo " make check-all - Pełny check całego workspace (razem z 03-ecosystems)" + @echo " make check-all - Pełny check całego workspace (razem z 03-ecosystems i projects)" @echo " make test PKG=core01-basics - Uruchom testy wybranego rozdziału" @echo " make test - Uruchom testy domyślnych ścieżek (01 + 02)" - @echo " make test-all - Uruchom testy całego workspace (01 + 02 + 03)" + @echo " make test-project - Uruchom testy mini-projektu incident-tracker" + @echo " make test-all - Uruchom testy całego workspace" @echo " make clippy - Linter Clippy dla 01-core + 02-engineering-2026" @echo " make clippy-all - Linter Clippy dla całego workspace" @echo " make fmt - Sformatuj kod (rustfmt)" @@ -42,6 +43,9 @@ else $(RUN_CONTAINER) cargo test endif +test-project: + $(RUN_CONTAINER) cargo test -p incident-tracker -- --nocapture + test-all: $(RUN_CONTAINER) cargo test --workspace diff --git a/README.md b/README.md index 4b16235..46937f2 100644 --- a/README.md +++ b/README.md @@ -55,12 +55,17 @@ make fmt - [ ] `eng03-cross-platform` — [03-cross-platform](exercises/02-engineering-2026/03-cross-platform/README.md): Linux / Windows / macOS (`PathBuf`, `#[cfg(target_os)]`) - [ ] `eng04-best-practices` — [04-best-practices](exercises/02-engineering-2026/04-best-practices/README.md): `Display`, `Error`, `From`, brak panik na granicach - [ ] `eng05-testing-types-and-mutation` — [05-testing-types-and-mutation](exercises/02-engineering-2026/05-testing-types-and-mutation/README.md): testy jednostkowe, integracyjne i mutacyjne (zabijanie mutantów) +- [ ] `eng06-security-appsec` — [06-security-appsec](exercises/02-engineering-2026/06-security-appsec/README.md): bezpieczeństwo kodu (Path Traversal, redakcja sekretów) ### Ścieżka 3: `03-ecosystems/` — CLI, Web, Mobile/Desktop i WASM - [ ] `eco01-cli-clap` — [01-cli-clap](exercises/03-ecosystems/01-cli-clap/README.md): parsowanie argumentów CLI z `clap` - [ ] `eco02-web-backend-axum` — [02-web-backend-axum](exercises/03-ecosystems/02-web-backend-axum/README.md): REST API w `axum` + `tokio` + `serde` - [ ] `eco03-shared-core-ffi` — [03-shared-core-ffi](exercises/03-ecosystems/03-shared-core-ffi/README.md): wspólny rdzeń pod iOS/Android (`UniFFI`) i Desktop (`Tauri`) z `thiserror` - [ ] `eco04-wasm-logic` — [04-wasm-logic](exercises/03-ecosystems/04-wasm-logic/README.md): moduł logiki pod WebAssembly (Frontend) +- [ ] `eco05-sql-sqlite` — [05-sql-sqlite](exercises/03-ecosystems/05-sql-sqlite/README.md): SQL i SQLite (`rusqlite`, ochrona przed SQLi) + +### Mini-Projekt Końcowy (Capstone): `projects/incident-tracker/` +- [ ] `incident-tracker` — [README](projects/incident-tracker/README.md): pełna aplikacja SRE (CLI `clap` + SQLite + JSON + testy, `make test-project`) --- @@ -73,6 +78,10 @@ make fmt * [03 — Algorytmy i złożoność obliczeniowa w Ruście (Big-O)](notes/03-algorithms-and-complexity.md) * [04 — Rodzaje testów w Ruście: jednostkowe, integracyjne, mutacyjne, doctesty](notes/04-testing-pyramid-and-types.md) * [05 — Efektywny debugging i czytanie błędów `rustc` i borrow checkera](notes/05-debugging-and-reading-errors.md) +* [06 — SQL i Bazy Danych w Ruście (`rusqlite`, `sqlx`, SQLite, PostgreSQL)](notes/06-sql-and-databases.md) +* [07 — Bezpieczeństwo Kodu w Ruście (AppSec & OWASP)](notes/07-appsec-and-secure-coding.md) +* [08 — Git w Korpo i Architektura Aplikacji w Ruście](notes/08-git-workflow-and-architecture.md) +* [99 — Dziennik Błędów i System Powtórek](notes/99-mistakes-log.md) ## Nauka z asystentem AI (metoda sokratejska i era 2026) diff --git a/exercises/02-engineering-2026/06-security-appsec/Cargo.toml b/exercises/02-engineering-2026/06-security-appsec/Cargo.toml new file mode 100644 index 0000000..74e5180 --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "eng06-security-appsec" +version = "0.1.0" +edition = "2021" diff --git a/exercises/02-engineering-2026/06-security-appsec/README.md b/exercises/02-engineering-2026/06-security-appsec/README.md new file mode 100644 index 0000000..74996ee --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/README.md @@ -0,0 +1,12 @@ +# 06 — Bezpieczeństwo Kodu (AppSec: Path Traversal, Redakcja Sekretów) + +Teoria: [notes/07-appsec-and-secure-coding.md](../../../notes/07-appsec-and-secure-coding.md) + +## Zadania (`src/lib.rs`) +1. `safe_join(base_dir: &Path, relative_path: &str) -> Result` — odrzuć ścieżki absolutne (`Path::is_absolute`) oraz zawierające `Component::ParentDir` (`..`), w przeciwnym razie zwróć `Ok(base_dir.join(relative_path))`. +2. `redact_secrets(log_line: &str) -> String` — zamaskuj wartości po `Bearer `, `token=` oraz `password=` na `***`. + +## Uruchomienie testów +```bash +make test PKG=eng06-security-appsec +``` diff --git a/exercises/02-engineering-2026/06-security-appsec/src/lib.rs b/exercises/02-engineering-2026/06-security-appsec/src/lib.rs new file mode 100644 index 0000000..95f9066 --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/src/lib.rs @@ -0,0 +1,50 @@ +#![allow(unused_variables, dead_code)] + +use std::path::{Component, Path, PathBuf}; + +#[derive(Debug, PartialEq, Eq)] +pub enum SecurityError { + PathTraversal, +} + +pub fn safe_join(base_dir: &Path, relative_path: &str) -> Result { + let _ = Component::ParentDir; + todo!("Odrzuć ścieżki absolutne i zawierające Component::ParentDir jako PathTraversal") +} + +pub fn redact_secrets(log_line: &str) -> String { + todo!("Zamień tokeny po 'Bearer ', 'token=' i 'password=' na '***'") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocks_path_traversal() { + let base = Path::new("/srv/app"); + assert_eq!( + safe_join(base, "configs/app.toml"), + Ok(base.join("configs/app.toml")) + ); + assert_eq!( + safe_join(base, "../../etc/passwd"), + Err(SecurityError::PathTraversal) + ); + assert_eq!( + safe_join(base, "/etc/passwd"), + Err(SecurityError::PathTraversal) + ); + } + + #[test] + fn redacts_secrets_from_logs() { + let line = + "auth failed header=Bearer s3cr3tTok3n user=admin password=hunter2 token=abc_123"; + let cleaned = redact_secrets(line); + assert!(!cleaned.contains("s3cr3tTok3n")); + assert!(!cleaned.contains("hunter2")); + assert!(!cleaned.contains("abc_123")); + assert!(cleaned.contains("user=admin")); + } +} diff --git a/exercises/03-ecosystems/05-sql-sqlite/Cargo.toml b/exercises/03-ecosystems/05-sql-sqlite/Cargo.toml new file mode 100644 index 0000000..c58ffea --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "eco05-sql-sqlite" +version = "0.1.0" +edition = "2021" + +[dependencies] +rusqlite = { version = "0.32", features = ["bundled"] } diff --git a/exercises/03-ecosystems/05-sql-sqlite/README.md b/exercises/03-ecosystems/05-sql-sqlite/README.md new file mode 100644 index 0000000..941b98b --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/README.md @@ -0,0 +1,14 @@ +# 05 — SQL i SQLite (`rusqlite`, parametryzowane zapytania, ochrona przed SQLi) + +Teoria: [notes/06-sql-and-databases.md](../../../notes/06-sql-and-databases.md) + +## Zadania (`src/lib.rs`) +Zaimplementuj `ServiceRegistry` na `rusqlite`: +1. `init_schema(&self) -> rusqlite::Result<()>` — `CREATE TABLE IF NOT EXISTS services(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, owner TEXT NOT NULL)`. +2. `register(&self, name: &str, owner: &str) -> rusqlite::Result` — parametryzowany `INSERT` (`params![name, owner]`) i `self.conn.last_insert_rowid()`. +3. `find_by_owner(&self, owner: &str) -> rusqlite::Result>` — posortowana lista nazw bez podatności na SQL Injection. + +## Uruchomienie testów +```bash +make test PKG=eco05-sql-sqlite +``` diff --git a/exercises/03-ecosystems/05-sql-sqlite/src/lib.rs b/exercises/03-ecosystems/05-sql-sqlite/src/lib.rs new file mode 100644 index 0000000..9f58f88 --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/src/lib.rs @@ -0,0 +1,63 @@ +#![allow(unused_variables, dead_code)] + +use rusqlite::{params, Connection}; +use std::path::Path; + +pub struct ServiceRegistry { + conn: Connection, +} + +impl ServiceRegistry { + pub fn open(path: &Path) -> rusqlite::Result { + Ok(Self { + conn: Connection::open(path)?, + }) + } + + pub fn init_schema(&self) -> rusqlite::Result<()> { + todo!("Utwórz tabelę services przez self.conn.execute_batch(...)") + } + + pub fn register(&self, name: &str, owner: &str) -> rusqlite::Result { + let _ = params![name, owner]; + todo!("Wstaw rekord parametryzowanym INSERT i zwróć self.conn.last_insert_rowid()") + } + + pub fn find_by_owner(&self, owner: &str) -> rusqlite::Result> { + todo!("Parametryzowany SELECT name FROM services WHERE owner = ?1 ORDER BY name ASC") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::time::{SystemTime, UNIX_EPOCH}; + + #[test] + fn sqlite_crud_and_sqli_resistance() { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let db = std::env::temp_dir().join(format!("rust-learning-reg-{nanos}.db")); + + let reg = ServiceRegistry::open(&db).unwrap(); + reg.init_schema().unwrap(); + let id1 = reg.register("billing-api", "team-core").unwrap(); + let id2 = reg.register("auth-api", "team-core").unwrap(); + reg.register("metrics-proxy", "team-sre").unwrap(); + + assert!(id1 > 0 && id2 > id1); + assert_eq!( + reg.find_by_owner("team-core").unwrap(), + vec![String::from("auth-api"), String::from("billing-api")] + ); + + // Negative security assertion: SQLi payload must NOT return all rows + assert!(reg.find_by_owner("' OR '1'='1").unwrap().is_empty()); + + drop(reg); + let _ = fs::remove_file(&db); + } +} diff --git a/notes/06-sql-and-databases.md b/notes/06-sql-and-databases.md new file mode 100644 index 0000000..b738282 --- /dev/null +++ b/notes/06-sql-and-databases.md @@ -0,0 +1,29 @@ +# SQL i Bazy Danych w Ruście (`rusqlite`, `sqlx`, SQLite, PostgreSQL) + +SQL pojawia się w **~22% wszystkich ofert IT w Polsce**. W Ruście dwa główne narzędzia to **`rusqlite`** (synchroniczny SQLite, świetny do CLI i narzędzi lokalnych) oraz **`sqlx`** (asynchroniczny SQL z weryfikacją zapytań w czasie kompilacji pod PostgreSQL/SQLite/MySQL). + +--- + +## 1. Podstawy SQL i `rusqlite` + +```sql +CREATE TABLE IF NOT EXISTS incidents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + severity TEXT NOT NULL CHECK (severity IN ('low', 'medium', 'high', 'critical')), + status TEXT NOT NULL DEFAULT 'open' +); +CREATE INDEX IF NOT EXISTS idx_incidents_status_sev ON incidents(status, severity); +``` + +## 2. Zawsze parametryzowane zapytania (`params![]`) +```rust +// ŹLE (SQL Injection!): +conn.execute(&format!("DELETE FROM services WHERE name = '{input}'"), [])?; + +// DOBRZE (parametryzowane zapytanie): +conn.execute("DELETE FROM services WHERE name = ?1", params![input])?; +``` + +## 3. Transakcje ACID +W `rusqlite` używasz `let tx = conn.transaction()?;` — jeśli transakcja wyjdzie poza zakres (*drop*) bez wywołania `tx.commit()?`, Rust **automatycznie robi `ROLLBACK`** (wzorzec RAII)! diff --git a/notes/07-appsec-and-secure-coding.md b/notes/07-appsec-and-secure-coding.md new file mode 100644 index 0000000..b2aeaf7 --- /dev/null +++ b/notes/07-appsec-and-secure-coding.md @@ -0,0 +1,17 @@ +# Bezpieczeństwo Kodu w Ruście (AppSec & OWASP w praktyce) + +Rust chroni przed większością błędów pamięci (*memory safety*), ale **nie chroni automatycznie przed błędami logiki i OWASP** (SQLi, Command Injection, Path Traversal, IDOR, wyciek sekretów)! + +| Podatność | Jak wygląda błąd w Ruście | Jak się zabezpieczyć | +| :--- | :--- | :--- | +| **SQL Injection** | `format!("SELECT ... '{}'", input)` | Zawsze `params![input]` / bindy w `sqlx`. | +| **Command Injection** | `Command::new("sh").arg("-c").arg(format!("ls {input}"))` | `Command::new("ls").arg(input)` bez powłoki `sh -c`. | +| **Path Traversal (`../`)** | `base.join(user_path)` bez sprawdzenia komponentów `..` / ścieżki absolutnej. | Znormalizuj/zweryfikuj komponenty (`Component::ParentDir`, `is_absolute()`) lub `canonicalize` + `starts_with`. | +| **Wyciek sekretów** | Tokeny w logach `tracing`, brak redakcji `Debug` dla kluczy API. | Redakcja sekretów (`Bearer ***`), własna implementacja `fmt::Debug` wypisująca `[REDACTED]`, skanowanie `gitleaks`. | +| **Paniki na wejściu użytkownika** | `.unwrap()` / indeksowanie `slice[i]` na niezaufanych danych (DoS!). | Zawsze `Result` / `Option` / `.get(i)` na granicach API. | + +## Higiena łańcucha dostaw (Supply Chain) +* **Podatności CVE w Ruście:** `cargo audit` (baza RustSec). +* **Sekrety w Gicie:** `gitleaks detect --source .` + +Praktyczne zadania znajdziesz w [exercises/02-engineering-2026/06-security-appsec](../exercises/02-engineering-2026/06-security-appsec/README.md). diff --git a/notes/08-git-workflow-and-architecture.md b/notes/08-git-workflow-and-architecture.md new file mode 100644 index 0000000..691347c --- /dev/null +++ b/notes/08-git-workflow-and-architecture.md @@ -0,0 +1,12 @@ +# Git w Korpo i Architektura Aplikacji w Ruście + +## 1. Git Workflow w międzynarodowych zespołach +* **Atomowe commity** + **Conventional Commits** (`feat:`, `fix:`, `refactor:`, `test:`, `docs:`, `chore:`). +* **`merge` vs `rebase`:** `rebase` tylko na lokalnych gałęziach roboczych; nigdy na współdzielonym `main`. +* **`git bisect`:** binarne wyszukiwanie commita winnego regresji w `O(log n)` krokach. +* **Checklista PR:** własny `git diff`, zielone `make check-all && make clippy-all && make fmt-check`, brak sekretów i `dbg!()`, opis: **Co / Dlaczego / Jak przetestowano**. + +## 2. Architektura w Ruście: oddzielenie domeny od I/O (Ports & Adapters) +* Trzymaj logikę domenową w czystej bibliotece (`lib.rs`) bez twardych zależności od CLI/HTTP/dysku. +* Granice definiuj traitami (porty) i podpinaj konkretne adaptery (`rusqlite`, `axum`, `clap`) w cienkiej warstwie wejściowej. +* Dokładnie ten wzorzec przećwiczysz w mini-projekcie `projects/incident-tracker/`. diff --git a/notes/99-mistakes-log.md b/notes/99-mistakes-log.md new file mode 100644 index 0000000..f6a3add --- /dev/null +++ b/notes/99-mistakes-log.md @@ -0,0 +1,12 @@ +# Dziennik Błędów i System Powtórek (Spaced Repetition) + +Zapisuj błędy kompilatora (`E0382`, `E0502`, lifetimes) i logiczne, na których utknąłeś, i wracaj do nich po: **+1 dzień → +3 dni → +7 dni → +30 dni**. + +| Data | Rozdział | Co poszło nie tak (objaw / kod `rustc`) | Przyczyna źródłowa (*root cause*) | Zasada na przyszłość | Powtórka (+3d / +7d) | +| :--- | :--- | :--- | :--- | :--- | :--- | +| *przykład* | `01-core/02-ownership` | `E0382: borrow of moved value` | Przekazanie `String` przez wartość zamiast `&str` | W sygnaturach przyjmuj `&str`, gdy nie potrzebujesz własności | `[ ]` `[ ]` | + +## Retrospektywa po ukończeniu ścieżki +1. Który koncept (np. ownership, lifetimes, `Result`) sprawił największą trudność? +2. Jakie 2–3 błędy powtarzały się najczęściej? +3. Co zrobiłbym inaczej w kolejnej gałęzi `attempt/`? diff --git a/notes/README.md b/notes/README.md index aa33d4b..969e88a 100644 --- a/notes/README.md +++ b/notes/README.md @@ -6,3 +6,7 @@ * [03 — Algorytmy i złożoność obliczeniowa w Ruście (Big-O)](03-algorithms-and-complexity.md) * [04 — Rodzaje testów w Ruście: jednostkowe, integracyjne, mutacyjne, doctesty](04-testing-pyramid-and-types.md) * [05 — Efektywny debugging i czytanie błędów `rustc` i borrow checkera](05-debugging-and-reading-errors.md) +* [06 — SQL i Bazy Danych w Ruście (`rusqlite`, `sqlx`, SQLite, PostgreSQL)](06-sql-and-databases.md) +* [07 — Bezpieczeństwo Kodu w Ruście (AppSec & OWASP)](07-appsec-and-secure-coding.md) +* [08 — Git w Korpo i Architektura Aplikacji w Ruście](08-git-workflow-and-architecture.md) +* [99 — Dziennik Błędów i System Powtórek](99-mistakes-log.md) diff --git a/projects/incident-tracker/Cargo.toml b/projects/incident-tracker/Cargo.toml new file mode 100644 index 0000000..a3feb2d --- /dev/null +++ b/projects/incident-tracker/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "incident-tracker" +version = "0.1.0" +edition = "2021" + +[dependencies] +clap = { version = "4", features = ["derive"] } +rusqlite = { version = "0.32", features = ["bundled"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" diff --git a/projects/incident-tracker/README.md b/projects/incident-tracker/README.md new file mode 100644 index 0000000..61bb822 --- /dev/null +++ b/projects/incident-tracker/README.md @@ -0,0 +1,12 @@ +# Capstone Mini-Projekt: `incident-tracker` (CLI `clap` + SQLite + JSON) + +Ten sam projekt SRE realizujesz w Pythonie, Go i Ruście, żeby porównać ergonomię i architekturę wszystkich trzech języków. + +## Wymagania (`src/lib.rs`) +1. `IncidentStore` na `rusqlite`: `init_schema`, `add(title, severity)`, `list(severity)`, `resolve(id)`, `stats()`. +2. `run_cli(db_path: &Path, args: &[&str]) -> Result` — parsuje podkomendy `add --severity <sev>`, `list [--severity <sev>]`, `resolve <id>`, `stats` przez `clap` i zwraca wynik jako JSON `String`. + +## Uruchomienie testów +```bash +make test-project +``` diff --git a/projects/incident-tracker/src/lib.rs b/projects/incident-tracker/src/lib.rs new file mode 100644 index 0000000..f65c409 --- /dev/null +++ b/projects/incident-tracker/src/lib.rs @@ -0,0 +1,165 @@ +#![allow(unused_variables, dead_code)] + +use clap::{Parser, Subcommand}; +use rusqlite::{params, Connection}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::Path; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum TrackerError { + #[error("invalid incident input: {0}")] + InvalidInput(String), + #[error("incident {0} not found")] + NotFound(i64), + #[error("database error: {0}")] + Db(#[from] rusqlite::Error), + #[error("cli error: {0}")] + Cli(String), + #[error("json error: {0}")] + Json(#[from] serde_json::Error), +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Incident { + pub id: i64, + pub title: String, + pub severity: String, + pub status: String, +} + +#[derive(Debug, Parser)] +#[command(name = "incident-tracker")] +pub struct Cli { + #[command(subcommand)] + pub command: Command, +} + +#[derive(Debug, Subcommand)] +pub enum Command { + Add { + title: String, + #[arg(long, default_value = "medium")] + severity: String, + }, + List { + #[arg(long)] + severity: Option<String>, + }, + Resolve { + id: i64, + }, + Stats, +} + +pub struct IncidentStore { + conn: Connection, +} + +impl IncidentStore { + pub fn open(path: &Path) -> Result<Self, TrackerError> { + Ok(Self { + conn: Connection::open(path)?, + }) + } + + pub fn init_schema(&self) -> Result<(), TrackerError> { + todo!("CREATE TABLE IF NOT EXISTS incidents (...)") + } + + pub fn add(&self, title: &str, severity: &str) -> Result<Incident, TrackerError> { + let _ = params![title, severity]; + todo!("Zwaliduj title i severity (low|medium|high|critical), zapisz i zwróć Incident") + } + + pub fn list(&self, severity: Option<&str>) -> Result<Vec<Incident>, TrackerError> { + todo!("Zwróć incydenty (opcjonalnie przefiltrowane po severity)") + } + + pub fn resolve(&self, id: i64) -> Result<Incident, TrackerError> { + todo!("Ustaw status='resolved' lub zwróć TrackerError::NotFound(id)") + } + + pub fn stats(&self) -> Result<BTreeMap<String, usize>, TrackerError> { + todo!("Zwróć mapę z kluczami 'open' i 'resolved'") + } +} + +pub fn run_cli(db_path: &Path, args: &[&str]) -> Result<String, TrackerError> { + todo!("Sparsuj Cli::try_parse_from(args), wykonaj komendę na IncidentStore i zwróć JSON") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn temp_db(tag: &str) -> std::path::PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!("rust-incident-{tag}-{nanos}.db")) + } + + #[test] + fn incident_store_sqlite_lifecycle() { + let db = temp_db("store"); + let store = IncidentStore::open(&db).unwrap(); + store.init_schema().unwrap(); + + assert!(matches!( + store.add(" ", "high"), + Err(TrackerError::InvalidInput(_)) + )); + assert!(matches!( + store.add("DB down", "urgent"), + Err(TrackerError::InvalidInput(_)) + )); + + let inc1 = store.add("K8s node NotReady", "critical").unwrap(); + let _inc2 = store.add("High disk usage", "medium").unwrap(); + assert_eq!(inc1.status, "open"); + assert_eq!(store.list(Some("critical")).unwrap().len(), 1); + + let resolved = store.resolve(inc1.id).unwrap(); + assert_eq!(resolved.status, "resolved"); + let stats = store.stats().unwrap(); + assert_eq!(stats.get("open"), Some(&1)); + assert_eq!(stats.get("resolved"), Some(&1)); + assert!(matches!( + store.resolve(9999), + Err(TrackerError::NotFound(9999)) + )); + + drop(store); + let _ = fs::remove_file(&db); + } + + #[test] + fn incident_cli_end_to_end() { + let db = temp_db("cli"); + let add_json = run_cli( + &db, + &[ + "incident-tracker", + "add", + "API 502 spike", + "--severity", + "high", + ], + ) + .unwrap(); + let created: Incident = serde_json::from_str(&add_json).unwrap(); + assert_eq!(created.severity, "high"); + + let stats_json = run_cli(&db, &["incident-tracker", "stats"]).unwrap(); + let stats: BTreeMap<String, usize> = serde_json::from_str(&stats_json).unwrap(); + assert_eq!(stats.get("open"), Some(&1)); + assert_eq!(stats.get("resolved"), Some(&0)); + + let _ = fs::remove_file(&db); + } +}