feat: add SQL/SQLite, AppSec, Capstone incident-tracker, Gitea Actions CI and spaced repetition
Test and Lint / quality (push) Successful in 2m13s
Test and Lint / quality (push) Successful in 2m13s
This commit is contained in:
1 parent
011f23e637
commit
33082598fc
19 files changed
+496
-6
No files matched your search
@@ -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
|
||||
@@ -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 \
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -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 '***'")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
```
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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=
|
||||
@@ -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`.
|
||||
@@ -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).
|
||||
@@ -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/`.
|
||||
@@ -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/`?
|
||||
@@ -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)
|
||||
@@ -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 <title> --severity <sev>`, `list [--severity <sev>]`, `resolve <id>`, `stats` wypisujące JSON do `out`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test-project
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
package incidenttracker
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidIncident = errors.New("invalid incident input")
|
||||
ErrNotFound = errors.New("incident not found")
|
||||
)
|
||||
|
||||
type Incident struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Severity string `json:"severity"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type IncidentStore struct {
|
||||
//lint:ignore U1000 używane po zaimplementowaniu metod
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func OpenStore(dbPath string) (*IncidentStore, error) {
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &IncidentStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *IncidentStore) Close() error {
|
||||
return s.db.Close()
|
||||
}
|
||||
|
||||
func (s *IncidentStore) InitSchema() error {
|
||||
panic("TODO: CREATE TABLE IF NOT EXISTS incidents (...)")
|
||||
}
|
||||
|
||||
func (s *IncidentStore) Add(title, severity string) (Incident, error) {
|
||||
panic("TODO: zwaliduj title i severity (low|medium|high|critical), zapisz w SQLite")
|
||||
}
|
||||
|
||||
func (s *IncidentStore) List(severity string) ([]Incident, error) {
|
||||
panic("TODO: zwróć incydenty (jeśli severity != '' to przefiltruj)")
|
||||
}
|
||||
|
||||
func (s *IncidentStore) Resolve(id int64) (Incident, error) {
|
||||
panic("TODO: ustaw status='resolved' lub zwróć ErrNotFound")
|
||||
}
|
||||
|
||||
func (s *IncidentStore) Stats() (map[string]int, error) {
|
||||
panic("TODO: zwróć map[string]int{\"open\": X, \"resolved\": Y}")
|
||||
}
|
||||
|
||||
func NewCLI(dbPath string, out io.Writer) *cobra.Command {
|
||||
root := &cobra.Command{Use: "incident-tracker", SilenceUsage: true, SilenceErrors: true}
|
||||
root.SetOut(out)
|
||||
panic("TODO: dodaj podkomendy add, list, resolve, stats wypisujące JSON do out")
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package incidenttracker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIncidentStoreSQLiteLifecycle(t *testing.T) {
|
||||
store, err := OpenStore(filepath.Join(t.TempDir(), "incidents.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open failed: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
if err := store.InitSchema(); err != nil {
|
||||
t.Fatalf("init schema failed: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.Add(" ", "high"); !errors.Is(err, ErrInvalidIncident) {
|
||||
t.Fatalf("expected ErrInvalidIncident, got %v", err)
|
||||
}
|
||||
if _, err := store.Add("DB down", "urgent"); !errors.Is(err, ErrInvalidIncident) {
|
||||
t.Fatalf("expected ErrInvalidIncident for bad severity, got %v", err)
|
||||
}
|
||||
|
||||
inc1, err := store.Add("K8s node NotReady", "critical")
|
||||
if err != nil || inc1.Status != "open" {
|
||||
t.Fatalf("add failed: %+v, %v", inc1, err)
|
||||
}
|
||||
_, _ = store.Add("High disk usage", "medium")
|
||||
|
||||
crit, err := store.List("critical")
|
||||
if err != nil || len(crit) != 1 {
|
||||
t.Fatalf("list critical failed: %v, %v", crit, err)
|
||||
}
|
||||
|
||||
res, err := store.Resolve(inc1.ID)
|
||||
if err != nil || res.Status != "resolved" {
|
||||
t.Fatalf("resolve failed: %+v, %v", res, err)
|
||||
}
|
||||
stats, err := store.Stats()
|
||||
if err != nil || stats["open"] != 1 || stats["resolved"] != 1 {
|
||||
t.Fatalf("unexpected stats: %v, %v", stats, err)
|
||||
}
|
||||
if _, err := store.Resolve(9999); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncidentCLIEndToEnd(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "cli.db")
|
||||
var buf bytes.Buffer
|
||||
|
||||
cmdAdd := NewCLI(dbPath, &buf)
|
||||
cmdAdd.SetArgs([]string{"add", "API 502 spike", "--severity", "high"})
|
||||
if err := cmdAdd.Execute(); err != nil {
|
||||
t.Fatalf("cli add failed: %v", err)
|
||||
}
|
||||
var created Incident
|
||||
if err := json.Unmarshal(buf.Bytes(), &created); err != nil || created.Severity != "high" {
|
||||
t.Fatalf("unexpected add JSON: %q (%v)", buf.String(), err)
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
cmdStats := NewCLI(dbPath, &buf)
|
||||
cmdStats.SetArgs([]string{"stats"})
|
||||
if err := cmdStats.Execute(); err != nil {
|
||||
t.Fatalf("cli stats failed: %v", err)
|
||||
}
|
||||
var stats map[string]int
|
||||
if err := json.Unmarshal(buf.Bytes(), &stats); err != nil || stats["open"] != 1 {
|
||||
t.Fatalf("unexpected stats JSON: %q (%v)", buf.String(), err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user