Keep step-up elevation for the signed-in session and stop gating terminals

The proxy forwards an HMAC-derived session id (X-Pipelines-Session) on
/connect and POST /files; the server trusts it only on token-authenticated
requests and keys elevation by it, so reconnects stay elevated up to a 24 h
cap. Terminals rely on their su -l login. The app no longer forgets the
elevation on disconnect and asks again only on a fresh refusal.
This commit is contained in:
2026-11-10 03:00:45 +00:00
parent 60b4c495f1
commit 1ad85de1f1
19 changed files with 876 additions and 165 deletions
+97 -57
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"log"
"strings"
"sync"
"time"
@@ -16,19 +17,29 @@ import (
// Step-up re-authentication (see internal/protocol/elevation.go). A web
// session is enough to read, but the requests below act as the operator's
// shell, so each connection must also confirm the sign-in password recently.
// shell, so the operator must also confirm the sign-in password once.
//
// A confirmation is keyed by the web session the token-authenticated proxy
// reports (trustedSession): every connection and reconnect of that session
// stays elevated until the cap (DefaultElevationTTL) passes. The session ending
// ends it too: the proxy closes the session's sockets and refuses its cookie,
// and its derived id changes with every new sign-in and every password change
// or revoke-all, so no later request can name the old elevation. A connection
// without a trusted session id (no server token configured, a direct client)
// is elevated by itself only, until it closes.
//
// The gate is on whenever the web sign-in password file exists; a server run
// without the web proxy (tests, a bare loopback server) has nothing to verify
// against and keeps its previous behaviour. A file that exists but cannot be
// read safely keeps the gate on and every elevate fails (fail closed).
// DefaultElevationTTL is how long one confirmation lasts on a connection.
const DefaultElevationTTL = 15 * time.Minute
// DefaultElevationTTL caps how long one confirmation lasts.
const DefaultElevationTTL = 24 * time.Hour
// Elevation attempt limits: a connection waits elevationBackoffBase doubled
// for each consecutive wrong password (at most elevationBackoffMax), and the
// whole server refuses attempts after elevationGlobalFailures wrong passwords
// within elevationGlobalWindow.
// Elevation attempt limits: a key waits elevationBackoffBase doubled for each
// consecutive wrong password (at most elevationBackoffMax), and the whole
// server refuses attempts after elevationGlobalFailures wrong passwords within
// elevationGlobalWindow. At most elevationTokenLimit elevations live at once.
const (
elevationBackoffBase = time.Second
elevationBackoffMax = time.Minute
@@ -37,14 +48,34 @@ const (
elevationTokenLimit = 256
)
// Terminals are deliberately absent: terminal_open starts `su -l`, so the OS
// account password is the barrier there.
var elevationGated = map[string]bool{
protocol.ChatShellRun: true,
protocol.ChatShellInput: true,
protocol.RenamePath: true,
protocol.MovePath: true,
protocol.DeletePath: true,
protocol.TerminalOpen: true,
protocol.TerminalInput: true,
}
const (
sessionKeyPrefix = "session:"
connectionKeyPrefix = "conn:"
)
// sessionElevationKey keys elevation by a trusted web session id.
func sessionElevationKey(session string) string { return sessionKeyPrefix + session }
// connectionElevationKey keys elevation by one websocket connection.
func connectionElevationKey(client string) string { return connectionKeyPrefix + client }
// elevationKeyFor is the key a connection elevates under: its web session
// when the proxy reported one, else the connection itself.
func elevationKeyFor(session, client string) string {
if session != "" {
return sessionElevationKey(session)
}
return connectionElevationKey(client)
}
type elevationGate struct {
@@ -55,7 +86,7 @@ type elevationGate struct {
verify sync.Mutex
mu sync.Mutex
until map[string]time.Time // client -> elevation end
until map[string]time.Time // key -> elevation end
tokens map[string]elevationToken
failures map[string]elevationFailures
recent []time.Time // wrong passwords, server-wide, oldest first
@@ -63,8 +94,8 @@ type elevationGate struct {
}
type elevationToken struct {
client string
until time.Time
key string
until time.Time
}
type elevationFailures struct {
@@ -106,43 +137,43 @@ func (g *elevationGate) enabled() bool {
return true
}
func (g *elevationGate) elevated(client string) bool {
func (g *elevationGate) elevated(key string) bool {
g.mu.Lock()
defer g.mu.Unlock()
until, ok := g.until[client]
until, ok := g.until[key]
if ok && !g.now().Before(until) {
g.dropLocked(client)
g.dropLocked(key)
return false
}
return ok
}
// allows reports whether client may perform a gated request now.
func (g *elevationGate) allows(client string) bool {
return g.elevated(client) || !g.enabled()
// allows reports whether key may perform a gated request now.
func (g *elevationGate) allows(key string) bool {
return g.elevated(key) || !g.enabled()
}
// refuse answers a gated request on a connection that is not elevated with a
// typed error and reports true; any other request passes (false).
func (g *elevationGate) refuse(request protocol.Message, client string, write func(protocol.Message) error) bool {
if !elevationGated[request.Type] || g.allows(client) {
// refuse answers a gated request whose key is not elevated with a typed error
// and reports true; any other request passes (false).
func (g *elevationGate) refuse(request protocol.Message, key string, write func(protocol.Message) error) bool {
if !elevationGated[request.Type] || g.allows(key) {
return false
}
_ = write(protocol.Message{
Type: protocol.Error,
ID: request.ID,
Code: protocol.ErrorElevationRequired,
Error: "Confirm your password to run commands, change files or use a terminal on this machine.",
Error: "Confirm your password to run commands or change files on this machine.",
})
return true
}
// handle answers an elevate request and reports true; other requests pass.
func (g *elevationGate) handle(request protocol.Message, client string, write func(protocol.Message) error) bool {
func (g *elevationGate) handle(request protocol.Message, key string, write func(protocol.Message) error) bool {
if request.Type != protocol.Elevate {
return false
}
reply, err := g.elevate(client, request.Password)
reply, err := g.elevate(key, request.Password)
if err != nil {
code := protocol.ErrorElevationFailed
if errors.Is(err, errWebAuthMissing) {
@@ -155,11 +186,11 @@ func (g *elevationGate) handle(request protocol.Message, client string, write fu
return true
}
func (g *elevationGate) elevate(client, password string) (*protocol.Elevation, error) {
func (g *elevationGate) elevate(key, password string) (*protocol.Elevation, error) {
if g == nil || g.authFile == "" {
return nil, fmt.Errorf("this server has no web sign-in password to confirm: %w", errWebAuthMissing)
}
if wait := g.blocked(client); wait > 0 {
if wait := g.blocked(key); wait > 0 {
return nil, fmt.Errorf("too many wrong passwords; try again in %d seconds", int((wait+time.Second-1)/time.Second))
}
verifier, err := readWebAuth(g.authFile)
@@ -178,13 +209,13 @@ func (g *elevationGate) elevate(client, password string) (*protocol.Elevation, e
return nil, errors.New("the password could not be checked; see the server log")
}
if !ok {
g.noteFailure(client)
g.noteFailure(key)
return nil, errors.New("wrong password")
}
return g.grant(client)
return g.grant(key)
}
func (g *elevationGate) blocked(client string) time.Duration {
func (g *elevationGate) blocked(key string) time.Duration {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
@@ -192,7 +223,7 @@ func (g *elevationGate) blocked(client string) time.Duration {
if len(g.recent) >= elevationGlobalFailures {
return g.recent[0].Add(elevationGlobalWindow).Sub(now)
}
if entry, ok := g.failures[client]; ok && now.Before(entry.until) {
if entry, ok := g.failures[key]; ok && now.Before(entry.until) {
return entry.until.Sub(now)
}
return 0
@@ -206,19 +237,26 @@ func (g *elevationGate) pruneLocked(now time.Time) {
g.recent = g.recent[keep:]
}
func (g *elevationGate) noteFailure(client string) {
func (g *elevationGate) noteFailure(key string) {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
g.recent = append(g.recent, now)
entry := g.failures[client]
// A session's failures outlive its connections; drop entries whose wait
// is long over so the map stays bounded by recent activity.
for other, entry := range g.failures {
if !now.Before(entry.until.Add(elevationGlobalWindow)) {
delete(g.failures, other)
}
}
entry := g.failures[key]
entry.count++
delay := elevationBackoffBase << min(entry.count-1, 6)
entry.until = now.Add(min(delay, elevationBackoffMax))
g.failures[client] = entry
g.failures[key] = entry
}
func (g *elevationGate) grant(client string) (*protocol.Elevation, error) {
func (g *elevationGate) grant(key string) (*protocol.Elevation, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return nil, err
@@ -228,18 +266,18 @@ func (g *elevationGate) grant(client string) (*protocol.Elevation, error) {
defer g.mu.Unlock()
now := g.now()
until := now.Add(g.ttl)
g.dropLocked(client)
delete(g.failures, client)
for key, entry := range g.tokens {
if !now.Before(entry.until) {
delete(g.tokens, key)
g.dropLocked(key)
delete(g.failures, key)
for other, end := range g.until {
if !now.Before(end) {
g.dropLocked(other)
}
}
if len(g.tokens) >= elevationTokenLimit {
return nil, errors.New("too many elevated connections on this server")
if len(g.until) >= elevationTokenLimit {
return nil, errors.New("too many elevated sessions on this server")
}
g.until[client] = until
g.tokens[tokenKey(token)] = elevationToken{client: client, until: until}
g.until[key] = until
g.tokens[tokenKey(token)] = elevationToken{key: key, until: until}
return &protocol.Elevation{
ExpiresAt: until.UTC().Format(time.RFC3339),
Seconds: int(g.ttl / time.Second),
@@ -252,28 +290,30 @@ func tokenKey(token string) string {
return hex.EncodeToString(sum[:])
}
// dropLocked ends client's elevation and its upload token.
func (g *elevationGate) dropLocked(client string) {
delete(g.until, client)
for key, entry := range g.tokens {
if entry.client == client {
delete(g.tokens, key)
// dropLocked ends key's elevation and its upload token.
func (g *elevationGate) dropLocked(key string) {
delete(g.until, key)
for hash, entry := range g.tokens {
if entry.key == key {
delete(g.tokens, hash)
}
}
}
// forget ends a closed connection's elevation and attempt history.
func (g *elevationGate) forget(client string) {
if g == nil {
// closed is called when a connection that elevated under key ends: a
// connection's own elevation and attempt history end with it, a web session's
// outlive it for that session's next connection.
func (g *elevationGate) closed(key string) {
if g == nil || !strings.HasPrefix(key, connectionKeyPrefix) {
return
}
g.mu.Lock()
defer g.mu.Unlock()
g.dropLocked(client)
delete(g.failures, client)
g.dropLocked(key)
delete(g.failures, key)
}
// tokenValid reports whether token belongs to a still elevated connection.
// tokenValid reports whether token belongs to a still live elevation.
func (g *elevationGate) tokenValid(token string) bool {
if token == "" {
return false
@@ -285,7 +325,7 @@ func (g *elevationGate) tokenValid(token string) bool {
return false
}
if !g.now().Before(entry.until) {
g.dropLocked(entry.client)
g.dropLocked(entry.key)
return false
}
return true
+13 -6
View File
@@ -10,12 +10,15 @@ import (
)
// requireElevationHTTP guards an HTTP route that changes the operator's files.
// The upload travels outside the websocket, so the elevated connection's token
// (protocol.ElevationHeader) authorises it; it is valid only while that
// connection stays open and elevated.
// The upload travels outside the websocket. It is allowed when the web session
// the proxy reports is elevated, or when it carries a live elevation's token
// (protocol.ElevationHeader; a connection-only elevation's token ends with its
// connection).
func (g *elevationGate) requireElevationHTTP(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if g.tokenValid(r.Header.Get(protocol.ElevationHeader)) || !g.enabled() {
session := trustedSession(r)
if (session != "" && g.elevated(sessionElevationKey(session))) ||
g.tokenValid(r.Header.Get(protocol.ElevationHeader)) || !g.enabled() {
next(w, r)
return
}
@@ -29,11 +32,15 @@ func (g *elevationGate) requireElevationHTTP(next http.HandlerFunc) http.Handler
}
}
// ElevationTTLFromEnvironment reads PIPELINES_ELEVATION_MINUTES (1 to 720);
// maxElevationMinutes is the longest PIPELINES_ELEVATION_MINUTES accepted:
// 30 days, the longest a remembered web session lasts.
const maxElevationMinutes = 30 * 24 * 60
// ElevationTTLFromEnvironment reads PIPELINES_ELEVATION_MINUTES (1 to 43200);
// anything else keeps DefaultElevationTTL.
func ElevationTTLFromEnvironment(getenv func(string) string) time.Duration {
minutes, err := strconv.Atoi(getenv("PIPELINES_ELEVATION_MINUTES"))
if err != nil || minutes < 1 || minutes > 720 {
if err != nil || minutes < 1 || minutes > maxElevationMinutes {
return DefaultElevationTTL
}
return time.Duration(minutes) * time.Minute
+193
View File
@@ -0,0 +1,193 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/servertoken"
)
const (
elevationTestPassword = "right password here"
elevationTestToken = "proxy-token-0123456789abcdefghijklmnopqrstuvwxyz"
sessionA = "session-a-0123456789abcdef"
sessionB = "session-b-0123456789abcdef"
)
// elevationServer serves a gated handler; token is the shared proxy token
// ("" for a server without one).
func elevationServer(t *testing.T, ctx context.Context, token string) *httptest.Server {
t.Helper()
t.Setenv("HOME", t.TempDir()) // the gated handlers never touch the real home
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{WebAuthFile: writeTestWebAuth(t, elevationTestPassword), AccessToken: token}))
t.Cleanup(srv.Close)
return srv
}
func proxiedHeaders(token, session string) http.Header {
headers := http.Header{}
if token != "" {
headers.Set(servertoken.Header, token)
}
if session != "" {
headers.Set(protocol.SessionHeader, session)
}
return headers
}
func dialAs(t *testing.T, ctx context.Context, srv *httptest.Server, token, session string) *websocket.Conn {
t.Helper()
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect",
&websocket.DialOptions{HTTPHeader: proxiedHeaders(token, session)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
return conn
}
var gatedDelete = protocol.Message{Type: protocol.DeletePath, ID: "delete", DeletePath: &protocol.DeletePathRequest{Path: "~/absent-elevation-test"}}
func refused(t *testing.T, ctx context.Context, conn *websocket.Conn) bool {
t.Helper()
return elevationRequest(t, ctx, conn, gatedDelete).Code == protocol.ErrorElevationRequired
}
func elevateOn(t *testing.T, ctx context.Context, conn *websocket.Conn) *protocol.Elevation {
t.Helper()
reply := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "elevate", Password: elevationTestPassword})
if reply.Type != protocol.Elevated || reply.Elevation == nil {
t.Fatalf("elevate: %+v", reply)
}
return reply.Elevation
}
func uploadAs(t *testing.T, srv *httptest.Server, token, session, elevation string) int {
t.Helper()
request, _ := http.NewRequest(http.MethodPost, srv.URL+"/files?path=~/absent-elevation-folder", strings.NewReader("x"))
request.Header = proxiedHeaders(token, session)
request.Header.Set(chatUploadHeader, "elevation-test.txt")
if elevation != "" {
request.Header.Set(protocol.ElevationHeader, elevation)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
return response.StatusCode
}
func TestElevationLastsForTheWebSessionAcrossConnections(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
srv := elevationServer(t, ctx, elevationTestToken)
first := dialAs(t, ctx, srv, elevationTestToken, sessionA)
if !refused(t, ctx, first) {
t.Fatal("unelevated session allowed")
}
if uploadAs(t, srv, elevationTestToken, sessionA, "") != http.StatusForbidden {
t.Fatal("upload allowed before elevation")
}
elevateOn(t, ctx, first)
first.Close(websocket.StatusNormalClosure, "")
// A reconnect of the same session is elevated without asking again.
second := dialAs(t, ctx, srv, elevationTestToken, sessionA)
if refused(t, ctx, second) {
t.Fatal("reconnected session lost its elevation")
}
if uploadAs(t, srv, elevationTestToken, sessionA, "") == http.StatusForbidden {
t.Fatal("elevated session's upload refused")
}
// Another session, and a connection naming no session, are not.
if !refused(t, ctx, dialAs(t, ctx, srv, elevationTestToken, sessionB)) {
t.Fatal("a different session inherited elevation")
}
if !refused(t, ctx, dialAs(t, ctx, srv, elevationTestToken, "")) {
t.Fatal("a connection without a session inherited elevation")
}
if uploadAs(t, srv, elevationTestToken, sessionB, "") != http.StatusForbidden {
t.Fatal("a different session's upload allowed")
}
// A malformed id is not trusted (and so elevates nothing shared).
if !refused(t, ctx, dialAs(t, ctx, srv, elevationTestToken, "short")) {
t.Fatal("malformed session id trusted")
}
}
func TestSessionHeaderIgnoredWithoutTheProxyToken(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
srv := elevationServer(t, ctx, "")
first := dialAs(t, ctx, srv, "", sessionA)
token := elevateOn(t, ctx, first).Token
if refused(t, ctx, first) {
t.Fatal("elevated connection refused")
}
// Without a configured token the header names nothing: a second
// connection claiming the same session is not elevated.
if !refused(t, ctx, dialAs(t, ctx, srv, "", sessionA)) {
t.Fatal("untrusted session header shared elevation")
}
if uploadAs(t, srv, "", sessionA, "") != http.StatusForbidden {
t.Fatal("untrusted session header authorised an upload")
}
// The connection's own token still works until the connection closes.
if uploadAs(t, srv, "", "", token) == http.StatusForbidden {
t.Fatal("connection token refused")
}
first.Close(websocket.StatusNormalClosure, "")
deadline := time.Now().Add(5 * time.Second)
for uploadAs(t, srv, "", "", token) != http.StatusForbidden {
if time.Now().After(deadline) {
t.Fatal("connection token outlived its connection")
}
time.Sleep(50 * time.Millisecond)
}
}
func TestBoundaryTrustsSessionOnlyWithToken(t *testing.T) {
var seen []string
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = append(seen, trustedSession(r)+"|"+r.Header.Get(protocol.SessionHeader))
})
for _, token := range []string{"", elevationTestToken} {
request := httptest.NewRequest(http.MethodPost, "/files", nil)
request.Header = proxiedHeaders(token, sessionA)
guardRequests(next, token).ServeHTTP(httptest.NewRecorder(), request)
}
if len(seen) != 2 || seen[0] != "|" || seen[1] != sessionA+"|" {
t.Fatalf("session trust = %q", seen)
}
}
func TestSessionElevationCapAndClose(t *testing.T) {
gate := newElevationGate(writeTestWebAuth(t, elevationTestPassword), time.Hour)
now := time.Unix(1_800_000_000, 0)
gate.now = func() time.Time { return now }
key := sessionElevationKey(sessionA)
reply, err := gate.elevate(key, elevationTestPassword)
if err != nil || reply.Seconds != 3600 {
t.Fatalf("elevate: %+v %v", reply, err)
}
// A session's connection closing keeps the session elevated.
gate.closed(key)
if !gate.elevated(key) || !gate.tokenValid(reply.Token) {
t.Fatal("session elevation ended with a connection")
}
now = now.Add(time.Hour - time.Second)
if !gate.elevated(key) {
t.Fatal("session elevation ended before its cap")
}
now = now.Add(time.Second)
if gate.elevated(key) || gate.tokenValid(reply.Token) {
t.Fatal("session elevation outlived its cap")
}
}
+18 -7
View File
@@ -109,11 +109,12 @@ func TestElevationBackoffGlobalCapAndExpiry(t *testing.T) {
t.Fatalf("global cap not applied: %v", err)
}
now = now.Add(elevationGlobalWindow)
if _, err := gate.elevate("fresh", "right password here"); err != nil {
fresh := connectionElevationKey("fresh")
if _, err := gate.elevate(fresh, "right password here"); err != nil {
t.Fatalf("global window did not drain: %v", err)
}
gate.forget("fresh")
if gate.elevated("fresh") {
gate.closed(fresh)
if gate.elevated(fresh) {
t.Fatal("closed connection stayed elevated")
}
}
@@ -156,8 +157,6 @@ func TestGatedRequestsNeedElevationOnTheSameConnection(t *testing.T) {
{Type: protocol.DeletePath, ID: "delete", DeletePath: &protocol.DeletePathRequest{Path: "~/absent-elevation-test"}},
{Type: protocol.RenamePath, ID: "rename"},
{Type: protocol.MovePath, ID: "move"},
{Type: protocol.TerminalOpen, ID: "terminal"},
{Type: protocol.TerminalInput, ID: "terminal-input"},
}
for _, request := range gated {
reply := elevationRequest(t, ctx, conn, request)
@@ -165,6 +164,16 @@ func TestGatedRequestsNeedElevationOnTheSameConnection(t *testing.T) {
t.Fatalf("%s not refused: %+v", request.Type, reply)
}
}
// Terminals are not gated (su -l asks for the account password); this
// server has no store, so terminal_open fails on its own terms.
for _, request := range []protocol.Message{
{Type: protocol.TerminalOpen, ID: "terminal"},
{Type: protocol.TerminalInput, ID: "terminal-input", TerminalRequest: &protocol.TerminalRequest{TerminalID: "absent", Data: "x"}},
} {
if reply := elevationRequest(t, ctx, conn, request); reply.Code == protocol.ErrorElevationRequired {
t.Fatalf("%s gated: %+v", request.Type, reply)
}
}
// Reads are not gated.
if reply := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Ping, ID: "ping"}); reply.Type != protocol.Pong {
t.Fatalf("ping refused: %+v", reply)
@@ -233,11 +242,13 @@ func TestElevationGateOffWithoutWebAuthFile(t *testing.T) {
// A present but unusable file keeps the gate closed.
broken := writeTestAuthJSON(t, map[string]any{"secret": "x"})
closed := newElevationGate(broken, 0)
if !closed.refuse(protocol.Message{Type: protocol.TerminalOpen}, "a", write) {
if !closed.refuse(protocol.Message{Type: protocol.ChatShellRun}, "a", write) {
t.Fatal("unusable password file opened the gate")
}
if ElevationTTLFromEnvironment(func(string) string { return "30" }) != 30*time.Minute ||
ElevationTTLFromEnvironment(func(string) string { return "0" }) != DefaultElevationTTL {
ElevationTTLFromEnvironment(func(string) string { return "1440" }) != 24*time.Hour ||
ElevationTTLFromEnvironment(func(string) string { return "43201" }) != DefaultElevationTTL ||
ElevationTTLFromEnvironment(func(string) string { return "0" }) != DefaultElevationTTL || DefaultElevationTTL != 24*time.Hour {
t.Fatal("PIPELINES_ELEVATION_MINUTES not honoured")
}
}
+34
View File
@@ -1,10 +1,12 @@
package server
import (
"context"
"net"
"net/http"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/servertoken"
)
@@ -23,6 +25,11 @@ import (
// request must carry it in servertoken.Header, except the chat-tools MCP
// endpoint (its own per-chat token, loopback and no-Origin checks) and
// /healthz (a bare liveness boolean).
// - Session: protocol.SessionHeader names the web session a proxied request
// belongs to (an opaque id the proxy derives from the verified cookie). It
// is trusted only on a request that carried the configured token; it is
// always removed from the request and, when trusted, reaches handlers
// through the context (trustedSession).
type requestBoundary struct {
next http.Handler
token string
@@ -47,9 +54,36 @@ func (b requestBoundary) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// The secret never reaches a handler, a log line or a forwarded request.
r.Header.Del(servertoken.Header)
session := r.Header.Get(protocol.SessionHeader)
r.Header.Del(protocol.SessionHeader)
if b.token != "" && validSessionID(session) {
r = r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, session))
}
b.next.ServeHTTP(w, r)
}
type sessionContextKey struct{}
// trustedSession is the web session id the token-authenticated proxy reported
// for r, or "" (no server token configured, a direct client, or no header).
func trustedSession(r *http.Request) string {
session, _ := r.Context().Value(sessionContextKey{}).(string)
return session
}
// validSessionID bounds the proxy's opaque id: 16 to 128 URL-safe characters.
func validSessionID(value string) bool {
if len(value) < 16 || len(value) > 128 {
return false
}
for _, c := range value {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') {
return false
}
}
return true
}
func tokenExempt(path string) bool {
return path == "/healthz" || strings.HasPrefix(path, chatToolPath)
}
+6 -3
View File
@@ -71,7 +71,7 @@ type Options struct {
AccessToken string
// WebAuthFile is the web sign-in password file step-up re-authentication
// verifies against (see elevation.go); empty disables the gate.
// ElevationTTL is how long one confirmation lasts (default 15 minutes).
// ElevationTTL caps how long one confirmation lasts (default 24 hours).
WebAuthFile string
ElevationTTL time.Duration
}
@@ -233,7 +233,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// clientID is this connection's identity for chat session claims: a
// second client is refused a session another connection holds.
clientID := chatClientToken()
defer elevation.forget(clientID)
// Elevation belongs to the web session the proxy reported, so a
// reconnect stays elevated; without one, to this connection alone.
elevationKey := elevationKeyFor(trustedSession(r), clientID)
defer elevation.closed(elevationKey)
// Drop every run subscription this connection holds when the read loop
// returns, so no subscriber, goroutine or timer outlives the connection.
defer events.unsubscribeClient(clientID)
@@ -284,7 +287,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "pipeline authoring is disabled on this execution server; ask the operator to publish through an explicitly enabled authoring server"})
continue
}
if elevation.handle(request, clientID, write) || elevation.refuse(request, clientID, write) {
if elevation.handle(request, elevationKey, write) || elevation.refuse(request, elevationKey, write) {
continue
}
if isChatSearch(request) {