Require step-up password confirmation for shells, terminals and file changes

A new elevate request verifies the web sign-in password (scrypt hash, read-only,
rate-limited, constant time) and elevates that connection for 15 minutes.
chat_shell_run/input, rename/move/delete, terminal_open/input and POST /files
(via a per-connection upload token) are refused with code elevation_required
until then.
This commit is contained in:
2026-11-10 01:21:15 +00:00
parent a706739088
commit f11ff8650d
12 changed files with 963 additions and 1 deletions
+5
View File
@@ -81,6 +81,11 @@ func main() {
// harness; the summariser falls back to the prompt's first line, so title
// generation never blocks or fails run creation.
options := server.Options{AllowAuthoring: *allowAuthoring, ArtifactsRoot: artifactsRoot, RunTitles: summarise.GenerateTitle, StepVerdicts: summarise.GenerateVerdictReason, VerificationFixtures: server.VerificationFixturesFromEnvironment(os.Getenv), DetachSessions: detach}
// Shell commands, terminals and file changes need a recent confirmation of
// the web sign-in password on the same connection (step-up
// re-authentication). PIPELINES_ELEVATION_MINUTES overrides 15 minutes.
options.WebAuthFile = server.DefaultWebAuthFile()
options.ElevationTTL = server.ElevationTTLFromEnvironment(os.Getenv)
recorded := ""
if value, err := store.OpenCodeEndpoint(ctx); err != nil {
log.Printf("OpenCode endpoint setting unreadable: %v", err)
+39
View File
@@ -0,0 +1,39 @@
package protocol
// Step-up re-authentication. A signed-in web session can read everything, but
// running shell commands, typing into a shell, changing or uploading files and
// opening a terminal additionally need a recent password confirmation on the
// same connection. The server verifies the password against the web sign-in
// password file; the elevation lasts for a bounded time (15 minutes by
// default) and ends with the connection.
const (
// Elevate confirms the sign-in password (Message.Password). The reply is
// Elevated, or Error with Code ErrorElevationFailed or
// ErrorElevationUnavailable.
Elevate = "elevate"
// Elevated carries Elevation: when it ends and the upload token.
Elevated = "elevated"
// ErrorElevationRequired types the refusal of a gated request on a
// connection that is not (or no longer) elevated. Clients confirm the
// password with Elevate and retry.
ErrorElevationRequired = "elevation_required"
// ErrorElevationFailed types a wrong password or a rate-limited attempt.
ErrorElevationFailed = "elevation_failed"
// ErrorElevationUnavailable types an elevate on a server without a web
// sign-in password file (nothing is gated there).
ErrorElevationUnavailable = "elevation_unavailable"
// ElevationHeader carries Elevation.Token on POST /files. A refused upload
// answers 403 with a JSON body {"code":"elevation_required","error":...}.
ElevationHeader = "X-Pipelines-Elevation"
)
// Elevation is the elevated reply body.
type Elevation struct {
// ExpiresAt is RFC 3339 UTC; Seconds is the remaining lifetime, for
// clients whose clock differs from the server's.
ExpiresAt string `json:"expires_at"`
Seconds int `json:"seconds"`
// Token authorises HTTP uploads for as long as this connection stays
// elevated. It is random, held only in memory and never logged.
Token string `json:"token,omitempty"`
}
+6
View File
@@ -302,6 +302,12 @@ type Message struct {
MovePath *MovePathRequest `json:"move_path,omitempty"`
DeletePath *DeletePathRequest `json:"delete_path,omitempty"`
PathMutated *PathMutatedResult `json:"path_mutated,omitempty"`
// Step-up re-authentication (see elevation.go): Code types an error,
// Password is the elevate body (never logged or echoed) and Elevation the
// elevated reply.
Code string `json:"code,omitempty"`
Password string `json:"password,omitempty"`
Elevation *Elevation `json:"elevation,omitempty"`
// ChatAttachmentImageRequest is the chat_attachment_image body and
// ChatAttachmentImage its reply.
ChatAttachmentImageRequest *ChatAttachmentImageRequest `json:"chat_attachment_image_request,omitempty"`
+292
View File
@@ -0,0 +1,292 @@
package server
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// 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.
// 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
// 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.
const (
elevationBackoffBase = time.Second
elevationBackoffMax = time.Minute
elevationGlobalFailures = 10
elevationGlobalWindow = 5 * time.Minute
elevationTokenLimit = 256
)
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,
}
type elevationGate struct {
authFile string
ttl time.Duration
now func() time.Time
// verify serializes scrypt work: one 32 MiB derivation at a time.
verify sync.Mutex
mu sync.Mutex
until map[string]time.Time // client -> elevation end
tokens map[string]elevationToken
failures map[string]elevationFailures
recent []time.Time // wrong passwords, server-wide, oldest first
reported bool
}
type elevationToken struct {
client string
until time.Time
}
type elevationFailures struct {
count int
until time.Time
}
func newElevationGate(authFile string, ttl time.Duration) *elevationGate {
if ttl <= 0 {
ttl = DefaultElevationTTL
}
return &elevationGate{
authFile: authFile,
ttl: ttl,
now: time.Now,
until: map[string]time.Time{},
tokens: map[string]elevationToken{},
failures: map[string]elevationFailures{},
}
}
// enabled reports whether gated requests need elevation.
func (g *elevationGate) enabled() bool {
if g == nil || g.authFile == "" {
return false
}
_, err := readWebAuth(g.authFile)
if errors.Is(err, errWebAuthMissing) {
return false
}
if err != nil {
g.mu.Lock()
if !g.reported {
log.Printf("elevation: web sign-in password file unusable, every elevate fails: %v", err)
g.reported = true
}
g.mu.Unlock()
}
return true
}
func (g *elevationGate) elevated(client string) bool {
g.mu.Lock()
defer g.mu.Unlock()
until, ok := g.until[client]
if ok && !g.now().Before(until) {
g.dropLocked(client)
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()
}
// 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) {
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.",
})
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 {
if request.Type != protocol.Elevate {
return false
}
reply, err := g.elevate(client, request.Password)
if err != nil {
code := protocol.ErrorElevationFailed
if errors.Is(err, errWebAuthMissing) {
code = protocol.ErrorElevationUnavailable
}
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Code: code, Error: err.Error()})
return true
}
_ = write(protocol.Message{Type: protocol.Elevated, ID: request.ID, Elevation: reply})
return true
}
func (g *elevationGate) elevate(client, 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 {
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)
if errors.Is(err, errWebAuthMissing) {
return nil, fmt.Errorf("this server has no web sign-in password to confirm: %w", err)
}
if err != nil {
log.Printf("elevation: web sign-in password file unusable: %v", err)
return nil, errors.New("the server's sign-in password file is unusable; see the server log")
}
g.verify.Lock()
ok, err := verifier.verify(password)
g.verify.Unlock()
if err != nil {
log.Printf("elevation: verify: %v", err)
return nil, errors.New("the password could not be checked; see the server log")
}
if !ok {
g.noteFailure(client)
return nil, errors.New("wrong password")
}
return g.grant(client)
}
func (g *elevationGate) blocked(client string) time.Duration {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
g.pruneLocked(now)
if len(g.recent) >= elevationGlobalFailures {
return g.recent[0].Add(elevationGlobalWindow).Sub(now)
}
if entry, ok := g.failures[client]; ok && now.Before(entry.until) {
return entry.until.Sub(now)
}
return 0
}
func (g *elevationGate) pruneLocked(now time.Time) {
keep := 0
for keep < len(g.recent) && !now.Before(g.recent[keep].Add(elevationGlobalWindow)) {
keep++
}
g.recent = g.recent[keep:]
}
func (g *elevationGate) noteFailure(client string) {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
g.recent = append(g.recent, now)
entry := g.failures[client]
entry.count++
delay := elevationBackoffBase << min(entry.count-1, 6)
entry.until = now.Add(min(delay, elevationBackoffMax))
g.failures[client] = entry
}
func (g *elevationGate) grant(client string) (*protocol.Elevation, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return nil, err
}
token := base64.RawURLEncoding.EncodeToString(raw)
g.mu.Lock()
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)
}
}
if len(g.tokens) >= elevationTokenLimit {
return nil, errors.New("too many elevated connections on this server")
}
g.until[client] = until
g.tokens[tokenKey(token)] = elevationToken{client: client, until: until}
return &protocol.Elevation{
ExpiresAt: until.UTC().Format(time.RFC3339),
Seconds: int(g.ttl / time.Second),
Token: token,
}, nil
}
func tokenKey(token string) string {
sum := sha256.Sum256([]byte(token))
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)
}
}
}
// forget ends a closed connection's elevation and attempt history.
func (g *elevationGate) forget(client string) {
if g == nil {
return
}
g.mu.Lock()
defer g.mu.Unlock()
g.dropLocked(client)
delete(g.failures, client)
}
// tokenValid reports whether token belongs to a still elevated connection.
func (g *elevationGate) tokenValid(token string) bool {
if token == "" {
return false
}
g.mu.Lock()
defer g.mu.Unlock()
entry, ok := g.tokens[tokenKey(token)]
if !ok {
return false
}
if !g.now().Before(entry.until) {
g.dropLocked(entry.client)
return false
}
return true
}
+40
View File
@@ -0,0 +1,40 @@
package server
import (
"encoding/json"
"net/http"
"strconv"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// 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.
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() {
next(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusForbidden)
_ = json.NewEncoder(w).Encode(map[string]string{
"code": protocol.ErrorElevationRequired,
"error": "Confirm your password to upload files to this machine.",
})
}
}
// ElevationTTLFromEnvironment reads PIPELINES_ELEVATION_MINUTES (1 to 720);
// 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 {
return DefaultElevationTTL
}
return time.Duration(minutes) * time.Minute
}
+243
View File
@@ -0,0 +1,243 @@
package server
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// writeTestWebAuth writes a private auth file with a cheap scrypt hash.
func writeTestWebAuth(t *testing.T, password string) string {
t.Helper()
salt := []byte("0123456789abcdef")
key, err := scryptKey([]byte(password), salt, 1024, 8, 1, 32)
if err != nil {
t.Fatal(err)
}
hash := fmt.Sprintf("scrypt$1024$8$1$%s$%s", base64.RawURLEncoding.EncodeToString(salt), base64.RawURLEncoding.EncodeToString(key))
return writeTestAuthJSON(t, map[string]any{"password_hash": hash, "secret": strings.Repeat("s", 40), "generation": 1})
}
func writeTestAuthJSON(t *testing.T, value map[string]any) string {
t.Helper()
path := filepath.Join(t.TempDir(), "web-auth.json")
body, _ := json.Marshal(value)
if err := os.WriteFile(path, body, 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestWebAuthVerifierHashPlaintextAndUnsafeFiles(t *testing.T) {
verifier, err := readWebAuth(writeTestWebAuth(t, "correct horse battery staple"))
if err != nil {
t.Fatal(err)
}
for candidate, want := range map[string]bool{"correct horse battery staple": true, "correct horse battery stapl": false, "": false} {
if got, err := verifier.verify(candidate); err != nil || got != want {
t.Fatalf("verify(%q) = %v, %v", candidate, got, err)
}
}
legacy, err := readWebAuth(writeTestAuthJSON(t, map[string]any{"password": "legacy-password", "secret": strings.Repeat("s", 40)}))
if err != nil {
t.Fatal(err)
}
if ok, _ := legacy.verify("legacy-password"); !ok {
t.Fatal("legacy plaintext password not accepted")
}
if ok, _ := legacy.verify("legacy-passwore"); ok {
t.Fatal("wrong legacy password accepted")
}
public := writeTestWebAuth(t, "x")
if err := os.Chmod(public, 0o644); err != nil {
t.Fatal(err)
}
if _, err := readWebAuth(public); err == nil || !strings.Contains(err.Error(), "private") {
t.Fatalf("public file accepted: %v", err)
}
if _, err := readWebAuth(writeTestAuthJSON(t, map[string]any{"password_hash": "scrypt$1000$8$1$AAAA$BBBB"})); err == nil {
t.Fatal("malformed hash accepted")
}
if _, err := readWebAuth(filepath.Join(t.TempDir(), "absent.json")); err != errWebAuthMissing {
t.Fatalf("missing file: %v", err)
}
}
func TestElevationBackoffGlobalCapAndExpiry(t *testing.T) {
gate := newElevationGate(writeTestWebAuth(t, "right password here"), time.Minute)
now := time.Unix(1_800_000_000, 0)
gate.now = func() time.Time { return now }
if _, err := gate.elevate("a", "wrong"); err == nil || err.Error() != "wrong password" {
t.Fatalf("wrong password: %v", err)
}
// The connection now waits before its next attempt, even a right one.
if _, err := gate.elevate("a", "right password here"); err == nil || !strings.Contains(err.Error(), "too many") {
t.Fatalf("backoff not applied: %v", err)
}
now = now.Add(2 * time.Second)
reply, err := gate.elevate("a", "right password here")
if err != nil || reply.Seconds != 60 || reply.Token == "" {
t.Fatalf("elevate: %+v %v", reply, err)
}
if !gate.elevated("a") || !gate.tokenValid(reply.Token) || gate.elevated("b") {
t.Fatal("elevation state wrong after success")
}
now = now.Add(time.Minute)
if gate.elevated("a") || gate.tokenValid(reply.Token) {
t.Fatal("elevation outlived its lifetime")
}
// Ten wrong passwords from separate connections close the gate for all.
for i := range elevationGlobalFailures {
if _, err := gate.elevate(fmt.Sprintf("c%d", i), "wrong"); err == nil {
t.Fatal("wrong password accepted")
}
}
if _, err := gate.elevate("fresh", "right password here"); err == nil || !strings.Contains(err.Error(), "too many") {
t.Fatalf("global cap not applied: %v", err)
}
now = now.Add(elevationGlobalWindow)
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") {
t.Fatal("closed connection stayed elevated")
}
}
func elevationRequest(t *testing.T, ctx context.Context, conn *websocket.Conn, message protocol.Message) protocol.Message {
t.Helper()
if err := wsjson.Write(ctx, conn, message); err != nil {
t.Fatal(err)
}
for {
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.ID == message.ID {
return reply
}
}
}
func TestGatedRequestsNeedElevationOnTheSameConnection(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
t.Setenv("HOME", t.TempDir()) // the gated handlers never touch the real home
auth := writeTestWebAuth(t, "right password here")
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{WebAuthFile: auth, TerminalWithoutTmux: true}))
defer srv.Close()
dial := func() *websocket.Conn {
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
return conn
}
conn := dial()
gated := []protocol.Message{
{Type: protocol.ChatShellRun, ID: "run"},
{Type: protocol.ChatShellInput, ID: "input"},
{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)
if reply.Type != protocol.Error || reply.Code != protocol.ErrorElevationRequired {
t.Fatalf("%s not refused: %+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)
}
upload := func(token string) *http.Response {
request, _ := http.NewRequest(http.MethodPost, srv.URL+"/files?path=~/absent-elevation-folder", strings.NewReader("x"))
request.Header.Set(chatUploadHeader, "elevation-test.txt")
if token != "" {
request.Header.Set(protocol.ElevationHeader, token)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
return response
}
if response := upload(""); response.StatusCode != http.StatusForbidden {
t.Fatalf("upload without elevation: %d", response.StatusCode)
}
wrong := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "wrong", Password: "nope"})
if wrong.Type != protocol.Error || wrong.Code != protocol.ErrorElevationFailed || strings.Contains(wrong.Error, "nope") {
t.Fatalf("wrong password reply: %+v", wrong)
}
time.Sleep(elevationBackoffBase + 100*time.Millisecond)
elevated := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "right", Password: "right password here"})
if elevated.Type != protocol.Elevated || elevated.Elevation == nil || elevated.Elevation.Token == "" || elevated.Password != "" {
t.Fatalf("elevate reply: %+v", elevated)
}
// The gate now lets the request through to its own handler.
if reply := elevationRequest(t, ctx, conn, gated[2]); reply.Code == protocol.ErrorElevationRequired {
t.Fatalf("elevated delete still refused: %+v", reply)
}
// Another connection is not elevated by this one.
other := dial()
if reply := elevationRequest(t, ctx, other, gated[2]); reply.Code != protocol.ErrorElevationRequired {
t.Fatalf("second connection inherited elevation: %+v", reply)
}
if response := upload(elevated.Elevation.Token); response.StatusCode == http.StatusForbidden {
t.Fatal("upload with a live elevation token refused")
}
if response := upload("forged"); response.StatusCode != http.StatusForbidden {
t.Fatal("forged elevation token accepted")
}
conn.Close(websocket.StatusNormalClosure, "")
deadline := time.Now().Add(5 * time.Second)
for upload(elevated.Elevation.Token).StatusCode != http.StatusForbidden {
if time.Now().After(deadline) {
t.Fatal("upload token outlived its connection")
}
time.Sleep(50 * time.Millisecond)
}
}
func TestElevationGateOffWithoutWebAuthFile(t *testing.T) {
gate := newElevationGate(filepath.Join(t.TempDir(), "absent.json"), 0)
var wrote []protocol.Message
write := func(m protocol.Message) error { wrote = append(wrote, m); return nil }
if gate.refuse(protocol.Message{Type: protocol.ChatShellRun}, "a", write) || len(wrote) != 0 {
t.Fatal("gate refused without a password file")
}
gate.handle(protocol.Message{Type: protocol.Elevate, Password: "x"}, "a", write)
if len(wrote) != 1 || wrote[0].Code != protocol.ErrorElevationUnavailable {
t.Fatalf("elevate without a password file: %+v", wrote)
}
// 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) {
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 {
t.Fatal("PIPELINES_ELEVATION_MINUTES not honoured")
}
}
+148
View File
@@ -0,0 +1,148 @@
package server
import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
)
// The web sign-in password file (web-auth.json) is written by the installer,
// ./password and the web proxy. This server only reads it, to verify step-up
// re-authentication against the same password the operator signs in with.
//
// password_hash is "scrypt$N$r$p$<salt>$<key>" with unpadded base64url salt and
// key; a file not yet migrated by the proxy still holds a plaintext
// "password", which is compared in constant time through SHA-256 digests.
// webAuthMaxBytes bounds the file read; real files are a few hundred bytes.
const webAuthMaxBytes = 64 << 10
// DefaultWebAuthFile is where the installer keeps the web sign-in password.
func DefaultWebAuthFile() string {
if explicit := os.Getenv("PIPELINES_WEB_AUTH_FILE"); explicit != "" {
return explicit
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".config", "pipelines", "web-auth.json")
}
type webAuthVerifier struct {
hash string
password string
}
var errWebAuthMissing = errors.New("no web sign-in password file")
// readWebAuth loads the verifier from path. A missing file is
// errWebAuthMissing; anything unsafe or malformed is another error, and the
// caller then fails closed.
func readWebAuth(path string) (webAuthVerifier, error) {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return webAuthVerifier{}, errWebAuthMissing
}
if err != nil {
return webAuthVerifier{}, err
}
if !info.Mode().IsRegular() {
return webAuthVerifier{}, errors.New("web sign-in password file is not a regular file")
}
if info.Mode().Perm()&0o077 != 0 {
return webAuthVerifier{}, errors.New("web sign-in password file is not private (chmod 600)")
}
if !ownedByCurrentUser(info) {
return webAuthVerifier{}, errors.New("web sign-in password file belongs to another user")
}
file, err := os.Open(path)
if err != nil {
return webAuthVerifier{}, err
}
defer file.Close()
body, err := io.ReadAll(io.LimitReader(file, webAuthMaxBytes+1))
if err != nil {
return webAuthVerifier{}, err
}
if len(body) > webAuthMaxBytes {
return webAuthVerifier{}, errors.New("web sign-in password file is too large")
}
var parsed struct {
PasswordHash string `json:"password_hash"`
Password string `json:"password"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
return webAuthVerifier{}, errors.New("web sign-in password file is malformed")
}
if parsed.PasswordHash != "" {
if _, err := parseScryptHash(parsed.PasswordHash); err != nil {
return webAuthVerifier{}, err
}
return webAuthVerifier{hash: parsed.PasswordHash}, nil
}
if len(parsed.Password) >= 8 {
return webAuthVerifier{password: parsed.Password}, nil
}
return webAuthVerifier{}, errors.New("web sign-in password file has no password")
}
type scryptHash struct {
n, r, p int
salt, key []byte
}
func parseScryptHash(value string) (scryptHash, error) {
invalid := errors.New("web sign-in password hash is malformed")
parts := strings.Split(value, "$")
if len(parts) != 6 || parts[0] != "scrypt" {
return scryptHash{}, invalid
}
var numbers [3]int
for i, limit := range [3]int{1 << 20, 32, 16} {
number, err := strconv.Atoi(parts[i+1])
if err != nil || number < 1 || number > limit {
return scryptHash{}, invalid
}
numbers[i] = number
}
salt, err := base64.RawURLEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 {
return scryptHash{}, invalid
}
key, err := base64.RawURLEncoding.DecodeString(parts[5])
if err != nil || len(key) < 16 || len(key) > 64 {
return scryptHash{}, invalid
}
if numbers[0] < 2 || numbers[0]&(numbers[0]-1) != 0 {
return scryptHash{}, invalid
}
return scryptHash{n: numbers[0], r: numbers[1], p: numbers[2], salt: salt, key: key}, nil
}
// verify reports whether candidate is the stored password, in constant time
// with respect to the candidate's content.
func (v webAuthVerifier) verify(candidate string) (bool, error) {
if v.hash == "" {
given := sha256.Sum256([]byte(candidate))
want := sha256.Sum256([]byte(v.password))
return subtle.ConstantTimeCompare(given[:], want[:]) == 1 && v.password != "", nil
}
parsed, err := parseScryptHash(v.hash)
if err != nil {
return false, err
}
derived, err := scryptKey([]byte(candidate), parsed.salt, parsed.n, parsed.r, parsed.p, len(parsed.key))
if err != nil {
return false, fmt.Errorf("verify password: %w", err)
}
return subtle.ConstantTimeCompare(derived, parsed.key) == 1, nil
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !(darwin || linux)
package server
import "os"
func ownedByCurrentUser(os.FileInfo) bool { return true }
+13
View File
@@ -0,0 +1,13 @@
//go:build darwin || linux
package server
import (
"os"
"syscall"
)
func ownedByCurrentUser(info os.FileInfo) bool {
stat, ok := info.Sys().(*syscall.Stat_t)
return ok && int(stat.Uid) == os.Getuid()
}
+112
View File
@@ -0,0 +1,112 @@
package server
import (
"crypto/pbkdf2"
"crypto/sha256"
"encoding/binary"
"errors"
"math/bits"
)
// scryptKey derives an RFC 7914 scrypt key. It is the same function Node's
// crypto.scrypt and Python's hashlib.scrypt compute, so the web proxy, the
// ./password script and this server verify one stored hash. The standard
// library has PBKDF2 but no scrypt, and this small implementation avoids a
// new module dependency.
func scryptKey(password, salt []byte, n, r, p, keyLen int) ([]byte, error) {
if n <= 1 || n&(n-1) != 0 {
return nil, errors.New("scrypt: N must be a power of two greater than 1")
}
if r <= 0 || p <= 0 || keyLen <= 0 || r*p >= 1<<30 || r > (1<<31-1)/128/p || n > (1<<31-1)/128/r {
return nil, errors.New("scrypt: parameters out of range")
}
b, err := pbkdf2.Key(sha256.New, string(password), salt, 1, p*128*r)
if err != nil {
return nil, err
}
xy := make([]uint32, 64*r)
v := make([]uint32, 32*n*r)
for i := 0; i < p; i++ {
scryptROMix(b[i*128*r:], r, n, v, xy)
}
return pbkdf2.Key(sha256.New, string(password), b, 1, keyLen)
}
func scryptROMix(b []byte, r, n int, v, xy []uint32) {
words := 32 * r
x, y := xy[:words], xy[words:]
for i := range x {
x[i] = binary.LittleEndian.Uint32(b[i*4:])
}
for i := 0; i < n; i++ {
copy(v[i*words:], x)
scryptBlockMix(x, y, r)
}
for i := 0; i < n; i++ {
j := int(x[(2*r-1)*16] & uint32(n-1))
for k := range x {
x[k] ^= v[j*words+k]
}
scryptBlockMix(x, y, r)
}
for i := range x {
binary.LittleEndian.PutUint32(b[i*4:], x[i])
}
}
// scryptBlockMix computes BlockMix_salsa20/8 of b in place, using y as scratch.
func scryptBlockMix(b, y []uint32, r int) {
var x [16]uint32
copy(x[:], b[(2*r-1)*16:])
for i := 0; i < 2*r; i++ {
for k := range x {
x[k] ^= b[i*16+k]
}
salsa208(&x)
// Even blocks go to the first half of the output, odd to the second.
copy(y[(i/2+(i%2)*r)*16:], x[:])
}
copy(b, y[:32*r])
}
func salsa208(b *[16]uint32) {
x := *b
rotl := bits.RotateLeft32
for i := 0; i < 8; i += 2 {
x[4] ^= rotl(x[0]+x[12], 7)
x[8] ^= rotl(x[4]+x[0], 9)
x[12] ^= rotl(x[8]+x[4], 13)
x[0] ^= rotl(x[12]+x[8], 18)
x[9] ^= rotl(x[5]+x[1], 7)
x[13] ^= rotl(x[9]+x[5], 9)
x[1] ^= rotl(x[13]+x[9], 13)
x[5] ^= rotl(x[1]+x[13], 18)
x[14] ^= rotl(x[10]+x[6], 7)
x[2] ^= rotl(x[14]+x[10], 9)
x[6] ^= rotl(x[2]+x[14], 13)
x[10] ^= rotl(x[6]+x[2], 18)
x[3] ^= rotl(x[15]+x[11], 7)
x[7] ^= rotl(x[3]+x[15], 9)
x[11] ^= rotl(x[7]+x[3], 13)
x[15] ^= rotl(x[11]+x[7], 18)
x[1] ^= rotl(x[0]+x[3], 7)
x[2] ^= rotl(x[1]+x[0], 9)
x[3] ^= rotl(x[2]+x[1], 13)
x[0] ^= rotl(x[3]+x[2], 18)
x[6] ^= rotl(x[5]+x[4], 7)
x[7] ^= rotl(x[6]+x[5], 9)
x[4] ^= rotl(x[7]+x[6], 13)
x[5] ^= rotl(x[4]+x[7], 18)
x[11] ^= rotl(x[10]+x[9], 7)
x[8] ^= rotl(x[11]+x[10], 9)
x[9] ^= rotl(x[8]+x[11], 13)
x[10] ^= rotl(x[9]+x[8], 18)
x[12] ^= rotl(x[15]+x[14], 7)
x[13] ^= rotl(x[12]+x[15], 9)
x[14] ^= rotl(x[13]+x[12], 13)
x[15] ^= rotl(x[14]+x[13], 18)
}
for i := range b {
b[i] += x[i]
}
}
+47
View File
@@ -0,0 +1,47 @@
package server
import (
"encoding/hex"
"testing"
)
// RFC 7914 section 12 test vectors (the 1 GiB N=1048576 vector is omitted).
func TestScryptKeyMatchesRFC7914(t *testing.T) {
cases := []struct {
password, salt string
n, r, p int
want string
}{
{"", "", 16, 1, 1, "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906"},
{"password", "NaCl", 1024, 8, 16, "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640"},
{"pleaseletmein", "SodiumChloride", 16384, 8, 1, "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887"},
}
for _, c := range cases {
got, err := scryptKey([]byte(c.password), []byte(c.salt), c.n, c.r, c.p, 64)
if err != nil {
t.Fatal(err)
}
if hex.EncodeToString(got) != c.want {
t.Fatalf("scrypt(%q,%q,%d,%d,%d) = %x", c.password, c.salt, c.n, c.r, c.p, got)
}
}
if _, err := scryptKey([]byte("x"), nil, 1000, 8, 1, 32); err == nil {
t.Fatal("non power-of-two N accepted")
}
}
// Hashes written by web/src/authStore.js (Node) and scripts/password.py.
func TestWebAuthVerifiesNodeAndPythonHashes(t *testing.T) {
for _, hash := range []string{
"scrypt$1024$8$1$MR3k3NXe_hsd4UA6ipwLCQ$4sbSBzIXD8kVwJxwdg85f7wSvF6yzn3E0V480Z2ktG8",
"scrypt$1024$8$1$ulLLNZltxuQsW2fYURfjkw$8LptNPQf8ABG7GBih5ZH924wfqf1eDnZOhhdVIA7z2U",
} {
verifier := webAuthVerifier{hash: hash}
if ok, err := verifier.verify("tulip orbit canyon ember"); !ok || err != nil {
t.Fatalf("%s: %v %v", hash, ok, err)
}
if ok, _ := verifier.verify("tulip orbit canyon embers"); ok {
t.Fatalf("%s accepted a wrong password", hash)
}
}
}
+11 -1
View File
@@ -72,6 +72,11 @@ type Options struct {
// them so they never share the real server's tmux sessions.
TerminalTmuxSocket string
TerminalWithoutTmux bool
// 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).
WebAuthFile string
ElevationTTL time.Duration
}
// Handler serves the persistent connection with default options. Canceling ctx
@@ -188,7 +193,8 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
mux.HandleFunc("GET /discovery", serveServerDiscovery)
mux.HandleFunc("GET /files", serveHomeFile)
mux.HandleFunc("POST /files", serveHomeFileUpload)
elevation := newElevationGate(options.WebAuthFile, options.ElevationTTL)
mux.HandleFunc("POST /files", elevation.requireElevationHTTP(serveHomeFileUpload))
mux.HandleFunc("POST /chat-uploads", serveChatUpload)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
@@ -233,6 +239,7 @@ 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)
// 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)
@@ -283,6 +290,9 @@ 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) {
continue
}
if isChatSearch(request) {
cancelChatSearch()
searchCtx, cancel := context.WithCancel(connCtx)