Compare commits

...
7 Commits
40 changed files with 1315 additions and 252 deletions

No files matched your search

+9 -5
View File
@@ -1,4 +1,4 @@
.PHONY: build build-release clean test run version install-hooks migrate migrate-status migrate-baseline
.PHONY: build build-release clean test run version install-hooks migrate migrate-status migrate-baseline security-check
# Get version from git
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
@@ -13,20 +13,20 @@ build:
go build -o bin/$(BINARY) ./cmd/qfs
# Build for release (optimized, with version)
build-release:
build-release: security-check
@echo "Building $(BINARY) version $(VERSION)..."
CGO_ENABLED=0 go build -ldflags="$(LDFLAGS)" -o bin/$(BINARY) ./cmd/qfs
@echo "✓ Built: bin/$(BINARY)"
@./bin/$(BINARY) -version
# Build release for Linux (cross-compile)
build-linux:
build-linux: security-check
@echo "Building $(BINARY) for Linux..."
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o bin/$(BINARY)-linux-amd64 ./cmd/qfs
@echo "✓ Built: bin/$(BINARY)-linux-amd64"
# Build release for macOS (cross-compile)
build-macos:
build-macos: security-check
@echo "Building $(BINARY) for macOS..."
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o bin/$(BINARY)-darwin-amd64 ./cmd/qfs
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="$(LDFLAGS)" -o bin/$(BINARY)-darwin-arm64 ./cmd/qfs
@@ -34,7 +34,7 @@ build-macos:
@echo "✓ Built: bin/$(BINARY)-darwin-arm64"
# Build release for Windows (cross-compile)
build-windows:
build-windows: security-check
@echo "Building $(BINARY) for Windows..."
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o bin/$(BINARY)-windows-amd64.exe ./cmd/qfs
@echo "✓ Built: bin/$(BINARY)-windows-amd64.exe"
@@ -77,6 +77,10 @@ migrate-baseline:
test:
go test -v ./...
# Pin the scanner so releases do not depend on a locally installed executable.
security-check:
go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...
# Run development server
run:
go run ./cmd/qfs
+11
View File
@@ -68,3 +68,14 @@ bible/ shared engineering rules
bible-local/ project-specific architecture
releases/ release artifacts and notes
```
## Local HTTP trust boundary
Loopback binding does not make a browser client trusted. Both setup and normal
routers reject non-loopback Host, Origin and Referer values, opaque origins and
cross-site Fetch Metadata requests before any handler runs. CLI clients may omit
browser headers. API requests carrying a body require application/json, except
the project vendor-import endpoint, which also accepts multipart/form-data.
Setup retains HTML forms; an empty password reuses the saved credential only
when host, port and user are unchanged. Changing the destination requires an
explicit password.
+8
View File
@@ -342,3 +342,11 @@ Rules:
- PN to LOT resolution uses the active local partnumber book;
- canonical persisted mapping is `lot_mappings[]`;
- QuoteForge does not use legacy BOM tables such as `qt_bom`, `qt_lot_bundles`, or `qt_lot_bundle_items`.
## Browser rendering
`web/static/html-escape.js` provides the shared `escapeHtml` for HTML text and
quoted attributes. Never interpolate data into JavaScript event attributes.
Cart and rental controls carry escaped LOT values in `data-lot` and dispatch
through delegated listeners. Sync errors are escaped as text; toast messages use
`textContent`. Run `node scripts/tests/html-security.cjs` for the regression check.
+19 -2
View File
@@ -439,8 +439,25 @@ MariaDB:
`UPTO` as applied **without running them**, for a server whose schema is already current;
- migrations use their own connection without read/write timeouts (`openMigrationDB`),
not the app's 3s-timeout sync connection — a long backfill must not be cut mid-file;
- a file is recorded only after all its statements succeed, so each file must be safe to
re-run (`ADD COLUMN IF NOT EXISTS`, idempotent `UPDATE ... WHERE <not yet done>`);
- each file, its `-- verify: <description> | <SQL>` queries and history insertion run
on one database session, preserving session variables;
- a file is recorded only after statements and all verify checks succeed. Verify
queries return rows only for broken invariants; a row or SQL error stops the run
without marking that file applied. Malformed verify headers fail before execution;
- only duplicate column/key names and already-existing objects are tolerated.
FK creation errors (including errno 150/121) remain fatal;
- each file must be safe to re-run after a partial failure (`ADD COLUMN IF NOT EXISTS`,
idempotent `UPDATE ... WHERE <not yet done>`). The current statement splitter assumes
semicolons occur only between statements; do not add semicolons inside literals;
- there is no GORM `AutoMigrate` against MariaDB: it retypes production columns to match the
running binary's models. On 2026-09-24 a stale v1.18 binary run with the old AutoMigrate
`-migrate` did exactly that, which is why it was removed.
## Connection transport
`connection_settings.tls_mode` defaults to `preferred`; `tls_ca_pem` stores an
optional public CA certificate bundle. SQLite startup adds these columns for
legacy settings. Every runtime/setup MariaDB DSN uses `internal/mariadb` to
apply the policy documented in [05-config.md](05-config.md). Private keys are
never part of the CA field. No mode silently falls back to plaintext except
`preferred`.
+20 -1
View File
@@ -62,7 +62,8 @@ They are stored in SQLite and encrypted with `local_encryption.key` unless `QUOT
| --- | --- |
| `-config <path>` | config file path |
| `-localdb <path>` | SQLite path |
| `-reset-localdb` | destructive local DB reset |
| `-reset-localdb` | reset after mandatory verified backup; refuses unsynced work |
| `-force-reset-localdb` | with `-reset-localdb`, allow clearing unsynced work; backup remains mandatory |
| `-migrate` | apply pending server SQL migrations (`migrations/*.sql`) and exit |
| `-migrate-status` | list server SQL migrations with applied/pending state and exit |
| `-migrate-baseline <file>` | record server migrations up to `<file>` as applied without running them, and exit |
@@ -74,3 +75,21 @@ They are stored in SQLite and encrypted with `local_encryption.key` unless `QUOT
2. runtime opens the local SQLite database;
3. if no stored MariaDB credentials exist, `/setup` is served;
4. after setup, runtime works locally and sync uses saved DB settings in the background.
`QFS_RESET_LOCAL_DB` is no longer supported. Reset requires an explicit CLI flag
on each launch. A forced reset still stops if the safety backup cannot be created
and verified. See [06-backup.md](06-backup.md).
## MariaDB TLS
`/setup` stores `tls_mode` and `tls_ca_pem` in SQLite `connection_settings`,
alongside encrypted credentials. Existing and new connections default to
`preferred`, which encrypts when advertised by MariaDB but can fall back to
plaintext and does not authenticate the server. `required` mandates encryption
without verifying the certificate. `verify-ca` requires a PEM CA and validates
the server certificate chain without checking its hostname. `verify-full`
validates both chain and hostname, using the supplied PEM or system roots.
Only the verification modes accept CA input; invalid modes/PEM are rejected.
Use `verify-full` for authenticated server connections. The setup form tests
the selected policy before saving. Sync, setup checks and migration tooling
share the same TLS configuration builder.
+18
View File
@@ -53,3 +53,21 @@ Archive name:
4. replace `config.yaml` if needed;
5. restart the app;
6. re-enter MariaDB credentials if the original encryption key is unavailable.
## Pre-reset safety backup
Before clearing any table, `-reset-localdb` creates a fresh ZIP under
`<backup root>/pre-reset/qfs-pre-reset-v1-<UTC timestamp>-<unique>.zip`, outside
normal retention and regardless of `QFS_BACKUP_DISABLE`. The archive contains
a consistent SQLite snapshot and the selected config when present. Every ZIP
entry is read back for CRC validation; the extracted database must pass SQLite
`integrity_check`. A backup or verification failure prevents the reset. The
backup directory must also resolve outside git after following symlinks.
Reset refuses queued changes and any project/configuration not marked `synced`,
including NULL/legacy states. A missing sync-status column also blocks reset.
Only `-reset-localdb -force-reset-localdb` bypasses this data check. Deletions run
in one transaction and preserve connection settings. Missing legacy tables are
skipped. Use the restore procedure above for the pre-reset archive; retain it
until the reset has been verified. The environment reset switch was removed to
prevent repeated destructive startup.
+15
View File
@@ -9,6 +9,7 @@ make migrate # apply pending server SQL migrations
go run ./cmd/migrate_project_updated_at
go test ./...
go vet ./...
make security-check # pinned govulncheck, blocks reachable vulnerabilities
make build-release
make install-hooks
```
@@ -34,3 +35,17 @@ make install-hooks
Release history belongs under `releases/<version>/RELEASE_NOTES.md`.
Do not keep temporary change summaries in the repository root.
## Toolchain and release security
`go.mod` requires Go 1.27.3 or newer, including security fixes in the standard
library. This minimum also rejects older compilers with `GOTOOLCHAIN=local`;
normal Go toolchain selection downloads a suitable compiler when necessary.
`make security-check` runs `golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...`.
The scanner version is pinned in the Makefile. All release build targets and
`scripts/release.sh` require this check to succeed before producing artifacts.
A scanner/database/download failure also stops release.
When updating dependencies: run `go mod tidy`, `go test ./...`, `go vet ./...`,
`make security-check` and the JavaScript regression check documented in
[02-architecture.md](02-architecture.md).
+1
View File
@@ -16,6 +16,7 @@ Project-specific architecture and operational contracts.
| [09-vendor-spec.md](09-vendor-spec.md) | Vendor BOM and CFXML import contract |
| [10-agent-api-guide.md](10-agent-api-guide.md) | End-to-end API guide for agents pricing servers from a TZ |
| [11-lot-suggestions.md](11-lot-suggestions.md) | lot_suggestion column in qt_vendor_partnumber_seen — write/read contract for manual UI mappings |
| [issue-plan-2026-10-26.md](issue-plan-2026-10-26.md) | Open issue plan, implementation status and validation |
| [decisions/](decisions/README.md) | Architectural decision log, one file per decision |
## Rules
+46
View File
@@ -0,0 +1,46 @@
# Issue implementation plan - 2026-10-26
Repository: https://git.mchus.pro/mchus/QuoteForge
All issue pages were retrieved, including closed issues: seven total, six open.
Issue [#1](https://git.mchus.pro/mchus/QuoteForge/issues/1) was already closed and
is excluded from implementation. Work is sequential on
`fix/open-issues-security-recovery`, with one implementation commit per open issue.
| Order | Issue | Implementation and acceptance | Status |
| --- | --- | --- | --- |
| 1 | [#2](https://git.mchus.pro/mchus/QuoteForge/issues/2) | Block foreign Host/Origin/Referer and cross-site browser requests in both routers; validate API body types; refuse saved-password reuse for a changed host/port/user. Middleware attack cases and setup credential tests must pass. | Implemented |
| 2 | [#4](https://git.mchus.pro/mchus/QuoteForge/issues/4) | Move LOT-bearing cart/rental events to delegated listeners and escaped data attributes; escape BOM and sync output; share HTML escaping; render toast as text. Malicious LOT regression checks and template tests must pass. | Implemented |
| 3 | [#7](https://git.mchus.pro/mchus/QuoteForge/issues/7) | Require a fresh verified archive outside rotation before reset, refuse unsynced/legacy states without explicit force, use transactional deletion, remove environment-triggered reset. Verify refusal, ZIP restore, backup failure and rollback. | Implemented |
| 4 | [#5](https://git.mchus.pro/mchus/QuoteForge/issues/5) | Persist TLS mode/CA in SQLite, expose setup controls, share policy across setup/sync/migration DSNs. Verify certificate trust, hostname checks, plaintext fallback policy and settings round-trip. | Implemented |
| 5 | [#3](https://git.mchus.pro/mchus/QuoteForge/issues/3) | Keep each migration file in one session, execute verify headers before history insertion, propagate FK failures. Verify failed queries/checks never enter history. | Implemented |
| 6 | [#6](https://git.mchus.pro/mchus/QuoteForge/issues/6) | Require Go 1.27.3, update vulnerable dependencies, block release on pinned govulncheck. Full tests, vet, security scan and macOS/Windows builds must pass. | Implemented |
## Decisions
- HTTP forms remain supported on setup and multipart vendor import; JSON APIs
reject non-JSON bodies. CLI clients may omit browser origin headers.
- CSP without inline scripts remains outside this patch; the issue lists it as optional.
- Forced reset still requires a verified backup. `QFS_RESET_LOCAL_DB` is ignored,
with a startup warning; only explicit CLI flags can initiate reset.
- TLS defaults to `preferred` for existing-server compatibility, as requested in
the issue. It permits plaintext fallback; use `verify-full` for authenticated
encryption. The setup form explains this distinction.
- `go 1.27.3` enforces the minimum compiler, including with `GOTOOLCHAIN=local`.
A redundant `toolchain go1.27.3` is removed by Go tooling and is unnecessary.
- The local ignored `.claude/skills/release/SKILL.md` was updated with the security
prerequisite; the shared Makefile and release script enforce it in git.
## Validation and handoff
Passed: `go test ./...`, `go vet ./...`, `node scripts/tests/html-security.cjs`,
`make security-check`, shell syntax and diff checks, and CGO-free builds for
macOS arm64 and Windows amd64.
Govulncheck reports zero reachable vulnerabilities and one module-level advisory
whose affected code is not called. Gin's transitive quic-go was explicitly raised
to v0.59.1 after the first scan identified a reachable advisory in v0.59.0.
The checks use temporary SQLite databases and synthetic certificates. They do
not exercise a live MariaDB server or browser automation. Review the draft PR
before merge; issue state changes and a production release remain separate steps.
+8 -19
View File
@@ -59,7 +59,8 @@ func main() {
configPath := flag.String("config", "", "path to config file (default: user state dir or QFS_CONFIG_PATH)")
localDBPath := flag.String("localdb", "", "path to local SQLite database (default: user state dir or QFS_DB_PATH)")
resetLocalDB := flag.Bool("reset-localdb", false, "reset local SQLite data on startup (keeps connection settings)")
resetLocalDB := flag.Bool("reset-localdb", false, "reset local SQLite data after a verified safety backup (keeps connection settings)")
forceResetLocalDB := flag.Bool("force-reset-localdb", false, "allow -reset-localdb to clear unsynced work after a verified backup")
migrate := flag.Bool("migrate", false, "apply pending server (MariaDB) SQL migrations and exit")
migrateStatus := flag.Bool("migrate-status", false, "list server SQL migrations with applied/pending state and exit")
migrateBaseline := flag.String("migrate-baseline", "", "record server SQL migrations up to and including this file as applied, without running them, and exit")
@@ -112,8 +113,11 @@ func main() {
}
}
if shouldResetLocalDB(*resetLocalDB) {
if err := localdb.ResetData(resolvedLocalDBPath); err != nil {
if os.Getenv("QFS_RESET_LOCAL_DB") != "" {
slog.Warn("QFS_RESET_LOCAL_DB is ignored; use -reset-localdb explicitly")
}
if *resetLocalDB {
if err := localdb.ResetDataWithOptions(resolvedLocalDBPath, resolvedConfigPath, *forceResetLocalDB); err != nil {
slog.Error("failed to reset local database", "error", err)
os.Exit(1)
}
@@ -304,22 +308,6 @@ func showStartupConsoleWarning() {
fmt.Printf("\033]0;%s\007", startupConsoleWarning)
}
func shouldResetLocalDB(flagValue bool) bool {
if flagValue {
return true
}
value := strings.TrimSpace(os.Getenv("QFS_RESET_LOCAL_DB"))
if value == "" {
return false
}
switch strings.ToLower(value) {
case "1", "true", "yes", "y":
return true
default:
return false
}
}
func derefString(value *string) string {
if value == nil {
return ""
@@ -565,6 +553,7 @@ func runSetupMode(local *localdb.LocalDB) {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Use(gin.Recovery())
router.Use(middleware.CORS())
if staticFS, err := qfassets.StaticFS(); err == nil {
router.StaticFS("/static", http.FS(staticFS))
+23 -23
View File
@@ -45,7 +45,7 @@ func TestConfigurationVersioningAPI(t *testing.T) {
}
// list versions happy path
listReq := httptest.NewRequest(http.MethodGet, "/api/configs/"+created.UUID+"/versions?limit=10&offset=0", nil)
listReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/versions?limit=10&offset=0", nil)
listRec := httptest.NewRecorder()
router.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
@@ -53,7 +53,7 @@ func TestConfigurationVersioningAPI(t *testing.T) {
}
// get version happy path
getReq := httptest.NewRequest(http.MethodGet, "/api/configs/"+created.UUID+"/versions/1", nil)
getReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/versions/1", nil)
getRec := httptest.NewRecorder()
router.ServeHTTP(getRec, getReq)
if getRec.Code != http.StatusOK {
@@ -62,7 +62,7 @@ func TestConfigurationVersioningAPI(t *testing.T) {
// rollback happy path
body := []byte(`{"target_version":1,"note":"api rollback"}`)
rbReq := httptest.NewRequest(http.MethodPost, "/api/configs/"+created.UUID+"/rollback", bytes.NewReader(body))
rbReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/rollback", bytes.NewReader(body))
rbReq.Header.Set("Content-Type", "application/json")
rbRec := httptest.NewRecorder()
router.ServeHTTP(rbRec, rbReq)
@@ -84,7 +84,7 @@ func TestConfigurationVersioningAPI(t *testing.T) {
}
// 404: version missing
notFoundReq := httptest.NewRequest(http.MethodGet, "/api/configs/"+created.UUID+"/versions/999", nil)
notFoundReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/versions/999", nil)
notFoundRec := httptest.NewRecorder()
router.ServeHTTP(notFoundRec, notFoundReq)
if notFoundRec.Code != http.StatusNotFound {
@@ -92,7 +92,7 @@ func TestConfigurationVersioningAPI(t *testing.T) {
}
// 400: invalid version number
invalidReq := httptest.NewRequest(http.MethodGet, "/api/configs/"+created.UUID+"/versions/abc", nil)
invalidReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/versions/abc", nil)
invalidRec := httptest.NewRecorder()
router.ServeHTTP(invalidRec, invalidReq)
if invalidRec.Code != http.StatusBadRequest {
@@ -100,7 +100,7 @@ func TestConfigurationVersioningAPI(t *testing.T) {
}
// 400: rollback invalid target_version
badRollbackReq := httptest.NewRequest(http.MethodPost, "/api/configs/"+created.UUID+"/rollback", bytes.NewReader([]byte(`{"target_version":0}`)))
badRollbackReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/rollback", bytes.NewReader([]byte(`{"target_version":0}`)))
badRollbackReq.Header.Set("Content-Type", "application/json")
badRollbackRec := httptest.NewRecorder()
router.ServeHTTP(badRollbackRec, badRollbackReq)
@@ -109,28 +109,28 @@ func TestConfigurationVersioningAPI(t *testing.T) {
}
// archive + reactivate flow
delReq := httptest.NewRequest(http.MethodDelete, "/api/configs/"+created.UUID, nil)
delReq := httptest.NewRequest(http.MethodDelete, "http://127.0.0.1:8080/api/configs/"+created.UUID, nil)
delRec := httptest.NewRecorder()
router.ServeHTTP(delRec, delReq)
if delRec.Code != http.StatusOK {
t.Fatalf("archive status=%d body=%s", delRec.Code, delRec.Body.String())
}
archivedListReq := httptest.NewRequest(http.MethodGet, "/api/configs?status=archived&page=1&per_page=20", nil)
archivedListReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs?status=archived&page=1&per_page=20", nil)
archivedListRec := httptest.NewRecorder()
router.ServeHTTP(archivedListRec, archivedListReq)
if archivedListRec.Code != http.StatusOK {
t.Fatalf("archived list status=%d body=%s", archivedListRec.Code, archivedListRec.Body.String())
}
reactivateReq := httptest.NewRequest(http.MethodPost, "/api/configs/"+created.UUID+"/reactivate", nil)
reactivateReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/reactivate", nil)
reactivateRec := httptest.NewRecorder()
router.ServeHTTP(reactivateRec, reactivateReq)
if reactivateRec.Code != http.StatusOK {
t.Fatalf("reactivate status=%d body=%s", reactivateRec.Code, reactivateRec.Body.String())
}
activeListReq := httptest.NewRequest(http.MethodGet, "/api/configs?status=active&page=1&per_page=20", nil)
activeListReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs?status=active&page=1&per_page=20", nil)
activeListRec := httptest.NewRecorder()
router.ServeHTTP(activeListRec, activeListReq)
if activeListRec.Code != http.StatusOK {
@@ -151,7 +151,7 @@ func TestProjectArchiveHidesConfigsAndCloneIntoProject(t *testing.T) {
t.Fatalf("setup router: %v", err)
}
createProjectReq := httptest.NewRequest(http.MethodPost, "/api/projects", bytes.NewReader([]byte(`{"name":"P1","code":"P1"}`)))
createProjectReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects", bytes.NewReader([]byte(`{"name":"P1","code":"P1"}`)))
createProjectReq.Header.Set("Content-Type", "application/json")
createProjectRec := httptest.NewRecorder()
router.ServeHTTP(createProjectRec, createProjectReq)
@@ -164,7 +164,7 @@ func TestProjectArchiveHidesConfigsAndCloneIntoProject(t *testing.T) {
}
createCfgBody := []byte(`{"name":"Cfg A","items":[{"lot_name":"CPU","quantity":1,"unit_price":100}],"server_count":1}`)
createCfgReq := httptest.NewRequest(http.MethodPost, "/api/projects/"+project.UUID+"/configs", bytes.NewReader(createCfgBody))
createCfgReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects/"+project.UUID+"/configs", bytes.NewReader(createCfgBody))
createCfgReq.Header.Set("Content-Type", "application/json")
createCfgRec := httptest.NewRecorder()
router.ServeHTTP(createCfgRec, createCfgReq)
@@ -179,7 +179,7 @@ func TestProjectArchiveHidesConfigsAndCloneIntoProject(t *testing.T) {
t.Fatalf("expected config project_uuid=%s got=%v", project.UUID, createdCfg.ProjectUUID)
}
cloneReq := httptest.NewRequest(http.MethodPost, "/api/projects/"+project.UUID+"/configs/"+createdCfg.UUID+"/clone", bytes.NewReader([]byte(`{"name":"Cfg A Clone"}`)))
cloneReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects/"+project.UUID+"/configs/"+createdCfg.UUID+"/clone", bytes.NewReader([]byte(`{"name":"Cfg A Clone"}`)))
cloneReq.Header.Set("Content-Type", "application/json")
cloneRec := httptest.NewRecorder()
router.ServeHTTP(cloneRec, cloneReq)
@@ -194,7 +194,7 @@ func TestProjectArchiveHidesConfigsAndCloneIntoProject(t *testing.T) {
t.Fatalf("expected clone project_uuid=%s got=%v", project.UUID, cloneCfg.ProjectUUID)
}
projectConfigsReq := httptest.NewRequest(http.MethodGet, "/api/projects/"+project.UUID+"/configs", nil)
projectConfigsReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/projects/"+project.UUID+"/configs", nil)
projectConfigsRec := httptest.NewRecorder()
router.ServeHTTP(projectConfigsRec, projectConfigsReq)
if projectConfigsRec.Code != http.StatusOK {
@@ -210,14 +210,14 @@ func TestProjectArchiveHidesConfigsAndCloneIntoProject(t *testing.T) {
t.Fatalf("expected 2 project configs after clone, got %d", len(projectConfigsResp.Configurations))
}
archiveReq := httptest.NewRequest(http.MethodPost, "/api/projects/"+project.UUID+"/archive", nil)
archiveReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects/"+project.UUID+"/archive", nil)
archiveRec := httptest.NewRecorder()
router.ServeHTTP(archiveRec, archiveReq)
if archiveRec.Code != http.StatusOK {
t.Fatalf("archive project status=%d body=%s", archiveRec.Code, archiveRec.Body.String())
}
activeReq := httptest.NewRequest(http.MethodGet, "/api/configs?status=active&page=1&per_page=20", nil)
activeReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs?status=active&page=1&per_page=20", nil)
activeRec := httptest.NewRecorder()
router.ServeHTTP(activeRec, activeReq)
if activeRec.Code != http.StatusOK {
@@ -245,7 +245,7 @@ func TestConfigMoveToProjectEndpoint(t *testing.T) {
t.Fatalf("setup router: %v", err)
}
createProjectReq := httptest.NewRequest(http.MethodPost, "/api/projects", bytes.NewReader([]byte(`{"name":"Move Project","code":"MOVE"}`)))
createProjectReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects", bytes.NewReader([]byte(`{"name":"Move Project","code":"MOVE"}`)))
createProjectReq.Header.Set("Content-Type", "application/json")
createProjectRec := httptest.NewRecorder()
router.ServeHTTP(createProjectRec, createProjectReq)
@@ -257,7 +257,7 @@ func TestConfigMoveToProjectEndpoint(t *testing.T) {
t.Fatalf("unmarshal project: %v", err)
}
createConfigReq := httptest.NewRequest(http.MethodPost, "/api/configs", bytes.NewReader([]byte(`{"name":"Move Me","items":[],"notes":"","server_count":1}`)))
createConfigReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/configs", bytes.NewReader([]byte(`{"name":"Move Me","items":[],"notes":"","server_count":1}`)))
createConfigReq.Header.Set("Content-Type", "application/json")
createConfigRec := httptest.NewRecorder()
router.ServeHTTP(createConfigRec, createConfigReq)
@@ -269,7 +269,7 @@ func TestConfigMoveToProjectEndpoint(t *testing.T) {
t.Fatalf("unmarshal config: %v", err)
}
moveReq := httptest.NewRequest(http.MethodPatch, "/api/configs/"+created.UUID+"/project", bytes.NewReader([]byte(`{"project_uuid":"`+project.UUID+`"}`)))
moveReq := httptest.NewRequest(http.MethodPatch, "http://127.0.0.1:8080/api/configs/"+created.UUID+"/project", bytes.NewReader([]byte(`{"project_uuid":"`+project.UUID+`"}`)))
moveReq.Header.Set("Content-Type", "application/json")
moveRec := httptest.NewRecorder()
router.ServeHTTP(moveRec, moveReq)
@@ -277,7 +277,7 @@ func TestConfigMoveToProjectEndpoint(t *testing.T) {
t.Fatalf("move config status=%d body=%s", moveRec.Code, moveRec.Body.String())
}
getReq := httptest.NewRequest(http.MethodGet, "/api/configs/"+created.UUID, nil)
getReq := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/configs/"+created.UUID, nil)
getRec := httptest.NewRecorder()
router.ServeHTTP(getRec, getReq)
if getRec.Code != http.StatusOK {
@@ -307,7 +307,7 @@ func TestVendorImportRejectsOversizedUpload(t *testing.T) {
t.Fatalf("setup router: %v", err)
}
createProjectReq := httptest.NewRequest(http.MethodPost, "/api/projects", bytes.NewReader([]byte(`{"name":"Import Project","code":"IMP"}`)))
createProjectReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects", bytes.NewReader([]byte(`{"name":"Import Project","code":"IMP"}`)))
createProjectReq.Header.Set("Content-Type", "application/json")
createProjectRec := httptest.NewRecorder()
router.ServeHTTP(createProjectRec, createProjectReq)
@@ -334,7 +334,7 @@ func TestVendorImportRejectsOversizedUpload(t *testing.T) {
t.Fatalf("close multipart writer: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/projects/"+project.UUID+"/vendor-import", &body)
req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/projects/"+project.UUID+"/vendor-import", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -358,7 +358,7 @@ func TestCreateConfigMalformedJSONReturnsGenericError(t *testing.T) {
t.Fatalf("setup router: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/configs", bytes.NewReader([]byte(`{"name":`)))
req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/configs", bytes.NewReader([]byte(`{"name":`)))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
+27 -21
View File
@@ -1,11 +1,11 @@
module git.mchus.pro/mchus/quoteforge
go 1.24.0
go 1.27.3
require (
github.com/gin-gonic/gin v1.9.1
github.com/gin-gonic/gin v1.12.0
github.com/glebarez/sqlite v1.11.0
github.com/go-sql-driver/mysql v1.7.1
github.com/go-sql-driver/mysql v1.10.1
github.com/google/uuid v1.6.0
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/mysql v1.5.2
@@ -13,35 +13,41 @@ require (
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/glebarez/go-sqlite v1.21.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/stretchr/testify v1.11.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/net v0.46.0 // indirect
golang.org/x/sys v0.37.0 // indirect
golang.org/x/text v0.30.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/net v0.61.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
+67 -56
View File
@@ -1,20 +1,24 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
@@ -25,16 +29,17 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
@@ -46,62 +51,69 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.1 h1:0Gmua0HW1Tv7ANR7hUYwRyD0MG5OJfgvYSZasGZzBic=
github.com/quic-go/quic-go v0.59.1/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
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/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
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/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
@@ -118,4 +130,3 @@ modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
+8 -2
View File
@@ -273,7 +273,10 @@ func createBackupArchive(destPath, dbPath, configPath string) error {
}
if strings.TrimSpace(configPath) != "" {
_ = addZipOptionalFile(zipWriter, configPath)
if err := addZipOptionalFile(zipWriter, configPath); err != nil {
_ = zipWriter.Close()
return fmt.Errorf("archive config: %w", err)
}
}
if err := zipWriter.Close(); err != nil {
@@ -355,7 +358,10 @@ func isSQLiteBusyError(err error) bool {
func addZipOptionalFile(writer *zip.Writer, path string) error {
if _, err := os.Stat(path); err != nil {
return nil
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("stat optional backup file: %w", err)
}
return addZipFile(writer, path)
}
+111
View File
@@ -0,0 +1,111 @@
package appstate
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// CreatePreResetBackup is mandatory and independent of recurring backup settings.
func CreatePreResetBackup(dbPath, configPath string) (string, error) {
root := filepath.Join(resolveBackupRoot(dbPath), "pre-reset")
if err := validateBackupRoot(root); err != nil {
return "", err
}
if err := os.MkdirAll(root, 0700); err != nil {
return "", fmt.Errorf("create pre-reset backup directory: %w", err)
}
resolved, err := filepath.EvalSymlinks(root)
if err != nil {
return "", fmt.Errorf("resolve pre-reset backup directory: %w", err)
}
if err := validateBackupRoot(resolved); err != nil {
return "", err
}
file, err := os.CreateTemp(resolved, "qfs-pre-reset-v1-"+time.Now().UTC().Format("20060102T150405Z")+"-*.zip")
if err != nil {
return "", fmt.Errorf("reserve pre-reset backup: %w", err)
}
path := file.Name()
if err := file.Close(); err != nil {
return "", fmt.Errorf("close pre-reset backup: %w", err)
}
if err := createBackupArchive(path, dbPath, configPath); err != nil {
return "", fmt.Errorf("write pre-reset archive: %w", err)
}
if err := verifyResetArchive(path, filepath.Base(dbPath)); err != nil {
return "", fmt.Errorf("verify pre-reset archive: %w", err)
}
return path, nil
}
func verifyResetArchive(path, dbName string) error {
archive, err := zip.OpenReader(path)
if err != nil {
return fmt.Errorf("open archive: %w", err)
}
defer archive.Close()
dir, err := os.MkdirTemp("", "qfs-verify-reset-*")
if err != nil {
return fmt.Errorf("create verification directory: %w", err)
}
defer os.RemoveAll(dir)
found := false
for _, entry := range archive.File {
in, err := entry.Open()
if err != nil {
return fmt.Errorf("open archive entry: %w", err)
}
var out io.Writer = io.Discard
var restored *os.File
if entry.Name == dbName {
restored, err = os.OpenFile(filepath.Join(dir, "verify.db"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
in.Close()
return fmt.Errorf("create verification database: %w", err)
}
out = restored
found = true
}
_, copyErr := io.Copy(out, in)
closeErr := in.Close()
if restored != nil {
if err := restored.Close(); err != nil {
return fmt.Errorf("close verification database: %w", err)
}
}
if copyErr != nil {
return fmt.Errorf("read archive entry: %w", copyErr)
}
if closeErr != nil {
return fmt.Errorf("close archive entry: %w", closeErr)
}
}
if !found {
return fmt.Errorf("archive has no database snapshot")
}
db, err := gorm.Open(sqlite.Open(filepath.Join(dir, "verify.db")), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
return fmt.Errorf("open restored snapshot: %w", err)
}
sqlDB, err := db.DB()
if err != nil {
return fmt.Errorf("get restored database: %w", err)
}
defer sqlDB.Close()
var result string
if err := db.Raw("PRAGMA integrity_check").Scan(&result).Error; err != nil {
return fmt.Errorf("check restored snapshot: %w", err)
}
if result != "ok" {
return fmt.Errorf("snapshot integrity check failed: %s", result)
}
return nil
}
+54 -17
View File
@@ -1,6 +1,7 @@
package handlers
import (
"errors"
"fmt"
"html/template"
"log/slog"
@@ -13,8 +14,10 @@ import (
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
"git.mchus.pro/mchus/quoteforge/internal/db"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"git.mchus.pro/mchus/quoteforge/internal/mariadb"
"github.com/gin-gonic/gin"
mysqlDriver "github.com/go-sql-driver/mysql"
"gorm.io/gorm"
)
type SetupHandler struct {
@@ -82,14 +85,24 @@ func (h *SetupHandler) TestConnection(c *gin.Context) {
port = p
}
// If password is empty, try to use saved password
if password == "" {
if settings, err := h.localDB.GetSettings(); err == nil && settings != nil {
password = settings.PasswordEncrypted // GetSettings returns decrypted password in this field
}
settings, err := h.localDB.GetSettings()
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
_ = c.Error(err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read settings"})
return
}
password, err = setupPassword(settings, host, port, user, password)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}
dsn := buildMySQLDSN(host, port, database, user, password, 5*time.Second)
tlsMode, caPEM := c.DefaultPostForm("tls_mode", "preferred"), c.PostForm("tls_ca_pem")
dsn, err := buildMySQLDSNWithTLS(host, port, database, user, password, 5*time.Second, tlsMode, caPEM)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}
lotCount, canWrite, err := db.ValidateMariaDBConnection(dsn)
if err != nil {
_ = c.Error(err)
@@ -110,7 +123,12 @@ func (h *SetupHandler) TestConnection(c *gin.Context) {
// SaveConnection saves the connection settings and signals restart
func (h *SetupHandler) SaveConnection(c *gin.Context) {
existingSettings, _ := h.localDB.GetSettings()
existingSettings, settingsErr := h.localDB.GetSettings()
if settingsErr != nil && !errors.Is(settingsErr, gorm.ErrRecordNotFound) {
_ = c.Error(settingsErr)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read settings"})
return
}
host := c.PostForm("host")
portStr := c.PostForm("port")
@@ -123,15 +141,19 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) {
port = p
}
// If password is empty, use saved password
if password == "" {
if settings, err := h.localDB.GetSettings(); err == nil && settings != nil {
password = settings.PasswordEncrypted // GetSettings returns decrypted password in this field
}
password, err := setupPassword(existingSettings, host, port, user, password)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}
// Test connection first
dsn := buildMySQLDSN(host, port, database, user, password, 5*time.Second)
tlsMode, caPEM := c.DefaultPostForm("tls_mode", "preferred"), c.PostForm("tls_ca_pem")
dsn, err := buildMySQLDSNWithTLS(host, port, database, user, password, 5*time.Second, tlsMode, caPEM)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}
if _, _, err := db.ValidateMariaDBConnection(dsn); err != nil {
_ = c.Error(err)
c.JSON(http.StatusBadRequest, gin.H{
@@ -142,7 +164,7 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) {
}
// Save settings
if err := h.localDB.SaveSettings(host, port, database, user, password); err != nil {
if err := h.localDB.SaveSettingsWithTLS(host, port, database, user, password, tlsMode, caPEM); err != nil {
_ = c.Error(err)
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
@@ -165,7 +187,8 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) {
existingSettings.Port != port ||
existingSettings.Database != database ||
existingSettings.User != user ||
existingSettings.PasswordEncrypted != password
existingSettings.PasswordEncrypted != password ||
existingSettings.TLSMode != tlsMode || existingSettings.TLSCAPEM != caPEM
restartQueued := settingsChanged && h.restartSig != nil
c.JSON(http.StatusOK, gin.H{
@@ -195,7 +218,7 @@ func (h *SetupHandler) GetStatus(c *gin.Context) {
})
}
func buildMySQLDSN(host string, port int, database, user, password string, timeout time.Duration) string {
func buildMySQLDSNWithTLS(host string, port int, database, user, password string, timeout time.Duration, tlsMode, caPEM string) (string, error) {
cfg := mysqlDriver.NewConfig()
cfg.User = user
cfg.Passwd = password
@@ -208,5 +231,19 @@ func buildMySQLDSN(host string, port int, database, user, password string, timeo
cfg.Params = map[string]string{
"charset": "utf8mb4",
}
return cfg.FormatDSN()
if err := mariadb.ConfigureTLS(cfg, tlsMode, caPEM); err != nil {
return "", fmt.Errorf("configure TLS: %w", err)
}
return cfg.FormatDSN(), nil
}
// setupPassword reuses a credential only for its saved destination and account.
func setupPassword(saved *localdb.ConnectionSettings, host string, port int, user, password string) (string, error) {
if password != "" || saved == nil {
return password, nil
}
if saved.Host != host || saved.Port != port || saved.User != user {
return "", fmt.Errorf("Password is required when changing host, port or user")
}
return saved.PasswordEncrypted, nil
}
+31
View File
@@ -0,0 +1,31 @@
package handlers
import (
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"testing"
)
func TestSetupPassword(t *testing.T) {
saved := &localdb.ConnectionSettings{Host: "db.example", Port: 3306, User: "example", PasswordEncrypted: "example"}
for _, tt := range []struct {
name, host, user, password string
port int
wantError bool
}{
{"same destination", "db.example", "example", "", 3306, false},
{"changed host", "other.example", "example", "", 3306, true},
{"changed port", "db.example", "example", "", 3307, true},
{"changed user", "db.example", "other", "", 3306, true},
{"explicit password", "other.example", "other", "example", 3307, false},
} {
t.Run(tt.name, func(t *testing.T) {
got, err := setupPassword(saved, tt.host, tt.port, tt.user, tt.password)
if (err != nil) != tt.wantError {
t.Fatalf("unexpected error: %v", err)
}
if !tt.wantError && got != "example" {
t.Fatal("credential not preserved")
}
})
}
}
+37
View File
@@ -0,0 +1,37 @@
package handlers
import (
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"github.com/gin-gonic/gin"
)
func TestSetupFreshSettingsValidateTLS(t *testing.T) {
local, err := localdb.New(filepath.Join(t.TempDir(), "qfs.db"))
if err != nil {
t.Fatal(err)
}
defer local.Close()
handler := &SetupHandler{localDB: local}
for _, test := range []struct {
path string
handler gin.HandlerFunc
}{{"/setup/test", handler.TestConnection}, {"/setup", handler.SaveConnection}} {
router := gin.New()
router.POST(test.path, test.handler)
body := url.Values{"host": {"db.example"}, "user": {"example"}, "tls_mode": {"invalid"}}.Encode()
req := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusUnprocessableEntity {
t.Fatalf("%s: status=%d body=%s", test.path, w.Code, w.Body.String())
}
}
}
+16 -44
View File
@@ -14,6 +14,7 @@ import (
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
"git.mchus.pro/mchus/quoteforge/internal/appstate"
"git.mchus.pro/mchus/quoteforge/internal/mariadb"
"github.com/glebarez/sqlite"
mysqlDriver "github.com/go-sql-driver/mysql"
uuidpkg "github.com/google/uuid"
@@ -24,6 +25,8 @@ import (
// ConnectionSettings stores MariaDB connection credentials
type ConnectionSettings struct {
TLSMode string `gorm:"default:preferred"`
TLSCAPEM string
ID uint `gorm:"primaryKey"`
Host string `gorm:"not null"`
Port int `gorm:"not null;default:3306"`
@@ -50,47 +53,6 @@ var localReadOnlyCacheTables = []string{
"local_partnumber_books",
}
// ResetData clears local data tables while keeping connection settings.
// It does not drop schema or connection_settings.
func ResetData(dbPath string) error {
if strings.TrimSpace(dbPath) == "" {
return nil
}
if _, err := os.Stat(dbPath); err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("stat local db: %w", err)
}
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
return fmt.Errorf("opening sqlite database: %w", err)
}
// Order does not matter because we use DELETEs without FK constraints in SQLite.
tables := []string{
"local_projects",
"local_configurations",
"local_configuration_versions",
"local_pricelists",
"local_pricelist_items",
"local_sync_guard_state",
"pending_changes",
"app_settings",
}
for _, table := range tables {
if err := db.Exec("DELETE FROM " + table).Error; err != nil {
return fmt.Errorf("clear %s: %w", table, err)
}
}
slog.Info("local database data reset", "path", dbPath)
return nil
}
// New creates a new LocalDB instance
func New(dbPath string) (*LocalDB, error) {
// Ensure directory exists
@@ -548,6 +510,14 @@ func (l *LocalDB) GetSettings() (*ConnectionSettings, error) {
// SaveSettings saves connection settings with encrypted password
func (l *LocalDB) SaveSettings(host string, port int, database, user, password string) error {
return l.SaveSettingsWithTLS(host, port, database, user, password, "preferred", "")
}
func (l *LocalDB) SaveSettingsWithTLS(host string, port int, database, user, password, tlsMode, caPEM string) error {
if err := mariadb.ConfigureTLS(mysqlDriver.NewConfig(), tlsMode, caPEM); err != nil {
return fmt.Errorf("validate connection TLS: %w", err)
}
// Encrypt password
encrypted, err := Encrypt(password)
if err != nil {
@@ -556,6 +526,8 @@ func (l *LocalDB) SaveSettings(host string, port int, database, user, password s
settings := ConnectionSettings{
ID: 1, // Always use ID=1 for single settings row
TLSMode: tlsMode,
TLSCAPEM: caPEM,
Host: host,
Port: port,
Database: database,
@@ -601,6 +573,9 @@ func (l *LocalDB) GetDSN() (string, error) {
"charset": "utf8mb4",
}
if err := mariadb.ConfigureTLS(cfg, settings.TLSMode, settings.TLSCAPEM); err != nil {
return "", fmt.Errorf("configure connection TLS: %w", err)
}
return cfg.FormatDSN(), nil
}
@@ -1285,7 +1260,6 @@ func (l *LocalDB) GetLastComponentSyncError() string {
return strings.TrimSpace(value)
}
const openConfigUUIDsKey = "open_config_uuids"
// GetOpenConfigUUIDs returns UUIDs of all configurations currently open in the configurator.
@@ -1361,7 +1335,6 @@ func (l *LocalDB) CountAllPricelistItems() int64 {
return count
}
// DBFilePath returns the path to the SQLite database file.
func (l *LocalDB) DBFilePath() string {
return l.path
@@ -2095,7 +2068,6 @@ func (l *LocalDB) GetLocalPricelistItemsPage(pricelistID uint, search string, pa
return items, total, nil
}
// GetSchemaMigrations returns all applied local schema migrations ordered by applied_at.
func (l *LocalDB) GetSchemaMigrations() ([]LocalSchemaMigration, error) {
var migrations []LocalSchemaMigration
+85
View File
@@ -0,0 +1,85 @@
package localdb
import (
"fmt"
"log/slog"
"os"
"strings"
"git.mchus.pro/mchus/quoteforge/internal/appstate"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func ResetData(dbPath string) error {
configPath, err := appstate.ResolveConfigPathNearDB("", dbPath)
if err != nil {
return fmt.Errorf("resolve reset config: %w", err)
}
return ResetDataWithOptions(dbPath, configPath, false)
}
// ResetDataWithOptions requires a fresh verified backup even for forced resets.
func ResetDataWithOptions(dbPath, configPath string, force bool) error {
if strings.TrimSpace(dbPath) == "" {
return nil
}
if _, err := os.Stat(dbPath); err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("stat reset database: %w", err)
}
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
return fmt.Errorf("open reset database: %w", err)
}
sqlDB, err := db.DB()
if err != nil {
return fmt.Errorf("get reset database: %w", err)
}
defer sqlDB.Close()
return db.Transaction(func(tx *gorm.DB) error {
for _, table := range []string{"pending_changes", "local_projects", "local_configurations"} {
if !tx.Migrator().HasTable(table) {
continue
}
query := tx.Table(table)
if table != "pending_changes" {
if !tx.Migrator().HasColumn(table, "sync_status") {
if !force {
return fmt.Errorf("reset refused: %s has no sync_status; use -reset-localdb -force-reset-localdb after reviewing local work", table)
}
continue
}
query = query.Where("sync_status IS NULL OR sync_status <> ?", "synced")
}
var count int64
if err := query.Count(&count).Error; err != nil {
return fmt.Errorf("check reset data in %s: %w", table, err)
}
if count > 0 && !force {
return fmt.Errorf("reset refused: %s contains %d unsynced rows; sync first or use -reset-localdb -force-reset-localdb", table, count)
}
}
archivePath, err := appstate.CreatePreResetBackup(dbPath, configPath)
if err != nil {
return fmt.Errorf("reset safety backup: %w", err)
}
slog.Info("verified pre-reset backup", "path", archivePath)
for _, table := range []string{
"local_projects", "local_configurations", "local_configuration_versions",
"local_pricelists", "local_pricelist_items", "local_sync_guard_state", "pending_changes", "app_settings",
} {
if !tx.Migrator().HasTable(table) {
continue
}
if err := tx.Exec("DELETE FROM " + table).Error; err != nil {
return fmt.Errorf("clear %s: %w", table, err)
}
}
slog.Info("local database data reset", "path", dbPath, "forced", force)
return nil
})
}
+154
View File
@@ -0,0 +1,154 @@
package localdb
import (
"archive/zip"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func TestResetProtectsUnsyncedData(t *testing.T) {
for _, table := range []string{"pending_changes", "local_projects", "local_configurations"} {
t.Run(table, func(t *testing.T) {
path, db := resetFixture(t)
if err := db.Exec("INSERT INTO " + table + " (sync_status) VALUES ('pending')").Error; err != nil {
t.Fatal(err)
}
err := ResetDataWithOptions(path, "", false)
if err == nil || !strings.Contains(err.Error(), table) {
t.Fatalf("expected refusal naming %s, got %v", table, err)
}
assertResetRows(t, db, table, 1)
})
}
}
func TestResetBackupAndRollback(t *testing.T) {
for _, failDelete := range []bool{false, true} {
t.Run(map[bool]string{false: "reset", true: "rollback"}[failDelete], func(t *testing.T) {
path, db := resetFixture(t)
t.Setenv("QFS_BACKUP_DISABLE", "1")
if err := db.Exec("INSERT INTO local_projects (sync_status) VALUES ('pending')").Error; err != nil {
t.Fatal(err)
}
if failDelete {
if err := db.Exec("CREATE TRIGGER block_reset BEFORE DELETE ON local_configurations BEGIN SELECT RAISE(ABORT, 'blocked'); END").Error; err != nil {
t.Fatal(err)
}
if err := db.Exec("INSERT INTO local_configurations (sync_status) VALUES ('pending')").Error; err != nil {
t.Fatal(err)
}
}
cfg := filepath.Join(filepath.Dir(path), "config.yaml")
if err := os.WriteFile(cfg, []byte("server: {}"), 0600); err != nil {
t.Fatal(err)
}
err := ResetDataWithOptions(path, cfg, true)
if (err != nil) != failDelete {
t.Fatalf("reset: %v", err)
}
want := int64(0)
if failDelete {
want = 1
}
assertResetRows(t, db, "local_projects", want)
archives, err := filepath.Glob(filepath.Join(filepath.Dir(path), "backups", "pre-reset", "*.zip"))
if err != nil || len(archives) != 1 {
t.Fatalf("archives=%v err=%v", archives, err)
}
archive, err := zip.OpenReader(archives[0])
if err != nil {
t.Fatal(err)
}
defer archive.Close()
for _, entry := range archive.File {
if entry.Name != filepath.Base(path) {
continue
}
in, err := entry.Open()
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(in)
in.Close()
if err != nil {
t.Fatal(err)
}
restoredPath := filepath.Join(t.TempDir(), "restored.db")
if err := os.WriteFile(restoredPath, data, 0600); err != nil {
t.Fatal(err)
}
restored, err := gorm.Open(sqlite.Open(restoredPath), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
sqlDB, _ := restored.DB()
defer sqlDB.Close()
assertResetRows(t, restored, "local_projects", 1)
}
assertResetRows(t, db, "connection_settings", 1)
})
}
}
func TestResetRefusesFailedBackup(t *testing.T) {
path, db := resetFixture(t)
if err := db.Exec("INSERT INTO local_projects (sync_status) VALUES ('synced')").Error; err != nil {
t.Fatal(err)
}
t.Setenv("QFS_BACKUP_DIR", path) // A database file cannot be a backup directory.
if err := ResetDataWithOptions(path, "", true); err == nil {
t.Fatal("expected backup refusal")
}
assertResetRows(t, db, "local_projects", 1)
}
func TestResetLegacySchema(t *testing.T) {
path, db := resetFixture(t)
if err := db.Exec("ALTER TABLE local_projects DROP COLUMN sync_status").Error; err != nil {
t.Fatal(err)
}
if err := ResetDataWithOptions(path, "", false); err == nil {
t.Fatal("expected legacy-state refusal")
}
if err := ResetDataWithOptions(path, "", true); err != nil {
t.Fatal(err)
}
}
func resetFixture(t *testing.T) (string, *gorm.DB) {
t.Helper()
t.Setenv("QFS_BACKUP_DIR", "")
path := filepath.Join(t.TempDir(), "qfs.db")
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
sqlDB, _ := db.DB()
t.Cleanup(func() { sqlDB.Close() })
for _, table := range []string{"pending_changes", "local_projects", "local_configurations", "connection_settings"} {
if err := db.Exec("CREATE TABLE " + table + " (id INTEGER PRIMARY KEY, sync_status TEXT)").Error; err != nil {
t.Fatal(err)
}
}
if err := db.Exec("INSERT INTO connection_settings (sync_status) VALUES ('synced')").Error; err != nil {
t.Fatal(err)
}
return path, db
}
func assertResetRows(t *testing.T, db *gorm.DB, table string, want int64) {
t.Helper()
var count int64
if err := db.Table(table).Count(&count).Error; err != nil {
t.Fatal(err)
}
if count != want {
t.Fatalf("%s has %d rows, want %d", table, count, want)
}
}
+34
View File
@@ -0,0 +1,34 @@
package localdb
import (
mysql "github.com/go-sql-driver/mysql"
"testing"
)
func TestSettingsTLSRoundTrip(t *testing.T) {
t.Setenv("QFS_STATE_DIR", t.TempDir())
local := newModeDB(t)
for _, mode := range []string{"preferred", "required", "verify-full"} {
if err := local.SaveSettingsWithTLS("db.example", 3306, "example", "example", "example", mode, ""); err != nil {
t.Fatal(err)
}
settings, err := local.GetSettings()
if err != nil {
t.Fatal(err)
}
if settings.TLSMode != mode {
t.Fatalf("mode=%s, want %s", settings.TLSMode, mode)
}
dsn, err := local.GetDSN()
if err != nil {
t.Fatal(err)
}
cfg, err := mysql.ParseDSN(dsn)
if err != nil {
t.Fatal(err)
}
if cfg.TLS == nil || cfg.AllowFallbackToPlaintext != (mode == "preferred") {
t.Fatalf("wrong TLS policy for %s", mode)
}
}
}
+71
View File
@@ -0,0 +1,71 @@
package mariadb
import (
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"fmt"
"strings"
mysql "github.com/go-sql-driver/mysql"
)
// ConfigureTLS configures the DSN so setup and runtime use the same TLS policy.
func ConfigureTLS(cfg *mysql.Config, mode, caPEM string) error {
mode = strings.TrimSpace(mode)
if mode == "" {
mode = "preferred"
}
caPEM = strings.TrimSpace(caPEM)
if caPEM != "" && mode != "verify-ca" && mode != "verify-full" {
return fmt.Errorf("CA certificate requires verify-ca or verify-full")
}
switch mode {
case "preferred":
cfg.TLSConfig = "preferred"
return nil
case "required":
cfg.TLSConfig = "skip-verify"
return nil
case "verify-full":
if caPEM == "" {
cfg.TLSConfig = "true"
return nil
}
case "verify-ca":
if caPEM == "" {
return fmt.Errorf("verify-ca requires a CA certificate")
}
default:
return fmt.Errorf("unsupported MariaDB TLS mode")
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM([]byte(caPEM)) {
return fmt.Errorf("invalid CA certificate PEM")
}
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
if mode == "verify-ca" {
// Verify the certificate chain explicitly; this mode omits hostname checks.
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
if len(state.PeerCertificates) == 0 {
return fmt.Errorf("MariaDB did not provide a certificate")
}
intermediates := x509.NewCertPool()
for _, cert := range state.PeerCertificates[1:] {
intermediates.AddCert(cert)
}
_, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{Roots: roots, Intermediates: intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}})
if err != nil {
return fmt.Errorf("verify MariaDB certificate: %w", err)
}
return nil
}
}
name := fmt.Sprintf("qfs-%x", sha256.Sum256([]byte(mode+"\n"+caPEM)))
if err := mysql.RegisterTLSConfig(name, tlsConfig); err != nil {
return fmt.Errorf("register MariaDB TLS: %w", err)
}
cfg.TLSConfig = name
return nil
}
+97
View File
@@ -0,0 +1,97 @@
package mariadb
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"testing"
"time"
mysql "github.com/go-sql-driver/mysql"
)
func TestTLSPolicy(t *testing.T) {
ca, cert := testCertificate(t)
_, other := testCertificate(t)
for _, tt := range []struct {
mode, ca string
wantError, fallback, insecure bool
}{
{"", "", false, true, true},
{"preferred", "", false, true, true},
{"required", "", false, false, true},
{"verify-full", "", false, false, false},
{"verify-full", ca, false, false, false},
{"verify-ca", ca, false, false, true},
{"verify-ca", "", true, false, false},
{"verify-full", "invalid", true, false, false},
{"preferred", ca, true, false, false},
{"false", "", true, false, false},
} {
t.Run(tt.mode+tt.ca[:min(len(tt.ca), 5)], func(t *testing.T) {
cfg := mysql.NewConfig()
cfg.Net, cfg.Addr = "tcp", "db.example:3306"
err := ConfigureTLS(cfg, tt.mode, tt.ca)
if (err != nil) != tt.wantError {
t.Fatalf("configure: %v", err)
}
if tt.wantError {
return
}
parsed, err := mysql.ParseDSN(cfg.FormatDSN())
if err != nil {
t.Fatal(err)
}
if parsed.TLS == nil || parsed.AllowFallbackToPlaintext != tt.fallback || parsed.TLS.InsecureSkipVerify != tt.insecure {
t.Fatalf("unexpected TLS policy for %s", tt.mode)
}
if tt.mode == "verify-ca" {
if err := parsed.TLS.VerifyConnection(tls.ConnectionState{PeerCertificates: []*x509.Certificate{cert}}); err != nil {
t.Fatal(err)
}
for _, chain := range [][]*x509.Certificate{nil, {other}} {
if err := parsed.TLS.VerifyConnection(tls.ConnectionState{PeerCertificates: chain}); err == nil {
t.Fatal("untrusted certificate accepted")
}
}
}
if tt.mode == "verify-full" && tt.ca != "" {
if parsed.TLS.ServerName != "db.example" {
t.Fatalf("missing hostname verification: %s", parsed.TLS.ServerName)
}
if _, err := cert.Verify(x509.VerifyOptions{Roots: parsed.TLS.RootCAs, DNSName: parsed.TLS.ServerName}); err != nil {
t.Fatal(err)
}
if _, err := other.Verify(x509.VerifyOptions{Roots: parsed.TLS.RootCAs, DNSName: parsed.TLS.ServerName}); err == nil {
t.Fatal("untrusted certificate accepted")
}
if _, err := cert.Verify(x509.VerifyOptions{Roots: parsed.TLS.RootCAs, DNSName: "other.example"}); err == nil {
t.Fatal("wrong hostname accepted")
}
}
})
}
}
func testCertificate(t *testing.T) (string, *x509.Certificate) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "example"}, DNSNames: []string{"db.example"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
t.Fatal(err)
}
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})), cert
}
+27 -1
View File
@@ -1,6 +1,7 @@
package middleware
import (
"mime"
"net"
"net/http"
"net/url"
@@ -11,6 +12,19 @@ import (
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
hostURL, hostErr := url.Parse("http://" + c.Request.Host)
if hostErr != nil || hostURL.Host != c.Request.Host || hostURL.Path != "" || hostURL.RawQuery != "" || !isLoopbackOrigin("http://"+c.Request.Host) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Invalid request host"})
return
}
if c.GetHeader("Sec-Fetch-Site") == "cross-site" {
c.AbortWithStatus(http.StatusForbidden)
return
}
if referer := c.GetHeader("Referer"); referer != "" && !isLoopbackOrigin(referer) {
c.AbortWithStatus(http.StatusForbidden)
return
}
origin := strings.TrimSpace(c.GetHeader("Origin"))
if origin != "" {
if isLoopbackOrigin(origin) {
@@ -20,7 +34,7 @@ func CORS() gin.HandlerFunc {
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Disposition")
c.Header("Access-Control-Max-Age", "86400")
} else if c.Request.Method == http.MethodOptions {
} else {
c.AbortWithStatus(http.StatusForbidden)
return
}
@@ -30,6 +44,15 @@ func CORS() gin.HandlerFunc {
c.AbortWithStatus(http.StatusNoContent)
return
}
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead &&
strings.HasPrefix(c.Request.URL.Path, "/api/") && c.Request.ContentLength != 0 {
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
isUpload := strings.HasPrefix(c.FullPath(), "/api/projects/") && strings.HasSuffix(c.FullPath(), "/vendor-import")
if err != nil || (mediaType != "application/json" && !(isUpload && mediaType == "multipart/form-data")) {
c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{"error": "Unsupported content type"})
return
}
}
c.Next()
}
@@ -43,6 +66,9 @@ func isLoopbackOrigin(origin string) bool {
if u.Scheme != "http" && u.Scheme != "https" {
return false
}
if u.User != nil || u.Opaque != "" {
return false
}
host := strings.TrimSpace(u.Hostname())
if host == "" {
return false
+66
View File
@@ -0,0 +1,66 @@
package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestLocalRequestBoundary(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name, method, path, host, origin, referer, fetchSite, contentType, body string
want int
}{
{name: "CLI JSON", method: "POST", contentType: "application/json", body: "{}", want: 200},
{name: "local browser", method: "POST", origin: "http://localhost:8080", contentType: "application/json; charset=utf-8", body: "{}", want: 200},
{name: "foreign form", method: "POST", path: "/setup", origin: "https://attacker.example", contentType: "application/x-www-form-urlencoded", body: "host=example", want: 403},
{name: "foreign JSON", method: "POST", origin: "https://attacker.example", contentType: "text/plain", body: "{}", want: 403},
{name: "rebind read", method: "GET", host: "attacker.example:8080", want: 403},
{name: "null origin", method: "POST", origin: "null", want: 403},
{name: "foreign referer", method: "POST", referer: "https://attacker.example/page", want: 403},
{name: "cross site", method: "POST", fetchSite: "cross-site", want: 403},
{name: "plain JSON", method: "POST", contentType: "text/plain", body: "{}", want: 415},
{name: "API form", method: "POST", contentType: "application/x-www-form-urlencoded", body: "x=y", want: 415},
{name: "setup form", method: "POST", path: "/setup", origin: "http://127.0.0.1:8080", contentType: "application/x-www-form-urlencoded", body: "host=example", want: 200},
{name: "upload", method: "POST", path: "/api/projects/id/vendor-import", contentType: "multipart/form-data; boundary=example", body: "example", want: 200},
{name: "multipart JSON route", method: "POST", contentType: "multipart/form-data; boundary=example", body: "example", want: 415},
{name: "bodyless action", method: "POST", want: 200},
{name: "local preflight", method: "OPTIONS", origin: "http://localhost:8080", want: 204},
{name: "foreign preflight", method: "OPTIONS", origin: "https://attacker.example", want: 403},
{name: "IPv6", method: "GET", host: "[::1]:8080", want: 200},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router := gin.New()
router.Use(CORS())
called := false
handler := func(c *gin.Context) { called = true; c.Status(200) }
router.Any("/api/configs", handler)
router.Any("/setup", handler)
router.POST("/api/projects/:uuid/vendor-import", handler)
path := tt.path
if path == "" {
path = "/api/configs"
}
req := httptest.NewRequest(tt.method, path, strings.NewReader(tt.body))
req.Host = tt.host
if req.Host == "" {
req.Host = "127.0.0.1:8080"
}
for key, value := range map[string]string{"Origin": tt.origin, "Referer": tt.referer, "Sec-Fetch-Site": tt.fetchSite, "Content-Type": tt.contentType} {
if value != "" {
req.Header.Set(key, value)
}
}
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != tt.want || called != (tt.want == http.StatusOK) {
t.Fatalf("status=%d called=%v, want %d", w.Code, called, tt.want)
}
})
}
}
+64
View File
@@ -0,0 +1,64 @@
package models
import (
"fmt"
"strings"
"gorm.io/gorm"
)
type migrationVerification struct {
description string
query string
}
func parseMigrationVerifications(script string) ([]migrationVerification, error) {
var checks []migrationVerification
for _, line := range strings.Split(script, "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "-- verify:") {
continue
}
description, query, ok := strings.Cut(strings.TrimPrefix(line, "-- verify:"), "|")
description, query = strings.TrimSpace(description), strings.TrimSpace(query)
if !ok || description == "" || query == "" {
return nil, fmt.Errorf("invalid migration verify header")
}
checks = append(checks, migrationVerification{description: description, query: query})
}
return checks, nil
}
func applySQLMigrationFile(db *gorm.DB, filename, content string) error {
checks, err := parseMigrationVerifications(content)
if err != nil {
return fmt.Errorf("parse migration %s: %w", filename, err)
}
return db.Connection(func(conn *gorm.DB) error {
if err := executeMigrationStatements(conn, filename, splitSQLStatements(content)); err != nil {
return err
}
for _, check := range checks {
rows, err := conn.Raw(check.query).Rows()
if err != nil {
return fmt.Errorf("verify migration %s (%s): %w", filename, check.description, err)
}
failed := rows.Next()
rowErr := rows.Err()
closeErr := rows.Close()
if rowErr != nil {
return fmt.Errorf("read migration verification %s (%s): %w", filename, check.description, rowErr)
}
if closeErr != nil {
return fmt.Errorf("close migration verification %s (%s): %w", filename, check.description, closeErr)
}
if failed {
return fmt.Errorf("verify migration %s failed: %s", filename, check.description)
}
}
if err := conn.Create(&SQLSchemaMigration{Filename: filename}).Error; err != nil {
return fmt.Errorf("record migration %s: %w", filename, err)
}
return nil
})
}
@@ -0,0 +1,69 @@
package models
import (
"path/filepath"
"strings"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func TestMigrationVerification(t *testing.T) {
for _, tt := range []struct{ name, content, wantError string }{
{"valid", "-- verify: bad value | SELECT 1 FROM example WHERE value <> 1\nCREATE TEMP TABLE example (value INT); INSERT INTO example VALUES (1);", ""},
{"failed", "-- verify: bad value | SELECT 1 FROM example WHERE value <> 1\nCREATE TEMP TABLE example (value INT); INSERT INTO example VALUES (2);", "bad value"},
{"query error", "-- verify: missing table | SELECT 1 FROM missing\nCREATE TEMP TABLE example (value INT);", "missing table"},
{"malformed", "-- verify: no query\nCREATE TABLE example (value INT);", "invalid migration verify header"},
{"second check fails", "-- verify: first | SELECT 1 WHERE 0\n-- verify: second | SELECT 1\nCREATE TEMP TABLE example (value INT);", "second"},
{"execution failure", "-- verify: none | SELECT 1 WHERE 0\nINVALID SQL;", "exec migration"},
} {
t.Run(tt.name, func(t *testing.T) {
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "migration.db")), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
sqlDB, _ := db.DB()
defer sqlDB.Close()
if err := db.AutoMigrate(&SQLSchemaMigration{}); err != nil {
t.Fatal(err)
}
err = applySQLMigrationFile(db, "001_example.sql", tt.content)
if tt.wantError != "" && (err == nil || !strings.Contains(err.Error(), tt.wantError)) {
t.Fatalf("want %q, got %v", tt.wantError, err)
}
if tt.wantError == "" && err != nil {
t.Fatal(err)
}
var count int64
if err := db.Model(&SQLSchemaMigration{}).Count(&count).Error; err != nil {
t.Fatal(err)
}
if (count == 1) != (tt.wantError == "") {
t.Fatalf("incorrect history count=%d", count)
}
if tt.name == "malformed" && db.Migrator().HasTable("example") {
t.Fatal("malformed header mutated database")
}
})
}
}
func TestMigrationErrorAllowlist(t *testing.T) {
for _, tt := range []struct {
message string
want bool
}{
{"Duplicate column name 'example'", true},
{"Duplicate key name 'example'", true},
{"Table 'example' already exists", true},
{"Can't create table example (errno: 150 Foreign key constraint is incorrectly formed)", false},
{"Can't create table example (errno: 121 Duplicate key)", false},
{"Duplicate foreign key constraint name 'example'", false},
{"Access denied", false},
} {
if got := isIgnorableMigrationError(tt.message); got != tt.want {
t.Errorf("%s: got %v", tt.message, got)
}
}
}
+2 -10
View File
@@ -157,13 +157,8 @@ func RunSQLMigrations(db *gorm.DB, migrations fs.FS, onApply func(filename strin
return applied, fmt.Errorf("read migration %s: %w", filename, err)
}
if statements := splitSQLStatements(string(content)); len(statements) > 0 {
if err := executeMigrationStatements(db, filename, statements); err != nil {
return applied, err
}
}
if err := db.Create(&SQLSchemaMigration{Filename: filename}).Error; err != nil {
return applied, fmt.Errorf("record migration %s: %w", filename, err)
if err := applySQLMigrationFile(db, filename, string(content)); err != nil {
return applied, err
}
applied = append(applied, filename)
}
@@ -235,9 +230,6 @@ func isIgnorableMigrationError(message string) bool {
"duplicate column name",
"duplicate key name",
"already exists",
"can't create table",
"duplicate foreign key constraint name",
"errno 121",
}
for _, pattern := range ignorable {
if strings.Contains(lower, pattern) {
+3
View File
@@ -21,6 +21,9 @@ fi
echo -e "${GREEN}Building QuoteForge version: ${VERSION}${NC}"
echo ""
# Stop before creating release artifacts if reachable vulnerabilities are found.
make security-check
ensure_release_notes() {
local notes_path="$1"
if [ -f "${notes_path}" ]; then
+55
View File
@@ -0,0 +1,55 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync('web/templates/index.html', 'utf8');
const base = fs.readFileSync('web/templates/base.html', 'utf8');
const nodes = {};
const listeners = {};
const calls = [];
const context = vm.createContext({
document: {
getElementById: id => nodes[id] ??= {},
createElement: () => ({}),
addEventListener: (name, handler) => listeners[name] = handler,
},
setTimeout: () => {},
cart: [], allComponents: [], currentTab: 'cpu',
getTabForCategory: () => 'cpu', getDisplayPrice: () => 1,
qualityDotHtml: () => '', formatMoney: String, formatPriceOrNA: String,
removeFromCart: lot => calls.push(['remove', lot]),
updateMultiQuantity: (lot, value) => calls.push(['quantity', lot, value]),
onRentalConditionChange: (lot, value) => calls.push(['condition', lot, value]),
showAutocompleteEditItem: lot => calls.push(['edit', lot]),
});
function loadFunction(text, name) {
const start = text.indexOf(`function ${name}(`);
assert(start >= 0);
const end = text.indexOf('\n}', start);
// Functions in base.html have eight spaces of indentation.
const baseEnd = text.indexOf('\n }', start);
vm.runInContext(text.slice(start, (end < 0 ? baseEnd + 10 : end + 2)), context);
}
vm.runInContext(fs.readFileSync('web/static/html-escape.js', 'utf8'), context);
loadFunction(source, 'renderMultiSelectTab');
vm.runInContext(source.split('<script>')[1].split('// Tab configuration')[0], context);
loadFunction(base, 'showToast');
nodes.toast = {replaceChildren: child => nodes.toast.child = child};
for (const lot of [`LOT'\"<img src=x onerror=alert(1)>`, 'LOT&#X61;&#39;);alert(1)//', 'LOT\\\'()&<>']) {
context.cart = [{lot_name: lot, quantity: 1, category: 'cpu'}];
context.renderMultiSelectTab([]);
const html = nodes['tab-content'].innerHTML;
assert(html.includes(`data-lot="${context.escapeHtml(lot)}"`));
assert(!html.includes(lot));
assert(!html.includes('onclick="removeFromCart('));
listeners.click({target: {closest: () => ({dataset: {lot}})}});
listeners.change({target: {dataset: {lot, cartAction: 'quantity'}, value: '2'}});
listeners.change({target: {dataset: {lot, cartAction: 'condition'}, checked: true}});
listeners.focusin({target: {dataset: {lot, cartAction: 'edit'}}});
assert(calls.splice(0).every(call => call[1] === lot));
context.showToast(lot, 'error');
assert.equal(nodes.toast.child.textContent, lot);
assert.equal(nodes.toast.child.innerHTML, undefined);
}
assert.equal(context.escapeHtml(0), '0');
assert.equal(context.escapeHtml(null), '');
console.log('HTML security regressions passed');
+9
View File
@@ -0,0 +1,9 @@
// Escape text for HTML text nodes and quoted attributes, never JavaScript code.
function escapeHtml(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
+11 -7
View File
@@ -10,6 +10,7 @@
<script src="/static/vendor/htmx-1.9.10.min.js"></script>
<script>window.QF_INDICATOR_MODE = "{{ .IndicatorMode }}";</script>
<script src="/static/price-quality.js"></script>
<script src="/static/html-escape.js"></script>
<style>
.htmx-request { opacity: 0.5; }
.line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
@@ -222,7 +223,10 @@
function showToast(msg, type) {
const colors = { success: 'bg-green-500', error: 'bg-red-500', info: 'bg-blue-500' };
const el = document.getElementById('toast');
el.innerHTML = '<div class="' + (colors[type] || colors.info) + ' text-white px-4 py-2 rounded shadow">' + msg + '</div>';
const message = document.createElement('div');
message.className = (colors[type] || colors.info) + ' text-white px-4 py-2 rounded shadow';
message.textContent = msg;
el.replaceChildren(message);
setTimeout(() => el.innerHTML = '', 3000);
}
@@ -340,11 +344,11 @@
const shortUUID = ch.entity_uuid.substring(0, 8);
const time = new Date(ch.created_at).toLocaleString('ru-RU');
const hasError = ch.last_error ? ' border-l-2 border-red-400 pl-2' : '';
const errorLine = ch.last_error ? `<div class="text-red-500 text-xs mt-0.5">${ch.last_error}</div>` : '';
const errorLine = ch.last_error ? `<div class="text-red-500 text-xs mt-0.5">${escapeHtml(ch.last_error)}</div>` : '';
return `<div class="bg-gray-50 rounded px-3 py-1.5${hasError}">
<span class="font-medium">${ch.operation}</span>
<span class="text-gray-500">${ch.entity_type}</span>
<span class="font-mono text-xs text-gray-400">${shortUUID}</span>
<span class="font-medium">${escapeHtml(ch.operation)}</span>
<span class="text-gray-500">${escapeHtml(ch.entity_type)}</span>
<span class="font-mono text-xs text-gray-400">${escapeHtml(shortUUID)}</span>
<span class="text-gray-400 text-xs ml-1">${time}</span>
${errorLine}
</div>`;
@@ -362,7 +366,7 @@
errorsList.innerHTML = data.errors.map(error => {
const time = new Date(error.timestamp).toLocaleString('ru-RU');
return `<div class="bg-red-50 text-red-700 rounded px-3 py-1.5">
<span class="text-xs text-red-400">${time}</span>: ${error.message}
<span class="text-xs text-red-400">${time}</span>: ${escapeHtml(error.message)}
</div>`;
}).join('');
} else {
@@ -409,7 +413,7 @@
resultDiv.className = 'mt-2 text-sm text-yellow-700 bg-yellow-50 rounded px-3 py-2';
resultDiv.textContent = 'Нечего исправлять или проблемы остались';
if (data.remaining_errors && data.remaining_errors.length > 0) {
resultDiv.innerHTML += '<div class="mt-1 text-xs">' + data.remaining_errors.join('<br>') + '</div>';
resultDiv.innerHTML += '<div class="mt-1 text-xs">' + data.remaining_errors.map(escapeHtml).join('<br>') + '</div>';
}
}
} else {
-5
View File
@@ -36,11 +36,6 @@ const configUUID = '{{.ConfigUUID}}';
let configData = null;
let projectData = null;
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text || '';
return div.innerHTML;
}
function formatMoney(value) {
const num = Number(value);
-5
View File
@@ -408,11 +408,6 @@ async function resolveUniqueConfigName(baseName, projectUUID, excludeUUID) {
return {name: candidate, changed: true};
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
async function deleteConfig(uuid) {
if (!confirm('Переместить конфигурацию в архив?')) return;
+22 -14
View File
@@ -404,6 +404,18 @@
</style>
<script>
document.addEventListener('click', event => {
const button = event.target.closest('[data-cart-action="remove"]');
if (button) removeFromCart(button.dataset.lot);
});
document.addEventListener('change', event => {
const input = event.target;
if (input.dataset.cartAction === 'quantity') updateMultiQuantity(input.dataset.lot, input.value);
if (input.dataset.cartAction === 'condition') onRentalConditionChange(input.dataset.lot, input.checked);
});
document.addEventListener('focusin', event => {
if (event.target.dataset.cartAction === 'edit') showAutocompleteEditItem(event.target.dataset.lot, event.target);
});
// Tab configuration comes from /api/configurator-settings (qt_settings.tab_config,
// or the Go-side fallback when the key is absent) — see applyServerSettings().
// Only "other" is client-owned: it collects categories not listed in any tab.
@@ -1523,7 +1535,7 @@ function renderSingleSelectTab(categories) {
<div class="autocomplete-wrapper relative">
<input type="text"
id="input-${cat}"
value="${selectedItem?.lot_name || ''}"
value="${escapeHtml(selectedItem?.lot_name || '')}"
placeholder="Введите артикул..."
class="w-full px-2 py-1 border rounded text-sm font-mono"
autocomplete="off" onfocus="showAutocomplete('${cat}', this)"
@@ -1592,7 +1604,7 @@ function renderMultiSelectTab(components) {
<input type="text"
value="${escapeHtml(item.lot_name)}"
class="w-full px-2 py-1 border rounded text-sm font-mono"
autocomplete="off" onfocus="showAutocompleteEditItem('${item.lot_name}', this)"
autocomplete="off" data-lot="${escapeHtml(item.lot_name)}" data-cart-action="edit"
oninput="filterAutocompleteEditItem(this.value)"
onkeydown="handleAutocompleteKeyEditItem(event)">
</div>
@@ -1601,12 +1613,12 @@ function renderMultiSelectTab(components) {
<td class="px-3 py-2 text-sm text-right">${formatPriceOrNA(item.estimate_price ?? item.unit_price)}</td>
<td class="px-3 py-2 text-center">
<input type="number" min="1" value="${item.quantity}"
onchange="updateMultiQuantity('${item.lot_name}', this.value)"
data-lot="${escapeHtml(item.lot_name)}" data-cart-action="quantity"
class="w-16 px-2 py-1 border rounded text-center text-sm">
</td>
<td class="px-3 py-2 text-sm text-right font-medium">${formatMoney(total)}</td>
<td class="px-3 py-2 text-center">
<button onclick="removeFromCart('${item.lot_name}')" class="text-red-500 hover:text-red-700">
<button data-lot="${escapeHtml(item.lot_name)}" data-cart-action="remove" class="text-red-500 hover:text-red-700">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
@@ -1704,7 +1716,7 @@ function renderMultiSelectTabWithSections(sections) {
value="${escapeHtml(item.lot_name)}"
data-categories="${categoriesStr}"
class="w-full px-2 py-1 border rounded text-sm font-mono"
autocomplete="off" onfocus="showAutocompleteEditItem('${item.lot_name}', this)"
autocomplete="off" data-lot="${escapeHtml(item.lot_name)}" data-cart-action="edit"
oninput="filterAutocompleteEditItem(this.value)"
onkeydown="handleAutocompleteKeyEditItem(event)">
</div>
@@ -1713,12 +1725,12 @@ function renderMultiSelectTabWithSections(sections) {
<td class="px-3 py-2 text-sm text-right">${formatPriceOrNA(item.estimate_price ?? item.unit_price)}</td>
<td class="px-3 py-2 text-center">
<input type="number" min="1" value="${item.quantity}"
onchange="updateMultiQuantity('${item.lot_name}', this.value)"
data-lot="${escapeHtml(item.lot_name)}" data-cart-action="quantity"
class="w-16 px-2 py-1 border rounded text-center text-sm">
</td>
<td class="px-3 py-2 text-sm text-right font-medium">${formatMoney(total)}</td>
<td class="px-3 py-2 text-center">
<button onclick="removeFromCart('${item.lot_name}')" class="text-red-500 hover:text-red-700">
<button data-lot="${escapeHtml(item.lot_name)}" data-cart-action="remove" class="text-red-500 hover:text-red-700">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
@@ -2300,7 +2312,7 @@ function updateCartUI() {
</div>
<div class="flex items-center space-x-2">
<span>${formatMoney(itemTotal)}</span>
<button onclick="removeFromCart('${item.lot_name}')" class="text-red-500 hover:text-red-700">
<button data-lot="${escapeHtml(item.lot_name)}" data-cart-action="remove" class="text-red-500 hover:text-red-700">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
@@ -3410,7 +3422,7 @@ async function renderRentalTab() {
return `<tr class="pricing-row-buy">
<td class="px-3 py-1.5 text-center text-xs border-t border-gray-200">
<input type="checkbox" ${isUsed ? 'checked' : ''}
onchange="onRentalConditionChange('${escapeHtml(item.lot_name).replace(/'/g, "\\'")}', this.checked)"
data-lot="${escapeHtml(item.lot_name)}" data-cart-action="condition"
class="rounded border-gray-300">
</td>
<td class="px-3 py-1.5 text-xs border-t border-gray-200">${escapeHtml(item.lot_name)}</td>
@@ -4154,7 +4166,7 @@ function _renderBOMParsedTable() {
let suffix = '';
if (qtyMismatch) suffix = ` <span class="text-yellow-600 text-xs">≠est(${cartQty})</span>`;
else if (notInCart) suffix = ` <span class="text-orange-500 text-xs">новый</span>`;
lotCell = `<div><span class="font-mono text-xs">${row.resolved_lot}</span>${suffix}</div>${renderBOMLotAllocationsEditor(idx)}`;
lotCell = `<div><span class="font-mono text-xs">${escapeHtml(row.resolved_lot)}</span>${suffix}</div>${renderBOMLotAllocationsEditor(idx)}`;
}
tr.innerHTML = `
@@ -5114,10 +5126,6 @@ async function exportPricingCSV(table) {
}
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function formatCurrency(val) {
if (val == null) return '—';
-9
View File
@@ -159,15 +159,6 @@
return 5;
}
function escapeHtml(text) {
if (text === null || text === undefined) return '';
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function renderItems(items) {
if (items.length === 0) {
-5
View File
@@ -354,11 +354,6 @@ let projectVariants = [];
let projectsCatalog = [];
let variantMenuInitialized = false;
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text || '';
return div.innerHTML;
}
function formatMoneyNoDecimals(value) {
const safe = Number.isFinite(Number(value)) ? Number(value) : 0;
-5
View File
@@ -80,11 +80,6 @@ let variantsLoaded = false;
const trackerBaseURL = 'https://tracker.yandex.ru/';
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text || '';
return div.innerHTML;
}
function formatMoney(v) {
return '$' + (v || 0).toLocaleString('ru-RU', {minimumFractionDigits: 2});
+17 -1
View File
@@ -75,10 +75,26 @@
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="{{if .Settings}}********{{else}}password{{end}}">
{{if .Settings}}
<p class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы сохранить текущий пароль</p>
<p class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы сохранить пароль для того же хоста, порта и пользователя</p>
{{end}}
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1" for="tls_mode">TLS</label>
<select name="tls_mode" id="tls_mode" class="w-full px-3 py-2 border rounded-md">
<option value="preferred" {{if .Settings}}{{if eq .Settings.TLSMode "preferred"}}selected{{end}}{{end}}>Preferred: шифрование, если сервер поддерживает</option>
<option value="required" {{if .Settings}}{{if eq .Settings.TLSMode "required"}}selected{{end}}{{end}}>Required: обязательное шифрование</option>
<option value="verify-ca" {{if .Settings}}{{if eq .Settings.TLSMode "verify-ca"}}selected{{end}}{{end}}>Verify CA: проверка сертификата</option>
<option value="verify-full" {{if .Settings}}{{if eq .Settings.TLSMode "verify-full"}}selected{{end}}{{end}}>Verify full: проверка сертификата и имени сервера</option>
</select>
<p class="text-xs text-gray-500 mt-1">Preferred допускает соединение без TLS. Для проверки подлинности сервера выберите Verify full.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1" for="tls_ca_pem">CA-сертификат (PEM)</label>
<textarea name="tls_ca_pem" id="tls_ca_pem" rows="3" class="w-full px-3 py-2 border rounded-md font-mono text-xs">{{if .Settings}}{{.Settings.TLSCAPEM}}{{end}}</textarea>
<p class="text-xs text-gray-500 mt-1">Для Verify CA обязателен; Verify full без PEM использует системные сертификаты.</p>
</div>
<div id="status" class="hidden p-3 rounded-md text-sm"></div>
<div class="flex space-x-3 pt-4 mt-auto">