Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Harden protected response media and security test fixtures

rcourtmanb8f9c51119d1
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8fc704802d..1f19cde52f 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2030,6 +2030,11 @@ token-free command. No copy receipt establishes installed removal or a release.
## Shared Boundaries
+Protected progress and synchronous reads use the API-owned non-executable media
+policy. Configuration-import replay admission retains guard-keyed request
+fingerprints without retaining archives or passphrases. These transport guards
+do not cancel independent agent work or establish durable recovery idempotency.
+
The shared OIDC Test diagnostic exposes only a numeric upstream HTTP status
and fixed recovery guidance on failed discovery, never a provider/proxy reason
phrase, header or body. It makes no agent credential, enrollment, lifecycle or
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index fa534ceace..7dde0dabc9 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -110,7 +110,8 @@ routes admits only `application/json` or `text/plain; charset=utf-8`, with
media parameters are normalized to the JSON type. Missing, malformed or other
handler types fall back to plain text; none may turn a result into HTML, SVG or
JavaScript. Alternate-case media headers are discarded before the canonical
-headers are set. Payload bytes, status and other admitted headers are preserved:
+headers are set directly at each transport commit or body-write boundary.
+Payload bytes, status and other admitted headers are preserved:
JSON is not HTML-escaped twice, parsed or buffered by this boundary.
This does not change admission, withdrawal checks, request cancellation or the
@@ -141,6 +142,13 @@ scope or organisation/instance authority suppress subsequent output. No HTTP
error or invented terminal success is appended to an admitted SSE response.
A frame admitted before concurrent withdrawal can already be in flight.
+The shared guarded stream writer pins `text/event-stream; charset=utf-8` for
+SSE or `application/json` for structured errors. Missing, malformed or other
+media types fall back to plain text with `nosniff`; alternate-case media
+headers cannot escape the boundary. Explicit status, implicit body writes and
+flush-only commits use the same closed media policy, with original payload
+bytes preserved. Informational headers do not commit the final response.
+
The guard exposes deadline setters, not an unguarded response-writer escape:
Assistant handlers still clear the initial server deadlines and bound each
write. The outer API error/status wrapper forwards these same two controls
@@ -444,8 +452,11 @@ nor a reload is repeated, and a cached success cannot imply that a newer edit
was restored. Different archives can be imported after the active import ends;
uncommitted failures can retry after their cause is corrected.
-Admission stores only scoped full-request digests and completion times, never
-archives, passphrases or response bodies. Empty/default scope aliases share
+Admission stores only scoped HMAC-SHA-256 request fingerprints and completion
+times, never archives, passphrases or response bodies. Each guard uses its own
+cryptographically random, process-local key, so retained fingerprints cannot be
+used as unkeyed passphrase verifiers. Length-prefixed input preserves archive
+and passphrase field boundaries. Empty/default scope aliases share
one admission; different tenants do not. The process-local registry holds at
most 128 active/recent attempts and fails closed with HTTP 503 rather than
evict an unexpired attempt. Active imports never expire; completed entries
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 3141e644e3..43beb89789 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -3393,6 +3393,7 @@
"internal/api/availability_handlers_test.go",
"internal/api/chartapi/history_activity_test.go",
"internal/api/configapi/config_handlers_connection_test.go",
+ "internal/api/configapi/config_import_admission_test.go",
"internal/api/contract_test.go",
"internal/api/docker_agents_report_size_test.go",
"internal/api/docker_container_action_executor_test.go",
@@ -3405,6 +3406,8 @@
"internal/api/patrol_autopilot_test.go",
"internal/api/runtime_inventory_sources_test.go",
"internal/api/telemetry_history_reads_test.go",
+ "internal/api/token_response_media_test.go",
+ "internal/api/token_stream_lifetime_test.go",
"internal/api/truenas_disk_history_integration_test.go",
"pulse-enterprise:test/extensions_contract_test.go"
]
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c6c5c5a5ad..e3fa206107 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -2292,6 +2292,11 @@ Compact Coverage age cells use the existing metadata-size text and reclaim numer
## Shared Boundaries
+Protected progress and synchronous reads use the API-owned non-executable media
+policy. Configuration-import replay admission retains guard-keyed request
+fingerprints without retaining archives or passphrases. These transport guards
+do not cancel independent agent work or establish durable recovery idempotency.
+
The shared OIDC Test diagnostic's failed-discovery response carries only a
numeric HTTP status and fixed guidance, not provider/proxy reason phrases,
headers or bodies. Testing does not save settings or replace credentials and
diff --git a/internal/api/configapi/config_import_admission_test.go b/internal/api/configapi/config_import_admission_test.go
index 684f552d8b..b49c565891 100644
--- a/internal/api/configapi/config_import_admission_test.go
+++ b/internal/api/configapi/config_import_admission_test.go
@@ -107,3 +107,40 @@ func TestConfigImportAdmissionConcurrentRequestsHaveOneOwner(t *testing.T) {
t.Fatalf("concurrent owners = %d, want one", admitted.Load())
}
}
+
+func TestConfigImportAdmissionFingerprintsAreGuardScoped(t *testing.T) {
+ now := time.Now()
+ req := ImportConfigRequest{Data: "synthetic-ciphertext", Passphrase: "synthetic-passphrase"}
+ var firstGuard, secondGuard configImportRequests
+ first, rejection := firstGuard.begin("default", req, now)
+ if rejection != nil {
+ t.Fatal(rejection)
+ }
+ second, rejection := secondGuard.begin("default", req, now)
+ if rejection != nil {
+ t.Fatal(rejection)
+ }
+ if first.key.fingerprint == second.key.fingerprint {
+ t.Fatal("independent guards retained the same request fingerprint")
+ }
+ firstGuard.finish(first, true, now)
+ if _, rejection := firstGuard.begin("default", req, now); rejection == nil || rejection.status != http.StatusConflict {
+ t.Fatal("keyed fingerprint did not recognise a completed request")
+ }
+}
+
+func TestConfigImportAdmissionFingerprintsPreserveFieldBoundaries(t *testing.T) {
+ now := time.Now()
+ var guard configImportRequests
+ // The concatenated bytes are equal, but archive and passphrase differ.
+ for _, req := range []ImportConfigRequest{
+ {Data: "synthetic-a", Passphrase: "bc"},
+ {Data: "synthetic-ab", Passphrase: "c"},
+ } {
+ attempt, rejection := guard.begin("default", req, now)
+ if rejection != nil {
+ t.Fatal("distinct fields reused a completed request fingerprint", rejection)
+ }
+ guard.finish(attempt, true, now)
+ }
+}
diff --git a/internal/api/configapi/config_import_replay.go b/internal/api/configapi/config_import_replay.go
index 3c46abab0c..b83a6d8a78 100644
--- a/internal/api/configapi/config_import_replay.go
+++ b/internal/api/configapi/config_import_replay.go
@@ -1,6 +1,8 @@
package configapi
import (
+ "crypto/hmac"
+ "crypto/rand"
"crypto/sha256"
"encoding/binary"
"io"
@@ -34,8 +36,10 @@ type configImportRejection struct {
// bounded: one in-flight import per org and at most 128 attempts for ten minutes
// after completion. Never evict an unexpired attempt to admit a new one.
type configImportRequests struct {
- mu sync.Mutex
- attempts map[configImportKey]*configImportAttempt
+ mu sync.Mutex
+ attempts map[configImportKey]*configImportAttempt
+ keyOnce sync.Once
+ fingerprintKey [sha256.Size]byte
}
func (g *configImportRequests) begin(orgID string, req ImportConfigRequest, now time.Time) (*configImportAttempt, *configImportRejection) {
@@ -44,8 +48,13 @@ func (g *configImportRequests) begin(orgID string, req ImportConfigRequest, now
}
// Length-prefix the data, including malformed input. Include the
// passphrase so a different password cannot reuse an earlier admission.
- // Only this full-request digest survives the request, never either input.
- hash := sha256.New()
+ // Key the fingerprint with a guard-local random secret so retained entries
+ // are not unkeyed passphrase hashes. Neither input is retained.
+ g.keyOnce.Do(func() {
+ // crypto/rand.Read terminates the process if secure randomness fails.
+ _, _ = rand.Read(g.fingerprintKey[:])
+ })
+ hash := hmac.New(sha256.New, g.fingerprintKey[:])
var length [8]byte
binary.BigEndian.PutUint64(length[:], uint64(len(req.Data)))
_, _ = hash.Write(length[:])
diff --git a/internal/api/token_response_authority.go b/internal/api/token_response_authority.go
index 3c9a255767..b14f51b754 100644
--- a/internal/api/token_response_authority.go
+++ b/internal/api/token_response_authority.go
@@ -27,6 +27,7 @@ const (
responseMediaZIP
responseMediaReport
responseMediaAudit
+ responseMediaEventStream
)
// retainResponseAuthority serves slow synchronous results and private downloads.
@@ -92,65 +93,77 @@ func (w *tokenResponseWriter) permitLocked() bool {
return true
}
-func (w *tokenResponseWriter) commitLocked(status int) {
- if !w.started {
- header := w.writer.Header()
- clear(header)
- for key, values := range w.header {
- if strings.EqualFold(key, "Content-Type") || strings.EqualFold(key, "X-Content-Type-Options") {
- continue
- }
- header[key] = append([]string(nil), values...)
+func (w *tokenResponseWriter) prepareHeaderLocked() string {
+ header := w.writer.Header()
+ clear(header)
+ for key, values := range w.header {
+ if strings.EqualFold(key, "Content-Type") || strings.EqualFold(key, "X-Content-Type-Options") {
+ continue
}
- // Results serve only their pinned media type or plain-text errors, never HTML.
- // Bind non-executable media to the actual transport, not just the
- // handler's private header map. Missing, malformed or unexpected
- // types must not allow HTTP sniffing or an extension to render HTML.
- // Leave payload bytes alone: HTML-escaping JSON would corrupt data.
- mediaType, _, err := mime.ParseMediaType(w.header.Get("Content-Type"))
- pinnedType := "text/plain; charset=utf-8"
- if err == nil {
- switch w.media {
- case responseMediaJSON:
- if mediaType == "application/json" {
- pinnedType = mediaType
- }
- case responseMediaZIP:
- if mediaType == "application/zip" {
- pinnedType = mediaType
- }
- case responseMediaAudit:
- // Audit exports are structured evidence, never report PDFs.
- switch mediaType {
- case "application/json":
- pinnedType = mediaType
- case "text/csv":
- pinnedType = "text/csv; charset=utf-8"
- }
- case responseMediaReport:
- // Existing PDF/CSV attachments and structured API errors.
- // CSV is UTF-8; never forward renderer-supplied parameters.
- switch mediaType {
- case "application/pdf", "application/json":
- pinnedType = mediaType
- case "text/csv":
- pinnedType = "text/csv; charset=utf-8"
- }
+ header[key] = append([]string(nil), values...)
+ }
+ // Results serve only their pinned media type or plain-text errors, never HTML.
+ // Bind non-executable media to the actual transport, not just the
+ // handler's private header map. Missing, malformed or unexpected
+ // types must not allow HTTP sniffing or an extension to render HTML.
+ // Leave payload bytes alone: HTML-escaping JSON would corrupt data.
+ return responseContentType(w.header, w.media)
+}
+
+// responseContentType returns only fixed, non-executable transport types.
+// Keep the selection shared by synchronous results and streaming reads.
+func responseContentType(header http.Header, media responseMediaPolicy) string {
+ mediaType, _, err := mime.ParseMediaType(header.Get("Content-Type"))
+ pinnedType := "text/plain; charset=utf-8"
+ if err == nil {
+ switch media {
+ case responseMediaEventStream:
+ switch mediaType {
+ case "text/event-stream":
+ pinnedType = "text/event-stream; charset=utf-8"
+ case "application/json":
+ pinnedType = mediaType
+ }
+ case responseMediaJSON:
+ if mediaType == "application/json" {
+ pinnedType = mediaType
+ }
+ case responseMediaZIP:
+ if mediaType == "application/zip" {
+ pinnedType = mediaType
+ }
+ case responseMediaAudit:
+ // Audit exports are structured evidence, never report PDFs.
+ switch mediaType {
+ case "application/json":
+ pinnedType = mediaType
+ case "text/csv":
+ pinnedType = "text/csv; charset=utf-8"
+ }
+ case responseMediaReport:
+ // Existing PDF/CSV attachments and structured API errors.
+ // CSV is UTF-8; never forward renderer-supplied parameters.
+ switch mediaType {
+ case "application/pdf", "application/json":
+ pinnedType = mediaType
+ case "text/csv":
+ pinnedType = "text/csv; charset=utf-8"
}
}
- header.Set("Content-Type", pinnedType)
- header.Set("X-Content-Type-Options", "nosniff")
- w.writer.WriteHeader(status)
- // Informational headers do not commit the final response.
- w.started = status >= 200 || status == http.StatusSwitchingProtocols
}
+ return pinnedType
}
func (w *tokenResponseWriter) WriteHeader(status int) {
w.mu.Lock()
defer w.mu.Unlock()
- if w.permitLocked() {
- w.commitLocked(status)
+ if w.permitLocked() && !w.started {
+ contentType := w.prepareHeaderLocked()
+ w.writer.Header().Set("Content-Type", contentType)
+ w.writer.Header().Set("X-Content-Type-Options", "nosniff")
+ w.writer.WriteHeader(status)
+ // Informational headers do not commit the final response.
+ w.started = status >= 200 || status == http.StatusSwitchingProtocols
}
}
@@ -160,7 +173,12 @@ func (w *tokenResponseWriter) Write(p []byte) (int, error) {
if !w.permitLocked() {
return 0, io.ErrClosedPipe
}
- w.commitLocked(http.StatusOK)
+ if !w.started {
+ contentType := w.prepareHeaderLocked()
+ w.writer.Header().Set("Content-Type", contentType)
+ w.writer.Header().Set("X-Content-Type-Options", "nosniff")
+ w.started = true
+ }
n, err := w.writer.Write(p)
if err != nil {
w.closed = true
diff --git a/internal/api/token_response_media_test.go b/internal/api/token_response_media_test.go
index 387164f39f..8ab73f3869 100644
--- a/internal/api/token_response_media_test.go
+++ b/internal/api/token_response_media_test.go
@@ -5,6 +5,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"testing"
@@ -33,7 +34,7 @@ var responseMediaCases = []responseMediaCase{
// automatic HTML sniff when a downstream writer omits Content-Type.
func requestResponseMedia(t *testing.T, media responseMediaCase, explicit bool) (http.Header, int, []byte) {
t.Helper()
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writer := &tokenResponseWriter{writer: w, header: w.Header().Clone(), allowed: func() bool { return true }}
defer writer.close()
if media.contentType != "" {
@@ -43,12 +44,13 @@ func requestResponseMedia(t *testing.T, media responseMediaCase, explicit bool)
if explicit {
writer.WriteHeader(http.StatusAccepted)
}
- if _, err := writer.Write([]byte(responseMediaMarkup)); err != nil {
+ writer.WriteHeader(http.StatusEarlyHints)
+ if _, err := writer.Write([]byte(r.URL.Query().Get("content"))); err != nil {
t.Error(err)
}
}))
defer server.Close()
- response, err := server.Client().Get(server.URL)
+ response, err := server.Client().Get(server.URL + "?content=" + url.QueryEscape(responseMediaMarkup))
if err != nil {
t.Fatal(err)
}
diff --git a/internal/api/token_stream_lifetime.go b/internal/api/token_stream_lifetime.go
index 313f56159c..bd93cf3ae9 100644
--- a/internal/api/token_stream_lifetime.go
+++ b/internal/api/token_stream_lifetime.go
@@ -4,6 +4,7 @@ import (
"context"
"io"
"net/http"
+ "strings"
"sync"
"time"
@@ -91,6 +92,7 @@ type tokenStreamWriter struct {
allowed func() bool
mu sync.Mutex
closed bool
+ started bool
}
func (w *tokenStreamWriter) Header() http.Header { return w.writer.Header() }
@@ -134,12 +136,31 @@ func (w *tokenStreamWriter) check() bool {
return w.checkLocked()
}
+// All guarded stream routes carry SSE data or structured/plain errors. Pin
+// their media before any operation can commit the transport, including Flush.
+func (w *tokenStreamWriter) prepareMediaLocked() string {
+ header := w.writer.Header()
+ contentType := responseContentType(header, responseMediaEventStream)
+ for key := range header {
+ if strings.EqualFold(key, "Content-Type") || strings.EqualFold(key, "X-Content-Type-Options") {
+ delete(header, key)
+ }
+ }
+ return contentType
+}
+
func (w *tokenStreamWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
if !w.checkLocked() {
return 0, io.ErrClosedPipe
}
+ if !w.started {
+ contentType := w.prepareMediaLocked()
+ w.writer.Header().Set("Content-Type", contentType)
+ w.writer.Header().Set("X-Content-Type-Options", "nosniff")
+ w.started = true
+ }
n, err := w.writer.Write(p)
if err != nil {
w.closed = true
@@ -152,6 +173,12 @@ func (w *tokenStreamWriter) WriteHeader(status int) {
w.mu.Lock()
defer w.mu.Unlock()
if w.checkLocked() {
+ if !w.started {
+ contentType := w.prepareMediaLocked()
+ w.writer.Header().Set("Content-Type", contentType)
+ w.writer.Header().Set("X-Content-Type-Options", "nosniff")
+ w.started = status >= 200 || status == http.StatusSwitchingProtocols
+ }
w.writer.WriteHeader(status)
}
}
@@ -160,6 +187,12 @@ func (w *tokenStreamWriter) Flush() {
w.mu.Lock()
defer w.mu.Unlock()
if w.checkLocked() {
+ if !w.started {
+ contentType := w.prepareMediaLocked()
+ w.writer.Header().Set("Content-Type", contentType)
+ w.writer.Header().Set("X-Content-Type-Options", "nosniff")
+ w.started = true
+ }
w.flusher.Flush()
}
}
diff --git a/internal/api/token_stream_lifetime_test.go b/internal/api/token_stream_lifetime_test.go
index aa36908660..6c4d621d9f 100644
--- a/internal/api/token_stream_lifetime_test.go
+++ b/internal/api/token_stream_lifetime_test.go
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"sync"
"testing"
@@ -24,6 +25,57 @@ const scopedReadToken = "synthetic-scoped-stream.12345678"
const scopedReadControl = "synthetic-scoped-control.12345678"
const scopedReadMonitor = "synthetic-monitor-reader.12345678"
+func TestTokenStreamWriterNativeMedia(t *testing.T) {
+ cases := append(append([]responseMediaCase(nil), responseMediaCases...),
+ responseMediaCase{"sse", "text/event-stream", "text/event-stream; charset=utf-8"},
+ responseMediaCase{"sse_parameters", "Text/Event-Stream; charset=iso-8859-1", "text/event-stream; charset=utf-8"})
+ for _, media := range cases {
+ for _, commit := range []string{"write", "header", "flush", "informational"} {
+ t.Run(media.name+"/"+commit, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithCancel(r.Context())
+ writer := &tokenStreamWriter{writer: w, flusher: w.(http.Flusher), ctx: ctx, cancel: cancel, allowed: func() bool { return true }}
+ defer writer.close()
+ if media.contentType != "" {
+ writer.Header().Set("Content-Type", media.contentType)
+ }
+ writer.Header()["content-type"] = []string{"text/html"}
+ writer.Header()["x-content-type-options"] = []string{"invalid"}
+ writer.Header().Set("X-Synthetic-Result", "preserved")
+ switch commit {
+ case "header":
+ writer.WriteHeader(http.StatusAccepted)
+ case "flush":
+ writer.Flush()
+ case "informational":
+ writer.WriteHeader(http.StatusEarlyHints)
+ }
+ if _, err := writer.Write([]byte(r.URL.Query().Get("content"))); err != nil {
+ t.Error(err)
+ }
+ }))
+ defer server.Close()
+ response, err := server.Client().Get(server.URL + "?content=" + url.QueryEscape(responseMediaMarkup))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(response.Body)
+ wantStatus := http.StatusOK
+ if commit == "header" {
+ wantStatus = http.StatusAccepted
+ }
+ if err != nil || response.StatusCode != wantStatus || string(body) != responseMediaMarkup || response.Header.Get("X-Synthetic-Result") != "preserved" {
+ t.Fatalf("response changed: status=%d headers=%v body=%q error=%v", response.StatusCode, response.Header, body, err)
+ }
+ if response.Header.Get("Content-Type") != media.wantType || len(response.Header.Values("Content-Type")) != 1 || response.Header.Get("X-Content-Type-Options") != "nosniff" || len(response.Header.Values("X-Content-Type-Options")) != 1 {
+ t.Fatalf("unsafe stream media: %v", response.Header)
+ }
+ })
+ }
+ }
+}
+
var protectedReadKinds = []string{"updates", "patrol", "preflights", "jobs"}
type protectedReadFixture struct {
diff --git a/scripts/tests/test_dependabot_config.py b/scripts/tests/test_dependabot_config.py
index 818d223e09..f1395ad561 100644
--- a/scripts/tests/test_dependabot_config.py
+++ b/scripts/tests/test_dependabot_config.py
@@ -144,18 +144,15 @@ class DependabotConfigTest(unittest.TestCase):
# PR 3178 rebundled the deferred SQLite/libc pair with a new Prometheus
# patch immediately after the non-storage refresh landed. Keep the
# driver's transitives in its own reviewable proposal, in either order.
- for dependency in (
- "modernc.org/sqlite",
- "modernc.org/libc",
- "modernc.org/memory",
- "modernc.org/mathutil",
- "github.com/prometheus/common",
- "github.com/klauspost/compress",
- "golang.org/x/net",
+ for dependency, expected in (
+ ("modernc.org/sqlite", "go-storage-runtime"),
+ ("modernc.org/libc", "go-storage-runtime"),
+ ("modernc.org/memory", "go-storage-runtime"),
+ ("modernc.org/mathutil", "go-storage-runtime"),
+ ("github.com/prometheus/common", "go-minor-patch"),
+ ("github.com/klauspost/compress", "go-minor-patch"),
+ ("golang.org/x/net", "go-minor-patch"),
):
- expected = (
- "go-storage-runtime" if dependency.startswith("modernc.org/") else "go-minor-patch"
- )
for update_type in ("minor", "patch"):
with self.subTest(dependency=dependency, update_type=update_type):
self.assertEqual(
diff --git a/scripts/tests/test_signed_installer_docs.py b/scripts/tests/test_signed_installer_docs.py
index d481620d74..f1c689c2af 100644
--- a/scripts/tests/test_signed_installer_docs.py
+++ b/scripts/tests/test_signed_installer_docs.py
@@ -3,6 +3,7 @@
import os
from contextlib import contextmanager
+from http.client import HTTPSConnection
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import re
@@ -56,7 +57,8 @@ def download_servers(root, mode):
self.send_response(302)
origin = (f"http://127.0.0.1:{plain.server_port}" if mode == "downgrade"
else f"https://127.0.0.1:{secure.server_port}")
- self.send_header("Location", origin + "/final/" + self.path.rsplit("/", 1)[-1])
+ asset_name = "install.sh.sshsig" if self.path.endswith(".sshsig") else "install.sh"
+ self.send_header("Location", origin + "/final/" + asset_name)
self.end_headers()
return
is_signature = self.path.endswith(".sshsig")
@@ -75,6 +77,7 @@ def download_servers(root, mode):
plain = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
secure = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(root / "tls.crt", root / "tls.key")
secure.socket = context.wrap_socket(secure.socket, server_side=True)
# Poll only the fixture server more often so teardown need not wait 500 ms.
@@ -127,6 +130,27 @@ def run_local_recipe(root, block, secure_port, plain_port, *, trust=True):
class SignedInstallerDocsTest(unittest.TestCase):
+ def test_redirects_cannot_reflect_request_paths(self):
+ for mode in ("redirect", "downgrade"):
+ with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ with download_servers(root, mode) as (secure, plain, _requests):
+ context = ssl.create_default_context(cafile=str(root / "tls.crt"))
+ connection = HTTPSConnection("127.0.0.1", secure, context=context, timeout=5)
+ try:
+ for path, asset in (("/release/untrusted-name%0D%0AX-Injected:value", "install.sh"),
+ ("/release/untrusted-name.sshsig", "install.sh.sshsig")):
+ connection.request("GET", path)
+ response = connection.getresponse()
+ origin = (f"http://127.0.0.1:{plain}" if mode == "downgrade"
+ else f"https://127.0.0.1:{secure}")
+ self.assertEqual(response.status, 302)
+ self.assertEqual(response.getheader("Location"), origin + "/final/" + asset)
+ self.assertIsNone(response.getheader("X-Injected"))
+ response.read()
+ finally:
+ connection.close()
+
def test_fixture_signer_replacement_preserves_policy_and_requires_one_key(self):
for block in recipes():
with self.subTest(recipe=block.splitlines()[0]):