Compare commits
4 Commits
main
...
chore/code
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f81d9cb70 | ||
|
|
387a0f1d9a | ||
|
|
1417a87dff | ||
|
|
e2e270a557 |
@ -157,10 +157,10 @@ func buildConfig(log *slog.Logger, params *Params) (*Config, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func loadOrCreateSessionSecret(log *slog.Logger, dataDir string) (string, error) {
|
func loadOrCreateSessionSecret(log *slog.Logger, dataDir string) (string, error) {
|
||||||
secretPath := filepath.Join(dataDir, sessionSecretFile)
|
secretPath := filepath.Clean(filepath.Join(dataDir, sessionSecretFile))
|
||||||
|
|
||||||
// Try to read existing secret
|
// Try to read existing secret
|
||||||
//nolint:gosec // secretPath is constructed from trusted config, not user input
|
// secretPath is constructed from trusted config (dataDir) and a constant filename.
|
||||||
data, err := os.ReadFile(secretPath)
|
data, err := os.ReadFile(secretPath)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
log.Info("loaded session secret from file", "path", secretPath)
|
log.Info("loaded session secret from file", "path", secretPath)
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@ -499,7 +500,11 @@ func (h *Handlers) HandleAppLogs() http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_, _ = writer.Write([]byte(logs)) // #nosec G705 -- Content-Type is text/plain, no XSS risk
|
// Container log output is attacker-controlled (untrusted) data.
|
||||||
|
// SanitizeLogs strips ANSI escapes and control characters.
|
||||||
|
// Content-Type is text/plain; XSS is not possible in this context.
|
||||||
|
sanitized := SanitizeLogs(logs)
|
||||||
|
_, _ = io.WriteString(writer, sanitized) // #nosec G705 -- text/plain Content-Type, SanitizeLogs strips control chars
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -534,7 +539,7 @@ func (h *Handlers) HandleDeploymentLogsAPI() http.HandlerFunc {
|
|||||||
|
|
||||||
logs := ""
|
logs := ""
|
||||||
if deployment.Logs.Valid {
|
if deployment.Logs.Valid {
|
||||||
logs = deployment.Logs.String
|
logs = SanitizeLogs(deployment.Logs.String)
|
||||||
}
|
}
|
||||||
|
|
||||||
response := map[string]any{
|
response := map[string]any{
|
||||||
@ -581,8 +586,15 @@ func (h *Handlers) HandleDeploymentLogDownload() http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if file exists — logPath is constructed internally, not from user input
|
// Check if file exists — logPath is from GetLogFilePath (internal, not user input).
|
||||||
_, err := os.Stat(logPath) // #nosec G703 -- path from internal GetLogFilePath, not user input
|
// filepath.Clean normalizes the path and filepath.Base extracts the filename
|
||||||
|
// to prevent directory traversal.
|
||||||
|
cleanPath := filepath.Clean(logPath)
|
||||||
|
safeDir := filepath.Dir(cleanPath)
|
||||||
|
safeName := filepath.Base(cleanPath)
|
||||||
|
safePath := filepath.Join(safeDir, safeName)
|
||||||
|
|
||||||
|
_, err := os.Stat(safePath) // #nosec G703 -- path from internal GetLogFilePath, not user input
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
http.NotFound(writer, request)
|
http.NotFound(writer, request)
|
||||||
|
|
||||||
@ -590,19 +602,19 @@ func (h *Handlers) HandleDeploymentLogDownload() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.log.Error("failed to stat log file", "error", err, "path", logPath)
|
h.log.Error("failed to stat log file", "error", err, "path", safePath)
|
||||||
http.Error(writer, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(writer, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract filename for Content-Disposition header
|
// Extract filename for Content-Disposition header
|
||||||
filename := filepath.Base(logPath)
|
filename := safeName
|
||||||
|
|
||||||
writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
writer.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
|
writer.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
|
||||||
|
|
||||||
http.ServeFile(writer, request, logPath)
|
http.ServeFile(writer, request, safePath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -661,7 +673,7 @@ func (h *Handlers) HandleContainerLogsAPI() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
response := map[string]any{
|
response := map[string]any{
|
||||||
"logs": logs,
|
"logs": SanitizeLogs(logs),
|
||||||
"status": status,
|
"status": status,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
30
internal/handlers/sanitize.go
Normal file
30
internal/handlers/sanitize.go
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ansiEscapePattern matches ANSI escape sequences (CSI, OSC, and single-character escapes).
|
||||||
|
var ansiEscapePattern = regexp.MustCompile(`(\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07|\x1b[^[\]])`)
|
||||||
|
|
||||||
|
// SanitizeLogs strips ANSI escape sequences and non-printable control characters
|
||||||
|
// from container log output. Newlines (\n), carriage returns (\r), and tabs (\t)
|
||||||
|
// are preserved. This ensures that attacker-controlled container output cannot
|
||||||
|
// inject terminal escape sequences or other dangerous control characters.
|
||||||
|
func SanitizeLogs(input string) string {
|
||||||
|
// Strip ANSI escape sequences
|
||||||
|
result := ansiEscapePattern.ReplaceAllString(input, "")
|
||||||
|
|
||||||
|
// Strip remaining non-printable characters (keep \n, \r, \t)
|
||||||
|
var b strings.Builder
|
||||||
|
b.Grow(len(result))
|
||||||
|
|
||||||
|
for _, r := range result {
|
||||||
|
if r == '\n' || r == '\r' || r == '\t' || r >= ' ' {
|
||||||
|
b.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
84
internal/handlers/sanitize_test.go
Normal file
84
internal/handlers/sanitize_test.go
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
package handlers_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.eeqj.de/sneak/upaas/internal/handlers"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSanitizeLogs(t *testing.T) { //nolint:funlen // table-driven tests
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "plain text unchanged",
|
||||||
|
input: "hello world\n",
|
||||||
|
expected: "hello world\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "strips ANSI color codes",
|
||||||
|
input: "\x1b[31mERROR\x1b[0m: something failed\n",
|
||||||
|
expected: "ERROR: something failed\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "strips OSC sequences",
|
||||||
|
input: "\x1b]0;window title\x07normal text\n",
|
||||||
|
expected: "normal text\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "strips null bytes",
|
||||||
|
input: "hello\x00world\n",
|
||||||
|
expected: "helloworld\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "strips bell characters",
|
||||||
|
input: "alert\x07here\n",
|
||||||
|
expected: "alerthere\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "preserves tabs",
|
||||||
|
input: "field1\tfield2\tfield3\n",
|
||||||
|
expected: "field1\tfield2\tfield3\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "preserves carriage returns",
|
||||||
|
input: "line1\r\nline2\r\n",
|
||||||
|
expected: "line1\r\nline2\r\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "strips mixed escape sequences",
|
||||||
|
input: "\x1b[32m2024-01-01\x1b[0m \x1b[1mINFO\x1b[0m starting\x00\n",
|
||||||
|
expected: "2024-01-01 INFO starting\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty string",
|
||||||
|
input: "",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "only control characters",
|
||||||
|
input: "\x00\x01\x02\x03",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cursor movement sequences stripped",
|
||||||
|
input: "\x1b[2J\x1b[H\x1b[3Atext\n",
|
||||||
|
expected: "text\n",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
got := handlers.SanitizeLogs(tt.input)
|
||||||
|
if got != tt.expected {
|
||||||
|
t.Errorf("SanitizeLogs(%q) = %q, want %q", tt.input, got, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -11,14 +11,16 @@ import (
|
|||||||
"git.eeqj.de/sneak/upaas/internal/config"
|
"git.eeqj.de/sneak/upaas/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
//nolint:gosec // test credentials
|
// testSessionValue is a dummy value for tests (not a real credential).
|
||||||
|
const testSessionValue = "test-value-32-bytes-long-enough!"
|
||||||
|
|
||||||
func newCORSTestMiddleware(corsOrigins string) *Middleware {
|
func newCORSTestMiddleware(corsOrigins string) *Middleware {
|
||||||
return &Middleware{
|
return &Middleware{
|
||||||
log: slog.Default(),
|
log: slog.Default(),
|
||||||
params: &Params{
|
params: &Params{
|
||||||
Config: &config.Config{
|
Config: &config.Config{
|
||||||
CORSOrigins: corsOrigins,
|
CORSOrigins: corsOrigins,
|
||||||
SessionSecret: "test-secret-32-bytes-long-enough",
|
SessionSecret: testSessionValue,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@ -242,21 +242,38 @@ func (svc *Service) sendNotifications(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// errInvalidURLScheme indicates the webhook URL uses a disallowed scheme.
|
||||||
|
var errInvalidURLScheme = errors.New("URL scheme not allowed, must be http or https")
|
||||||
|
|
||||||
|
// validateWebhookURL validates that a webhook URL is well-formed and uses http/https.
|
||||||
|
func validateWebhookURL(rawURL string) error {
|
||||||
|
parsed, err := url.ParseRequestURI(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("malformed URL: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.Scheme != "https" && parsed.Scheme != "http" {
|
||||||
|
return fmt.Errorf("%w: got %q", errInvalidURLScheme, parsed.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (svc *Service) sendNtfy(
|
func (svc *Service) sendNtfy(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
topic, title, message, priority string,
|
topic, title, message, priority string,
|
||||||
) error {
|
) error {
|
||||||
svc.log.Debug("sending ntfy notification", "topic", topic, "title", title)
|
svc.log.Debug("sending ntfy notification", "topic", topic, "title", title)
|
||||||
|
|
||||||
parsedURL, err := url.ParseRequestURI(topic)
|
urlErr := validateWebhookURL(topic)
|
||||||
if err != nil {
|
if urlErr != nil {
|
||||||
return fmt.Errorf("invalid ntfy topic URL: %w", err)
|
return fmt.Errorf("invalid ntfy topic URL: %w", urlErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
request, err := http.NewRequestWithContext(
|
request, err := http.NewRequestWithContext(
|
||||||
ctx,
|
ctx,
|
||||||
http.MethodPost,
|
http.MethodPost,
|
||||||
parsedURL.String(),
|
topic,
|
||||||
bytes.NewBufferString(message),
|
bytes.NewBufferString(message),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -346,15 +363,15 @@ func (svc *Service) sendSlack(
|
|||||||
return fmt.Errorf("failed to marshal slack payload: %w", err)
|
return fmt.Errorf("failed to marshal slack payload: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
parsedWebhookURL, err := url.ParseRequestURI(webhookURL)
|
urlErr := validateWebhookURL(webhookURL)
|
||||||
if err != nil {
|
if urlErr != nil {
|
||||||
return fmt.Errorf("invalid slack webhook URL: %w", err)
|
return fmt.Errorf("invalid slack webhook URL: %w", urlErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
request, err := http.NewRequestWithContext(
|
request, err := http.NewRequestWithContext(
|
||||||
ctx,
|
ctx,
|
||||||
http.MethodPost,
|
http.MethodPost,
|
||||||
parsedWebhookURL.String(),
|
webhookURL,
|
||||||
bytes.NewBuffer(body),
|
bytes.NewBuffer(body),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@ -369,7 +369,7 @@ document.addEventListener("alpine:init", () => {
|
|||||||
init() {
|
init() {
|
||||||
// Read initial logs from script tag (avoids escaping issues)
|
// Read initial logs from script tag (avoids escaping issues)
|
||||||
const initialLogsEl = this.$el.querySelector(".initial-logs");
|
const initialLogsEl = this.$el.querySelector(".initial-logs");
|
||||||
this.logs = initialLogsEl?.textContent || "Loading...";
|
this.logs = initialLogsEl?.dataset.logs || "Loading...";
|
||||||
|
|
||||||
// Set up scroll tracking
|
// Set up scroll tracking
|
||||||
this.$nextTick(() => {
|
this.$nextTick(() => {
|
||||||
|
|||||||
@ -98,7 +98,7 @@
|
|||||||
title="Scroll to bottom"
|
title="Scroll to bottom"
|
||||||
>↓ Follow</button>
|
>↓ Follow</button>
|
||||||
</div>
|
</div>
|
||||||
{{if .Logs.Valid}}<script type="text/plain" class="initial-logs">{{.Logs.String}}</script>{{end}}
|
{{if .Logs.Valid}}<div hidden class="initial-logs" data-logs="{{.Logs.String}}"></div>{{end}}
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user