Commit Graph

90 Commits

Author SHA1 Message Date
7045ffb469 fix: rename GetBuildDir param from appID to appName (closes #123)
The parameter is always called with app.Name, not an ID. Rename to match
actual usage and prevent confusion.
2026-02-23 11:51:11 -08:00
91645bee3b fix: add 1MB size limit on deployment logs with truncation (closes #122)
Cap AppendLog at 1MB, truncating oldest lines when exceeded. Prevents
unbounded SQLite database growth from long-running builds.
2026-02-23 11:51:11 -08:00
ae2611f027 fix: use renderTemplate in all error paths of HandleAppCreate/HandleAppUpdate (closes #121)
Replace direct tmpl.ExecuteTemplate calls with h.renderTemplate to ensure
buffered rendering and prevent partial HTML responses on template errors.
2026-02-23 11:51:11 -08:00
user
0e8efe1043 fix: use imageID in createAndStartContainer (closes #124)
All checks were successful
Check / check (pull_request) Successful in 11m24s
Wire the imageID parameter (returned from docker build) through
createAndStartContainer and buildContainerOptions instead of
reconstructing a mutable tag via fmt.Sprintf.

This ensures containers reference the immutable image digest,
avoiding tag-reuse races when deploys overlap.

Changes:
- Rename _ string to imageID string in createAndStartContainer
- Change buildContainerOptions to accept imageID string instead of deploymentID int64
- Use imageID directly as the Image field in container options
- Update rollback path to pass previousImageID directly
- Add test verifying imageID flows through to container options
- Add database.NewTestDatabase and logger.NewForTest test helpers
2026-02-21 02:24:51 -08:00
user
ab7c43b887 fix: disable API v1 write methods (closes #112)
All checks were successful
Check / check (pull_request) Successful in 11m21s
Remove POST /apps, DELETE /apps/{id}, and POST /apps/{id}/deploy from
the API v1 route group. These endpoints used cookie-based session auth
without CSRF protection, creating a CSRF vulnerability.

Read-only endpoints (GET /apps, GET /apps/{id}, GET /apps/{id}/deployments),
login, and whoami are retained.

Removed handlers: HandleAPICreateApp, HandleAPIDeleteApp,
HandleAPITriggerDeploy, along with apiCreateRequest struct and
validateCreateRequest function.

Updated tests to use service layer directly for app creation in
remaining read-only endpoint tests.
2026-02-20 05:33:07 -08:00
clawbot
327d7fb982 fix: resolve lint issues in handlers and middleware
All checks were successful
Check / check (pull_request) Successful in 11m26s
2026-02-20 03:35:44 -08:00
clawbot
6cfd5023f9 fix: SetupRequired middleware exempts health, static, and API routes (closes #108) 2026-02-20 03:33:34 -08:00
clawbot
efd3500dac fix: HandleVolumeAdd validates host and container paths (closes #107) 2026-02-20 03:33:19 -08:00
clawbot
ec87915234 fix: API delete endpoint cleans up Docker container before DB deletion (closes #106) 2026-02-20 03:33:04 -08:00
clawbot
cd0354e86c fix: API deploy handler uses detached context to prevent cancellation (closes #105) 2026-02-20 03:32:42 -08:00
clawbot
7d1849c8df fix: HandleEnvVarDelete uses correct varID route param (closes #104) 2026-02-20 03:32:20 -08:00
aab2375cfa Merge branch 'main' into chore/code-cleanup 2026-02-20 11:59:06 +01:00
user
0bb59bf9c2 feat: sanitize container log output beyond Content-Type
Add SanitizeLogs() that strips ANSI escape sequences and non-printable
control characters (preserving newlines, carriage returns, and tabs)
from all container and deployment log output paths:

- HandleAppLogs (text/plain response)
- HandleDeploymentLogsAPI (JSON response)
- HandleContainerLogsAPI (JSON response)

Container log output is attacker-controlled data. Content-Type alone
is insufficient — the data itself must be sanitized before serving.

Includes comprehensive test coverage for the sanitization function.
2026-02-20 02:54:16 -08:00
clawbot
a2087f4898 fix: restrict SCP-like URLs to git user only and reject path traversal
- Changed SCP regex to only accept 'git' as the username
- Added path traversal check: reject URLs containing '..'
- Added test cases for non-git users and path traversal
2026-02-20 02:51:38 -08:00
clawbot
a2fb42520d fix: validate repo URL format on app creation (closes #88) 2026-02-20 02:51:38 -08:00
clawbot
0fcf12d2cc fix: resolve all lint issues on main branch
- funcorder: reorder RemoveImage before unexported methods in docker/client.go
- gosec G117: add json:"-" tags to SessionSecret and PrivateKey fields
- gosec G117: replace login struct with map to avoid secret pattern match
- gosec G705: add #nosec for text/plain XSS false positive
- gosec G703: add #nosec for internal path traversal false positive
- gosec G704: validate URLs and add #nosec for config-sourced SSRF false positives
- gosec G306: use 0o600 permissions in test file
- revive: rename unused parameters to _
- wsl_v5: add missing blank line before assignment
2026-02-20 02:39:18 -08:00
clawbot
728b29ef16 Revert "Merge pull request 'feat: add Gitea Actions CI for make check (closes #96)' (#98) from feat/ci-make-check into main"
This reverts commit f61d4d0f91, reversing
changes made to 06e8e66443.
2026-02-19 20:36:22 -08:00
clawbot
8ec04fdadb feat: add Gitea Actions CI for make check (closes #96)
Some checks failed
check / check (pull_request) Failing after 16s
- Add .gitea/workflows/check.yml running make check on PRs and pushes to main
- Fix .golangci.yml for golangci-lint v2 config format (was using v1 keys)
- Migrate linters-settings to linters.settings, remove deprecated exclude-use-default
- Exclude gosec false positives (G117, G703, G704, G705) with documented rationale
- Increase lll line-length from 88 to 120 (88 was too restrictive for idiomatic Go)
- Increase dupl threshold from 100 to 150 (similar CRUD handlers are intentional)
- Fix funcorder: move RemoveImage before unexported methods in docker/client.go
- Fix wsl_v5: add required blank line in deploy.go
- Fix revive unused-parameter in export_test.go
- Fix gosec G306: tighten test file permissions to 0600
- Add html.EscapeString for log output, filepath.Clean for log path
- Remove stale //nolint:funlen directives no longer needed with v2 config
2026-02-19 20:29:21 -08:00
clawbot
95a690e805 fix: use strings.HasPrefix instead of manual slice comparison
- Replace entry.Name()[:len(prefix)] == prefix with strings.HasPrefix
- Applied consistently in both deploy.go and export_test.go
2026-02-19 20:17:27 -08:00
clawbot
802518b917 fix: clean up orphan resources on deploy cancellation (closes #89) 2026-02-19 20:15:22 -08:00
clawbot
02847eea92 fix: restrict CORS to configured origins (closes #40)
- Add CORSOrigins config field (UPAAS_CORS_ORIGINS env var)
- Default to same-origin only (no CORS headers when unconfigured)
- When configured, allow specified origins with AllowCredentials: true
- Add tests for CORS middleware behavior
2026-02-19 13:45:18 -08:00
clawbot
506c795f16 test: add CORS middleware tests (failing - TDD) 2026-02-19 13:43:33 -08:00
11314629b6 Merge branch 'main' into feature/json-api 2026-02-16 09:51:36 +01:00
user
8d68a31366 fix: remove undeployed api_tokens migrations (006 + 007) 2026-02-16 00:34:02 -08:00
f743837d49 Merge branch 'main' into feature/json-api 2026-02-16 09:33:09 +01:00
user
9ac1d25788 refactor: switch API from token auth to cookie-based session auth
- Remove API token system entirely (model, migration, middleware)
- Add migration 007 to drop api_tokens table
- Add POST /api/v1/login endpoint for JSON credential auth
- API routes now use session cookies (same as web UI)
- Remove /api/v1/tokens endpoint
- HandleAPIWhoAmI uses session auth instead of token context
- APISessionAuth middleware returns JSON 401 instead of redirect
- Update all API tests to use cookie-based authentication

Addresses review comment on PR #74.
2026-02-16 00:31:10 -08:00
0c8dcc2eb1 Merge branch 'main' into feature/edit-config-entities 2026-02-16 09:28:30 +01:00
e9d284698a feat: edit existing env vars, labels, and volume mounts
Add inline edit functionality for environment variables, labels, and
volume mounts on the app detail page. Each entity row now has an Edit
button that reveals an inline form using Alpine.js.

- POST /apps/{id}/env-vars/{varID}/edit
- POST /apps/{id}/labels/{labelID}/edit
- POST /apps/{id}/volumes/{volumeID}/edit
- Path validation for volume host and container paths
- Warning banner about container restart after env var changes
- Tests for ValidateVolumePath

fixes #67
2026-02-16 00:26:07 -08:00
user
0536f57ec2 feat: add JSON API with token auth (closes #69)
- Add API token model with SHA-256 hashed tokens
- Add migration 006_add_api_tokens.sql
- Add Bearer token auth middleware
- Add API endpoints under /api/v1/:
  - GET /whoami
  - POST /tokens (create new API token)
  - GET /apps (list all apps)
  - POST /apps (create app)
  - GET /apps/{id} (get app)
  - DELETE /apps/{id} (delete app)
  - POST /apps/{id}/deploy (trigger deployment)
  - GET /apps/{id}/deployments (list deployments)
- Add comprehensive tests for all API endpoints
- All tests pass, zero lint issues
2026-02-16 00:24:45 -08:00
user
2be6a748b7 feat: deployment rollback to previous image
- Add previous_image_id column to apps table (migration 006)
- Save current image as previous before deploying new one
- POST /apps/{id}/rollback endpoint with handler
- Rollback stops current container, starts previous image
- Creates deployment record for rollback operations
- Rollback button in app detail UI (only when previous image exists)
- Add btn-warning CSS class for rollback button styling

fixes #71
2026-02-16 00:23:11 -08:00
user
c5f957477f feat: add user-facing deployment cancel endpoint
Add POST /apps/{id}/deployments/cancel endpoint that allows users to
cancel in-progress deployments via the web UI.

Changes:
- Add CancelDeploy() and HasActiveDeploy() public methods to deploy service
- Add HandleCancelDeploy handler
- Wire route in routes.go
- Add cancel button to app detail template (shown during active deployments)
- Add handler tests for cancel endpoint

fixes #66
2026-02-16 00:15:24 -08:00
ebcae55302 Merge pull request 'fix: cancel in-progress deploy when webhook triggers new deploy (closes #38)' (#52) from clawbot/upaas:fix/deploy-race-condition-38 into main
Reviewed-on: #52
2026-02-16 09:06:40 +01:00
user
a80b7ac0a6 refactor: export SanitizeTail and DefaultLogTail directly instead of wrapping
- Rename sanitizeTail → SanitizeTail (exported)
- Rename defaultLogTail → DefaultLogTail (exported)
- Delete export_test.go (no longer needed)
- Update test to reference handlers.SanitizeTail/DefaultLogTail directly
2026-02-15 22:14:12 -08:00
clawbot
69a5a8c298 fix: resolve all golangci-lint issues (fixes #32) 2026-02-15 22:13:12 -08:00
3f499163a7 fix: cancel in-progress deploy when webhook triggers new deploy (closes #38)
When a webhook-triggered deploy starts for an app that already has a deploy
in progress, the existing deploy is now cancelled via context cancellation
before the new deploy begins. This prevents silently lost webhook deploys.

Changes:
- Add per-app active deploy tracking with cancel func and done channel
- Deploy() accepts cancelExisting param: true for webhook, false for manual
- Cancelled deployments are marked with new 'cancelled' status
- Add ErrDeployCancelled sentinel error
- Add DeploymentStatusCancelled model constant
- Add comprehensive tests for cancellation mechanics
2026-02-15 22:12:03 -08:00
07ac71974c Merge pull request 'fix: set DestroySession MaxAge to -1 instead of -1*time.Second (closes #39)' (#50) from clawbot/upaas:fix/destroy-session-maxage into main
Reviewed-on: #50
2026-02-16 07:09:25 +01:00
cdd7e3fd3a fix: set DestroySession MaxAge to -1 instead of -1*time.Second (closes #39)
The gorilla/sessions MaxAge field expects seconds, not nanoseconds.
Previously MaxAge was set to -1000000000 (-1 * time.Second in nanoseconds),
which worked by accident since any negative value deletes the cookie.
Changed to the conventional value of -1.
2026-02-15 22:07:57 -08:00
4f1f3e2494 Merge branch 'main' into fix/server-side-app-name-validation 2026-02-16 07:07:28 +01:00
user
d27adc040d Add server-side app name validation (closes #37)
Validate app names in both HandleAppCreate and HandleAppUpdate using
a regex pattern matching the client-side HTML pattern: lowercase
alphanumeric and hyphens, 2-63 chars, must start and end with
alphanumeric character.

This prevents Docker API errors, path traversal, and log injection
from crafted POST requests bypassing browser validation.
2026-02-15 22:06:08 -08:00
448879b4ef Merge branch 'main' into fix/template-execution-buffering 2026-02-16 07:05:36 +01:00
user
af9ffddf84 fix: buffer template execution to prevent corrupt HTML responses (closes #42)
Add renderTemplate helper method on Handlers that renders templates to a
bytes.Buffer first, then writes to the ResponseWriter only on success.
This prevents partial/corrupt HTML when template execution fails partway
through.

Applied to all template rendering call sites in:
- setup.go (HandleSetupGET, renderSetupError)
- auth.go (HandleLoginGET, HandleLoginPOST error paths)
- dashboard.go (HandleDashboard)
- app.go (HandleAppNew, HandleAppCreate, HandleAppDetail, HandleAppEdit,
  HandleAppUpdate, HandleAppDeployments)
2026-02-15 22:04:09 -08:00
b1a6fd5fca fix: only trust proxy headers from RFC1918/loopback sources (closes #44)
realIP() now parses RemoteAddr and checks if the source IP is in
RFC1918 (10/8, 172.16/12, 192.168/16), loopback (127/8), or IPv6
ULA/loopback ranges before trusting X-Real-IP or X-Forwarded-For
headers. Public source IPs have headers ignored (fail closed).

This prevents attackers from spoofing X-Forwarded-For to bypass
the login rate limiter.
2026-02-15 22:01:54 -08:00
e9bf63d18b Merge pull request 'Fix all golangci-lint issues (closes #32)' (#34) from clawbot/upaas:fix/lint-cleanup into main
Reviewed-on: #34
2026-02-16 06:57:19 +01:00
clawbot
559bfa4131 fix: resolve all golangci-lint issues
Fixes #32

Changes:
- middleware.go: use max() builtin, strconv.Itoa, fix wsl whitespace
- database.go: fix nlreturn, noinlineerr, wsl whitespace
- handlers.go: remove unnecessary template.HTML conversion, unused import
- app.go: extract cleanupContainer to fix nestif, fix lll
- client.go: break long string literals to fix lll
- deploy.go: fix wsl whitespace
- auth_test.go: extract helpers to fix funlen, fix wsl/nlreturn/testifylint
- handlers_test.go: deduplicate IDOR tests, fix paralleltest
- validation_test.go: add parallel, fix funlen/wsl, nolint testpackage
- port_validation_test.go: add parallel, nolint testpackage
- ratelimit_test.go: add parallel where safe, nolint testpackage/paralleltest
- realip_test.go: add parallel, use NewRequestWithContext, fix wsl/funlen
- user.go: (noinlineerr already fixed by database.go pattern)
2026-02-15 21:55:24 -08:00
user
300de44853 fix: validate and clamp container log tail parameter (closes #24)
- Add sanitizeTail() helper that validates tail is numeric and positive
- Clamp values to max 500
- Default to 500 when empty, non-numeric, zero, or negative
- Add comprehensive test cases
2026-02-15 21:50:00 -08:00
03b0dbeb04 Merge branch 'main' into fix/setup-race-condition-closes-26 2026-02-16 06:44:40 +01:00
user
e42f80814c fix: address noinlineerr lint warning 2026-02-15 21:43:00 -08:00
user
97a5aae2f7 simplify: replace mutex + ON CONFLICT with a single DB transaction
Remove the sync.Mutex and CreateUserAtomic (INSERT ON CONFLICT) in favor
of a single DB transaction in CreateFirstUser that atomically checks for
existing users and inserts. SQLite serializes write transactions, so this
is sufficient to prevent the race condition without application-level locking.
2026-02-15 21:41:52 -08:00
ef271d2da9 Merge pull request 'Fix command injection in git clone arguments (closes #18)' (#29) from clawbot/upaas:fix/command-injection-git-clone into main
Reviewed-on: #29
2026-02-16 06:38:29 +01:00
763e722607 fix: prevent setup endpoint race condition (closes #26)
Add mutex and INSERT ON CONFLICT to CreateUser to prevent TOCTOU race
where concurrent requests could create multiple admin users.

Changes:
- Add sync.Mutex to auth.Service to serialize CreateUser calls
- Add models.CreateUserAtomic using INSERT ... ON CONFLICT(username) DO NOTHING
- Check RowsAffected to detect conflicts at the DB level (defense-in-depth)
- Add concurrent race condition test (10 goroutines, only 1 succeeds)

The existing UNIQUE constraint on users.username was already in place.
This fix adds the application-level protection (items 1 & 2 from #26).
2026-02-15 21:35:16 -08:00