diff --git a/.gitea/workflows/test-and-lint.yaml b/.gitea/workflows/test-and-lint.yaml new file mode 100644 index 0000000..8b9dce3 --- /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 (gofmt) + run: make fmt-check + + - name: Vet and staticcheck + run: make check && make lint + + - 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/Makefile b/Makefile index 4548959..f8ab319 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ RUN_CONTAINER = $(ENGINE) run --rm \ -w /workspace \ $(IMAGE) -.PHONY: help image check lint test test-all fmt fmt-check shell +.PHONY: help image check lint test test-project test-all fmt fmt-check shell help: @echo "Dostępne komendy:" @@ -18,6 +18,7 @@ help: @echo " make lint - Uruchom staticcheck" @echo " make test PKG=./exercises/01-core/01-basics - Uruchom testy wybranego rozdziału (-race)" @echo " make test - Uruchom testy 01-core + 02-engineering-2026" + @echo " make test-project - Uruchom testy mini-projektu incident-tracker" @echo " make test-all - Uruchom testy całego repozytorium" @echo " make fmt - Sformatuj kod (gofmt)" @echo " make fmt-check - Sprawdź formatowanie kodu" @@ -39,14 +40,17 @@ else $(RUN_CONTAINER) go test -race -v ./exercises/01-core/... ./exercises/02-engineering-2026/... endif +test-project: + $(RUN_CONTAINER) go test -race -v ./projects/incident-tracker/... + test-all: $(RUN_CONTAINER) go test -race -v ./... fmt: - $(RUN_CONTAINER) gofmt -w exercises + $(RUN_CONTAINER) gofmt -w exercises projects fmt-check: - $(RUN_CONTAINER) sh -c 'out=$$(gofmt -l exercises); test -z "$$out" || (echo "Unformatted files:"; echo "$$out"; exit 1)' + $(RUN_CONTAINER) sh -c 'out=$$(gofmt -l exercises projects); test -z "$$out" || (echo "Unformatted files:"; echo "$$out"; exit 1)' shell: $(ENGINE) run --rm -it \ diff --git a/README.md b/README.md index 97f7df4..efe334d 100644 --- a/README.md +++ b/README.md @@ -54,12 +54,17 @@ make fmt - [ ] `03-cross-platform-os` — [README](exercises/02-engineering-2026/03-cross-platform-os/README.md): `path/filepath`, env vars, cross-kompilacja - [ ] `04-testing-best-practices` — [README](exercises/02-engineering-2026/04-testing-best-practices/README.md): table-driven tests, `t.TempDir()`, `httptest` - [ ] `05-testing-types-and-mutation` — [README](exercises/02-engineering-2026/05-testing-types-and-mutation/README.md): testy jednostkowe, integracyjne i mutacyjne (zabijanie mutantów) +- [ ] `06-security-appsec` — [README](exercises/02-engineering-2026/06-security-appsec/README.md): bezpieczeństwo kodu (Path Traversal, redakcja sekretów) ### Ścieżka 3: `03-ecosystems/` — DevOps, SRE, Cloud Native - [ ] `01-cli-cobra` — [README](exercises/03-ecosystems/01-cli-cobra/README.md): parsowanie argumentów CLI w `cobra` - [ ] `02-http-api-stdlib` — [README](exercises/03-ecosystems/02-http-api-stdlib/README.md): serwer HTTP (`net/http` Go 1.22+), JSON, middleware - [ ] `03-sre-health-and-metrics` — [README](exercises/03-ecosystems/03-sre-health-and-metrics/README.md): `/healthz`, `/readyz`, `log/slog`, metryki Prometheusa - [ ] `04-k8s-style-reconciler` — [README](exercises/03-ecosystems/04-k8s-style-reconciler/README.md): pętla uzgadniania (*reconciliation loop* jak w operatorach K8s) +- [ ] `05-sql-sqlite` — [README](exercises/03-ecosystems/05-sql-sqlite/README.md): SQL i SQLite (`database/sql` + `modernc.org/sqlite`, ochrona przed SQLi) + +### Mini-Projekt Końcowy (Capstone): `projects/incident-tracker/` +- [ ] `incident-tracker` — [README](projects/incident-tracker/README.md): pełna aplikacja SRE (CLI `cobra` + SQLite + JSON + testy, `make test-project`) --- @@ -72,6 +77,10 @@ make fmt * [03 — Algorytmy i złożoność obliczeniowa w Go (Big-O)](notes/03-algorithms-and-complexity.md) * [04 — Rodzaje testów w Go: jednostkowe, integracyjne, mutacyjne, fuzzing](notes/04-testing-pyramid-and-types.md) * [05 — Efektywny debugging i czytanie błędów w Go (Panic & `-race`)](notes/05-debugging-and-reading-errors.md) +* [06 — SQL i Bazy Danych w Go (`database/sql`, SQLite, PostgreSQL)](notes/06-sql-and-databases.md) +* [07 — Bezpieczeństwo Kodu w Go (AppSec & OWASP)](notes/07-appsec-and-secure-coding.md) +* [08 — Git w Korpo i Architektura Aplikacji w Go](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/README.md b/exercises/02-engineering-2026/06-security-appsec/README.md new file mode 100644 index 0000000..779956a --- /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 (`appsec.go`) +1. `SafeJoin(baseDir, relPath string) (string, error)` — bezpiecznie połącz `baseDir` z `relPath`. Odrzuć ścieżki absolutne i próby wyjścia poza `baseDir` (`../../etc/passwd`) błędem `ErrPathTraversal`. +2. `RedactSecrets(logLine string) string` — zamaskuj wartości po `Bearer `, `token=` i `password=` na `***`. + +## Uruchomienie testów +```bash +make test PKG=./exercises/02-engineering-2026/06-security-appsec +``` diff --git a/exercises/02-engineering-2026/06-security-appsec/appsec.go b/exercises/02-engineering-2026/06-security-appsec/appsec.go new file mode 100644 index 0000000..17b3530 --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/appsec.go @@ -0,0 +1,13 @@ +package appsec + +import "errors" + +var ErrPathTraversal = errors.New("path escapes base directory") + +func SafeJoin(baseDir, relPath string) (string, error) { + panic("TODO: odrzuć filepath.IsAbs(relPath) oraz ścieżki wychodzące poza baseDir (filepath.Rel -> '..')") +} + +func RedactSecrets(logLine string) string { + panic("TODO: zamień wartości po 'Bearer ', 'token=' i 'password=' na '***'") +} diff --git a/exercises/02-engineering-2026/06-security-appsec/appsec_test.go b/exercises/02-engineering-2026/06-security-appsec/appsec_test.go new file mode 100644 index 0000000..ade501d --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/appsec_test.go @@ -0,0 +1,40 @@ +package appsec + +import ( + "errors" + "path/filepath" + "strings" + "testing" +) + +func TestSafeJoinBlocksTraversal(t *testing.T) { + base := t.TempDir() + got, err := SafeJoin(base, filepath.Join("configs", "app.yaml")) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := filepath.Join(base, "configs", "app.yaml") + if got != want { + t.Fatalf("got %q, want %q", got, want) + } + + if _, err := SafeJoin(base, "../../etc/passwd"); !errors.Is(err, ErrPathTraversal) { + t.Fatalf("expected ErrPathTraversal, got %v", err) + } + if _, err := SafeJoin(base, "/etc/passwd"); !errors.Is(err, ErrPathTraversal) { + t.Fatalf("expected ErrPathTraversal for abs path, got %v", err) + } +} + +func TestRedactSecrets(t *testing.T) { + line := "auth failed header=Bearer s3cr3tTok3n user=admin password=hunter2 token=abc_123" + cleaned := RedactSecrets(line) + for _, leaked := range []string{"s3cr3tTok3n", "hunter2", "abc_123"} { + if strings.Contains(cleaned, leaked) { + t.Errorf("secret %q leaked in %q", leaked, cleaned) + } + } + if !strings.Contains(cleaned, "user=admin") { + t.Errorf("non-secret field lost in %q", cleaned) + } +} 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..258077a --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/README.md @@ -0,0 +1,14 @@ +# 05 — SQL i SQLite (`database/sql` + `modernc.org/sqlite`, ochrona przed SQLi) + +Teoria: [notes/06-sql-and-databases.md](../../../notes/06-sql-and-databases.md) + +## Zadania (`sqlite_store.go`) +Zaimplementuj `ServiceRegistry` na `database/sql` ze sterownikiem pure-Go `modernc.org/sqlite` (`sql.Open("sqlite", dbPath)`): +1. `InitSchema() error` — `CREATE TABLE IF NOT EXISTS services(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, owner TEXT NOT NULL)`. +2. `Register(name, owner string) (int64, error)` — parametryzowany `INSERT` (`?`) i `res.LastInsertId()`. +3. `FindByOwner(owner string) ([]string, error)` — posortowana lista nazw serwisów bez podatności na SQL Injection. + +## Uruchomienie testów +```bash +make test PKG=./exercises/03-ecosystems/05-sql-sqlite +``` diff --git a/exercises/03-ecosystems/05-sql-sqlite/sqlite_store.go b/exercises/03-ecosystems/05-sql-sqlite/sqlite_store.go new file mode 100644 index 0000000..b79176e --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/sqlite_store.go @@ -0,0 +1,36 @@ +package sqlsqlite + +import ( + "database/sql" + + _ "modernc.org/sqlite" +) + +type ServiceRegistry struct { + //lint:ignore U1000 używane po zaimplementowaniu metod + db *sql.DB +} + +func OpenRegistry(dbPath string) (*ServiceRegistry, error) { + db, err := sql.Open("sqlite", dbPath) + if err != nil { + return nil, err + } + return &ServiceRegistry{db: db}, nil +} + +func (r *ServiceRegistry) Close() error { + return r.db.Close() +} + +func (r *ServiceRegistry) InitSchema() error { + panic("TODO: CREATE TABLE IF NOT EXISTS services (...)") +} + +func (r *ServiceRegistry) Register(name, owner string) (int64, error) { + panic("TODO: parametryzowany INSERT INTO services(name, owner) VALUES(?, ?)") +} + +func (r *ServiceRegistry) FindByOwner(owner string) ([]string, error) { + panic("TODO: parametryzowany SELECT name FROM services WHERE owner = ? ORDER BY name ASC") +} diff --git a/exercises/03-ecosystems/05-sql-sqlite/sqlite_store_test.go b/exercises/03-ecosystems/05-sql-sqlite/sqlite_store_test.go new file mode 100644 index 0000000..69d5043 --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/sqlite_store_test.go @@ -0,0 +1,40 @@ +package sqlsqlite + +import ( + "path/filepath" + "reflect" + "testing" +) + +func TestSQLiteCRUDAndSQLiResistance(t *testing.T) { + reg, err := OpenRegistry(filepath.Join(t.TempDir(), "registry.db")) + if err != nil { + t.Fatalf("open failed: %v", err) + } + defer reg.Close() + + if err := reg.InitSchema(); err != nil { + t.Fatalf("init schema failed: %v", err) + } + id1, err := reg.Register("billing-api", "team-core") + if err != nil || id1 <= 0 { + t.Fatalf("register failed: id=%d err=%v", id1, err) + } + _, _ = reg.Register("auth-api", "team-core") + _, _ = reg.Register("metrics-proxy", "team-sre") + + got, err := reg.FindByOwner("team-core") + if err != nil { + t.Fatalf("find failed: %v", err) + } + want := []string{"auth-api", "billing-api"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %v, want %v", got, want) + } + + // Negative security assertion: SQL Injection payload must NOT return all rows + sqli, err := reg.FindByOwner("' OR '1'='1") + if err != nil || len(sqli) != 0 { + t.Fatalf("SQLi resistance failed: got=%v err=%v", sqli, err) + } +} diff --git a/go.mod b/go.mod index 48305ee..303496c 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,22 @@ module gitea.wired.synology.me/soda64/go-learning -go 1.24 - -require github.com/spf13/cobra v1.9.1 +go 1.26.0 require ( + github.com/spf13/cobra v1.9.1 + modernc.org/sqlite v1.64.0 +) + +require ( + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/spf13/pflag v1.0.6 // indirect + golang.org/x/sys v0.49.0 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect ) diff --git a/go.sum b/go.sum index ffae55e..18641f7 100644 --- a/go.sum +++ b/go.sum @@ -1,10 +1,60 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.64.0 h1:xCoLcRc2g33gLkmaRrcsJLitr4TRMQGGb3H4HYs3mbM= +modernc.org/sqlite v1.64.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/notes/06-sql-and-databases.md b/notes/06-sql-and-databases.md new file mode 100644 index 0000000..69bc386 --- /dev/null +++ b/notes/06-sql-and-databases.md @@ -0,0 +1,33 @@ +# SQL i Bazy Danych w Go (`database/sql`, SQLite, PostgreSQL) + +SQL pojawia się w **~22% wszystkich ofert IT w Polsce**. W Go standardem jest wbudowany pakiet `database/sql` w połączeniu ze sterownikiem (np. pure-Go `modernc.org/sqlite` dla SQLite albo `pgx` dla PostgreSQL). + +--- + +## 1. Podstawy SQL i `database/sql` + +```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); +``` + +* **Zawsze zamykaj zasoby:** `defer db.Close()` i `defer rows.Close()`. +* **Zawsze sprawdzaj `rows.Err()`** po zakończeniu pętli `for rows.Next()`. +* **Zawsze używaj parametryzowanych zapytań (`?` w SQLite, `$1` w PostgreSQL)** — nigdy `fmt.Sprintf` do wstawiania danych użytkownika do SQL! + +```go +// ŹLE (SQL Injection!): +db.Query(fmt.Sprintf("SELECT name FROM services WHERE owner = '%s'", owner)) + +// DOBRZE (parametryzowane zapytanie): +db.Query("SELECT name FROM services WHERE owner = ? ORDER BY name ASC", owner) +``` + +## 2. Transakcje ACID i `sqlc` +* Transakcje: `tx, err := db.BeginTx(ctx, nil)` + `defer tx.Rollback()` + `tx.Commit()`. +* W większych projektach Go zamiast ciężkiego ORM-a popularny jest **`sqlc`** — generuje w 100% typowany kod Go na podstawie czystych plików `.sql`. diff --git a/notes/07-appsec-and-secure-coding.md b/notes/07-appsec-and-secure-coding.md new file mode 100644 index 0000000..d1e37c9 --- /dev/null +++ b/notes/07-appsec-and-secure-coding.md @@ -0,0 +1,15 @@ +# Bezpieczeństwo Kodu w Go (AppSec & OWASP w praktyce) + +| Podatność | Jak wygląda błąd w Go | Jak się zabezpieczyć | +| :--- | :--- | :--- | +| **SQL Injection** | `fmt.Sprintf("... '%s'", input)` | Parametryzowane zapytania `db.Query("... ?", input)`. | +| **Command Injection** | `exec.Command("sh", "-c", "ls " + userDir)` | `exec.Command("ls", userDir)` bez pośredniej powłoki `sh -c`. | +| **Path Traversal (`../`)** | `filepath.Join(base, userPath)` bez weryfikacji ucieczki poza `base`. | `filepath.Rel(absBase, absTarget)` i odrzucenie ścieżek zaczynających się od `..` lub absolutnych. | +| **Wyciek sekretów** | Tokeny w logach `slog`, hasła w kodzie. | Redakcja tokenów w logach (`Bearer ***`), zmienne środowiskowe, `gitleaks`. | +| **Brak timeoutów HTTP** | `http.Get(url)` używa `http.DefaultClient` **bez timeoutu**! | Zawsze `&http.Client{Timeout: 5 * time.Second}` i `context.WithTimeout`. | + +## Higiena łańcucha dostaw (Supply Chain) +* **Podatności CVE w Go:** `govulncheck ./...` (oficjalne narzędzie zespołu Go). +* **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..5cdc157 --- /dev/null +++ b/notes/08-git-workflow-and-architecture.md @@ -0,0 +1,12 @@ +# Git w Korpo i Architektura Aplikacji w Go + +## 1. Git Workflow w międzynarodowych zespołach +* **Atomowe commity** + **Conventional Commits** (`feat:`, `fix:`, `refactor:`, `test:`, `docs:`, `chore:`). +* **`merge` vs `rebase`:** `rebase` tylko na własnych lokalnych gałęziach; nigdy na współdzielonym `main`. +* **`git bisect`:** szukanie commita winnego regresji w `O(log n)` krokach. +* **Checklista PR:** własny przegląd `git diff`, zielone `make check && make lint && make fmt-check`, brak sekretów i debug-printów, opis: **Co / Dlaczego / Jak przetestowano**. + +## 2. Architektura w Go: małe interfejsy i oddzielenie domeny od I/O +* **„Accept interfaces, return structs”** — definiuj małe interfejsy (1–3 metody) w pakiecie, który ich *używa*. +* Oddziel czystą logikę domenową od warstwy CLI (`cobra`), HTTP (`net/http`) i persystencji (`database/sql`). +* Zobacz ten wzorzec w praktyce 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..39d6585 --- /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, 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 / błąd) | Przyczyna źródłowa (*root cause*) | Zasada na przyszłość | Powtórka (+3d / +7d) | +| :--- | :--- | :--- | :--- | :--- | :--- | +| *przykład* | `02-engineering/01-ai-code-audit` | `WARNING: DATA RACE` w `go test -race` | Zapis do pola `Counter.value` bez synchronizacji | Chroń stan przez `sync.Mutex` lub `atomic.Int64` | `[ ]` `[ ]` | + +## Retrospektywa po ukończeniu ścieżki +1. Który koncept sprawił mi największą trudność (PL i EN)? +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 26eda88..b8bb199 100644 --- a/notes/README.md +++ b/notes/README.md @@ -6,3 +6,7 @@ * [03 — Algorytmy i złożoność obliczeniowa w Go (Big-O)](03-algorithms-and-complexity.md) * [04 — Rodzaje testów w Go: jednostkowe, integracyjne, mutacyjne, fuzzing](04-testing-pyramid-and-types.md) * [05 — Efektywny debugging i czytanie błędów w Go (Panic & `-race`)](05-debugging-and-reading-errors.md) +* [06 — SQL i Bazy Danych w Go (`database/sql`, SQLite, PostgreSQL)](06-sql-and-databases.md) +* [07 — Bezpieczeństwo Kodu w Go (AppSec & OWASP)](07-appsec-and-secure-coding.md) +* [08 — Git w Korpo i Architektura Aplikacji w Go](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/README.md b/projects/incident-tracker/README.md new file mode 100644 index 0000000..6705e76 --- /dev/null +++ b/projects/incident-tracker/README.md @@ -0,0 +1,12 @@ +# Capstone Mini-Projekt: `incident-tracker` (CLI `cobra` + 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 (`tracker.go`) +1. `IncidentStore` na SQLite (`modernc.org/sqlite`): `InitSchema`, `Add(title, severity)`, `List(severity)`, `Resolve(id)`, `Stats()`. +2. `NewCLI(dbPath string, out io.Writer) *cobra.Command` — podkomendy `add