diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..c701417 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,44 @@ +# Dependabot version updates for the sftp module. +version: 2 +updates: + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "03:00" + commit-message: + prefix: "chore(deps)" + include: "scope" + open-pull-requests-limit: 5 + groups: + sftp-minor-patch: + update-types: ["minor", "patch"] + + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "03:00" + commit-message: + prefix: "chore(deps)" + include: "scope" + open-pull-requests-limit: 5 + groups: + sftp-docker-minor-patch: + update-types: ["minor", "patch"] + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "03:00" + commit-message: + prefix: "chore(deps)" + include: "scope" + open-pull-requests-limit: 5 + groups: + actions-minor-patch: + update-types: ["minor", "patch"] diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..8811ad2 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,26 @@ +# CI: the shared Gameplane workflow for split components (lint with Gameplane's +# .golangci.yml and .hadolint.yaml, race tests on amd64 and arm64 with the +# .testcoverage.yml gate, govulncheck, image build). Pinned by SHA. +name: ci + +on: + pull_request: + push: + branches: [main] + schedule: + - cron: "17 4 * * 1" # weekly, so govulncheck sees new advisories + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + ci: + uses: GameplanePanel/Gameplane/.github/workflows/go-component.yaml@783aefb67b0744eaf8d0ee51cb10d94ae9739fd6 # master + with: + # This repo is the sftp/ submodule in Gameplane; the Dockerfile copies sftp/... + path: sftp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2bedb6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/sftp +coverage/ diff --git a/.testcoverage.yml b/.testcoverage.yml new file mode 100644 index 0000000..15079d0 --- /dev/null +++ b/.testcoverage.yml @@ -0,0 +1,11 @@ +# Coverage threshold gate for the sftp module. +# Enforced in CI by Gameplane's shared go-component.yaml workflow (go-test-coverage/v2). +# The scaffold only has run(); main() is process wiring. Ratchet up as the +# SSH server, API client and virtual file system land (spec 040 T020-T029). +profile: coverage/unit.out +github-action-output: false + +threshold: + file: 0 + package: 0 + total: 70 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..9d2eac0 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,22 @@ +# sftp — AI assistant guide + +This repository holds the optional SFTP endpoint for game server files (spec 040 in Gameplane). It is a split component of [GameplanePanel/Gameplane](https://github.com/GameplanePanel/Gameplane), checked out there as the `sftp/` submodule. It never reads game volumes itself: every login and file operation goes to the Gameplane API as the signed-in user. What it does and its contracts: [`specs.md`](specs.md). + +## How it fits into Gameplane + +- **Own Go module**, not part of Gameplane's `go.work`. Build and test from this repository's root: `go build ./...` (inside a Gameplane checkout, prefix `GOWORK=off`). +- **CI** is `.github/workflows/ci.yaml`, a thin caller of Gameplane's shared [`go-component.yaml`](https://github.com/GameplanePanel/Gameplane/blob/master/.github/workflows/go-component.yaml), pinned by SHA: lint with Gameplane's root `.golangci.yml` and `.hadolint.yaml` (no copy here), race tests on amd64 and arm64 with the `.testcoverage.yml` gate, govulncheck, and an image build. Dependabot runs in this repository. +- **Images** `sftp` (`Dockerfile`, built by `make image-sftp`) are built and published from the Gameplane repository root: the Dockerfiles copy `sftp/...` from that build context. +- **Callers live in Gameplane:** paths such as `operator/`, `api/`, `charts/`, `docs/` and `web/` in `specs.md` and code comments refer to that repository. +- **Shipping a change:** PR to `main` here → after it merges, bump the `sftp` pointer in Gameplane (`git -C sftp checkout `, `git add sftp`) in a Gameplane PR. A user-visible change gets its `changelog/unreleased/` entry in that Gameplane PR. + +## Rules + +Gameplane's [`AGENTS.md`](https://github.com/GameplanePanel/Gameplane/blob/master/AGENTS.md) core rules apply here. The ones that matter most in this repository: + +- **CI verifies:** locally only compile checks (`go build ./...`); never run test or lint suites locally. +- **Fix, don't silence:** no `//nolint` and no per-repository `.golangci.yml`; `_test.go` files are exempt from `errcheck`/`gosec`/`unparam` through the shared config. +- **Go errors:** wrap with `%w`. +- **Tests:** never delete or weaken a test without the maintainer's explicit sign-off; fix the code. +- **Git:** signed commits (`git commit -s`), conventional prefixes (`feat:`, `fix:`, `chore:`, `docs:` …), one branch per unit of work, never amend pushed commits; delete the branch after merge. +- **Docs:** keep `specs.md` in step with behaviour changes in the same PR. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..9d2eac0 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,22 @@ +# sftp — AI assistant guide + +This repository holds the optional SFTP endpoint for game server files (spec 040 in Gameplane). It is a split component of [GameplanePanel/Gameplane](https://github.com/GameplanePanel/Gameplane), checked out there as the `sftp/` submodule. It never reads game volumes itself: every login and file operation goes to the Gameplane API as the signed-in user. What it does and its contracts: [`specs.md`](specs.md). + +## How it fits into Gameplane + +- **Own Go module**, not part of Gameplane's `go.work`. Build and test from this repository's root: `go build ./...` (inside a Gameplane checkout, prefix `GOWORK=off`). +- **CI** is `.github/workflows/ci.yaml`, a thin caller of Gameplane's shared [`go-component.yaml`](https://github.com/GameplanePanel/Gameplane/blob/master/.github/workflows/go-component.yaml), pinned by SHA: lint with Gameplane's root `.golangci.yml` and `.hadolint.yaml` (no copy here), race tests on amd64 and arm64 with the `.testcoverage.yml` gate, govulncheck, and an image build. Dependabot runs in this repository. +- **Images** `sftp` (`Dockerfile`, built by `make image-sftp`) are built and published from the Gameplane repository root: the Dockerfiles copy `sftp/...` from that build context. +- **Callers live in Gameplane:** paths such as `operator/`, `api/`, `charts/`, `docs/` and `web/` in `specs.md` and code comments refer to that repository. +- **Shipping a change:** PR to `main` here → after it merges, bump the `sftp` pointer in Gameplane (`git -C sftp checkout `, `git add sftp`) in a Gameplane PR. A user-visible change gets its `changelog/unreleased/` entry in that Gameplane PR. + +## Rules + +Gameplane's [`AGENTS.md`](https://github.com/GameplanePanel/Gameplane/blob/master/AGENTS.md) core rules apply here. The ones that matter most in this repository: + +- **CI verifies:** locally only compile checks (`go build ./...`); never run test or lint suites locally. +- **Fix, don't silence:** no `//nolint` and no per-repository `.golangci.yml`; `_test.go` files are exempt from `errcheck`/`gosec`/`unparam` through the shared config. +- **Go errors:** wrap with `%w`. +- **Tests:** never delete or weaken a test without the maintainer's explicit sign-off; fix the code. +- **Git:** signed commits (`git commit -s`), conventional prefixes (`feat:`, `fix:`, `chore:`, `docs:` …), one branch per unit of work, never amend pushed commits; delete the branch after merge. +- **Docs:** keep `specs.md` in step with behaviour changes in the same PR. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..90ed54d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS build +WORKDIR /src + +COPY sftp/go.mod sftp/go.sum* ./sftp/ +WORKDIR /src/sftp +RUN go mod download + +WORKDIR /src +COPY sftp/ ./sftp/ +WORKDIR /src/sftp + +ARG VERSION=dev +# Cross-compile on the build host ($BUILDPLATFORM above) rather than under +# QEMU emulation: multi-arch release builds of the arm64 image were slow +# enough to hit the release job timeout. +ARG TARGETARCH +RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ + -trimpath \ + -ldflags="-s -w -X main.Version=${VERSION}" \ + -o /out/sftp . + +FROM gcr.io/distroless/static:nonroot +WORKDIR / +COPY --from=build /out/sftp /sftp +USER 65532:65532 +# SFTP listens on 2222 by default (Helm sftp.port); the Service maps it. +EXPOSE 2222 +ENTRYPOINT ["/sftp"] diff --git a/README.md b/README.md index 2c99c58..f2274aa 100644 --- a/README.md +++ b/README.md @@ -1 +1,24 @@ # sftp + +> This repository is checked out as the `sftp/` submodule of [GameplanePanel/Gameplane](https://github.com/GameplanePanel/Gameplane). Paths such as `docs/`, `operator/`, `api/`, `charts/` and `web/` below refer to that repository. + +The **sftp** component [optional] is Gameplane's SFTP endpoint for game server files. Each cluster can run one. A user connects with any SFTP client (FileZilla, WinSCP, `sftp`) using an SSH key or a generated SFTP password from their Gameplane profile, and sees one folder per game server they may access. Logging in as `+` opens one server directly. + +The server holds no permissions and mounts no volumes: every login and file operation is sent to the Gameplane API as that user, so roles, ownership, per-cluster grants and the audit log apply exactly as in the dashboard Files tab. + +Status: the server runs (`sftp serve`). The design is spec 040 (`specs/040-sftp-access/` in Gameplane). + +## Running + +```sh +sftp serve \ + --host-key /etc/sftp/hostkeys \ + --api-url https://gameplane-api.gameplane.svc:8080 \ + --service-token-file /etc/sftp/service-token +``` + +Every flag has a `GAMEPLANE_SFTP_*` environment variable; the flag wins. Required: `--host-key` (a key file or a directory of keys, kept stable so clients can verify it), `--api-url`, `--service-token-file`. Optional: `--listen` (`:2222`), `--ca-file`, `--idle-timeout` (`15m`), `--max-sessions-per-user` (`4`), `--max-preauth-connections` (`64`, connections still authenticating; more are closed at once), `--max-transfers-per-user` (`8`), `--default-namespace` (`gameplane-games`, must match the API), `--metrics-addr` (`:9102`, empty disables). `sftp version` prints the build version. The full contract is in [`specs.md`](specs.md). + +Clients log in as `` to see every server they may access, or as `+` (or `+/`) to open one server directly. There is no shell, command execution or port forwarding. Dotfiles are hidden. + +Gameplane builds and ships the image and the Helm chart (`sftp.enabled`). Lint, tests, coverage and govulncheck for this module run in this repository's own CI. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..69c8787 --- /dev/null +++ b/go.mod @@ -0,0 +1,22 @@ +module github.com/GameplanePanel/gameplane/sftp + +go 1.27.0 + +require ( + github.com/pkg/sftp v1.13.12 + github.com/prometheus/client_golang v1.25.0 + golang.org/x/crypto v0.59.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/kr/fs v0.1.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.72.0 // indirect + github.com/prometheus/procfs v0.22.0 // indirect + golang.org/x/sys v0.50.0 // indirect + google.golang.org/protobuf v1.36.12 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2717eba --- /dev/null +++ b/go.sum @@ -0,0 +1,40 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/pkg/sftp v1.13.12 h1:Myhzy/ZzLPnCtE2F2WtDHsgs8RfgMnH2gfbHuCJhkMU= +github.com/pkg/sftp v1.13.12/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4= +github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk= +github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= +github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go new file mode 100644 index 0000000..38b26ef --- /dev/null +++ b/internal/apiclient/client.go @@ -0,0 +1,719 @@ +// Package apiclient is the sftp service's only path to the Gameplane API. It +// logs SFTP users in, checks which session tokens are still valid, lists the +// servers a session may reach and performs file operations as that session. +// It never talks to game pods directly; the API owns authorisation and the +// agent round trip. +package apiclient + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +// Sentinel errors. Every failure from the API maps to exactly one of these +// through errors.Is; the wrapping *Error carries the HTTP status and body text. +var ( + ErrNotFound = errors.New("not found") + ErrPermission = errors.New("permission denied") + ErrExists = errors.New("already exists") + ErrNoSpace = errors.New("no space left") + ErrTooLarge = errors.New("file too large") + ErrUnauthorized = errors.New("unauthorized") + ErrBadRequest = errors.New("bad request") + ErrBadOffset = errors.New("bad offset") + ErrBusy = errors.New("busy: rate limited") + ErrUnavailable = errors.New("unavailable") + ErrFailure = errors.New("operation failed") +) + +const ( + defaultTimeout = 30 * time.Second + defaultUserAgent = "gameplane-sftp" + maxErrorBody = 1024 + maxMessageLen = 256 + maxCheckTokens = 500 + maxLoginBody = 1 << 20 + maxListBody = 64 << 20 +) + +// Error is a failed API call. Err is the sentinel for the failure class and +// Status is the HTTP status, or zero when no response was received. +type Error struct { + Status int + Op string + Msg string + Err error +} + +// Error implements error. +func (e *Error) Error() string { + var b strings.Builder + b.WriteString("apiclient: ") + b.WriteString(e.Op) + b.WriteString(": ") + if e.Err != nil { + b.WriteString(e.Err.Error()) + } else { + b.WriteString("error") + } + if e.Status != 0 { + fmt.Fprintf(&b, " (HTTP %d)", e.Status) + } + if e.Msg != "" { + b.WriteString(": ") + b.WriteString(e.Msg) + } + return b.String() +} + +// Unwrap returns the sentinel so errors.Is works on the failure class. +func (e *Error) Unwrap() error { return e.Err } + +// Config configures a Client. +type Config struct { + // BaseURL is the API origin, for example https://gameplane-api.gameplane.svc:8080. + // A trailing slash is trimmed. Only http and https are accepted. + BaseURL string + // ServiceToken is the contents of the service token file, trimmed. It is + // used only for Login and CheckSessions. + ServiceToken string + // CAFile is an optional PEM bundle appended to the system roots. + CAFile string + // Timeout bounds non-streaming calls. Zero means 30 seconds. Streaming + // calls (Download and Stream) are bounded by their context only. + Timeout time.Duration + // UserAgent is sent on every request. Empty means "gameplane-sftp". + UserAgent string +} + +// Client talks to the Gameplane API. It is safe for concurrent use. +type Client struct { + baseURL string + serviceToken string + userAgent string + hc *http.Client // bounded by Timeout + streamHC *http.Client // no overall timeout; context only +} + +// New builds a Client with a TLS 1.2+ transport. CAFile, when set, must hold +// at least one PEM certificate. +func New(cfg Config) (*Client, error) { + base, err := validateBaseURL(cfg.BaseURL) + if err != nil { + return nil, err + } + pool, err := loadCAPool(cfg.CAFile) + if err != nil { + return nil, err + } + tr := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{Timeout: defaultTimeout, KeepAlive: 30 * time.Second}).DialContext, + ForceAttemptHTTP2: true, + MaxIdleConns: 100, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: pool}, + } + timeout := cfg.Timeout + if timeout <= 0 { + timeout = defaultTimeout + } + hc := &http.Client{Transport: tr, Timeout: timeout} + stream := &http.Client{Transport: tr} + return newClient(base, cfg, hc, stream), nil +} + +// NewWithHTTPClient builds a Client that sends every request through hc. It +// is meant for tests; CAFile and Timeout in cfg are ignored because hc owns +// TLS and timeouts. +func NewWithHTTPClient(cfg Config, hc *http.Client) (*Client, error) { + base, err := validateBaseURL(cfg.BaseURL) + if err != nil { + return nil, err + } + if hc == nil { + return nil, errors.New("apiclient: nil http client") + } + return newClient(base, cfg, hc, hc), nil +} + +// LoadServiceToken reads the service token file and returns its trimmed +// contents. An empty file is an error. +func LoadServiceToken(path string) (string, error) { + data, err := readConfigFile(path) + if err != nil { + return "", fmt.Errorf("read service token: %w", err) + } + token := strings.TrimSpace(string(data)) + if token == "" { + return "", errors.New("service token file is empty") + } + return token, nil +} + +func newClient(base string, cfg Config, hc, stream *http.Client) *Client { + ua := cfg.UserAgent + if ua == "" { + ua = defaultUserAgent + } + return &Client{ + baseURL: base, + serviceToken: strings.TrimSpace(cfg.ServiceToken), + userAgent: ua, + hc: hc, + streamHC: stream, + } +} + +func validateBaseURL(raw string) (string, error) { + s := strings.TrimRight(strings.TrimSpace(raw), "/") + u, err := url.Parse(s) + if err != nil { + return "", fmt.Errorf("apiclient: parse base URL: %w", err) + } + if u.Scheme != "http" && u.Scheme != "https" { + return "", errors.New("apiclient: base URL must use http or https") + } + if u.Host == "" { + return "", errors.New("apiclient: base URL has no host") + } + return s, nil +} + +func loadCAPool(path string) (*x509.CertPool, error) { + if path == "" { + return nil, nil + } + data, err := readConfigFile(path) + if err != nil { + return nil, fmt.Errorf("apiclient: read CA file: %w", err) + } + pool, err := x509.SystemCertPool() + if err != nil || pool == nil { + pool = x509.NewCertPool() + } + if !pool.AppendCertsFromPEM(data) { + return nil, errors.New("apiclient: CA file contains no PEM certificates") + } + return pool, nil +} + +// readConfigFile reads an operator-supplied file (a mounted secret or config +// map). It goes through os.Root so the read stays inside the file's directory: +// a path cannot escape with ".." or a symlink that leaves that directory. +func readConfigFile(path string) ([]byte, error) { + dir, name := filepath.Split(path) + if dir == "" { + dir = "." + } + root, err := os.OpenRoot(dir) + if err != nil { + return nil, fmt.Errorf("open directory: %w", err) + } + defer func() { _ = root.Close() }() + data, err := root.ReadFile(name) + if err != nil { + return nil, fmt.Errorf("read file: %w", err) + } + return data, nil +} + +// LoginRequest is one SFTP login attempt. Exactly one of Password or PublicKey +// must be set; the API rejects anything else with a generic 401. +type LoginRequest struct { + // Username is the full SSH username, including any "+target" suffix. + Username string `json:"username"` + // Password is the plaintext password, when password auth is used. + Password string `json:"password,omitempty"` + // PublicKey is an authorized_keys line, when public-key auth is used. + PublicKey string `json:"publicKey,omitempty"` + // RemoteAddr is the client's address, for example "203.0.113.7:51234". + RemoteAddr string `json:"remoteAddr"` +} + +// Target names the server a session is bound to. +type Target struct { + Namespace string `json:"namespace"` + Server string `json:"server"` +} + +// Session is a successful login. +type Session struct { + Token string + ExpiresAt time.Time + User string + // Target is nil when the login did not name a server. + Target *Target +} + +type loginResponse struct { + SessionToken string `json:"sessionToken"` + ExpiresAt string `json:"expiresAt"` + User string `json:"user"` + Target *Target `json:"target"` +} + +// Login exchanges a login attempt for a session token. It uses the service +// token. A 401 maps to ErrUnauthorized and a 429 to ErrBusy. +func (c *Client) Login(ctx context.Context, r LoginRequest) (Session, error) { + if c.serviceToken == "" { + return Session{}, &Error{Op: "login", Msg: "service token not configured", Err: ErrUnauthorized} + } + var resp loginResponse + if err := c.callJSON(ctx, "login", http.MethodPost, "/sftp/v1/login", c.serviceToken, nil, r, &resp, maxLoginBody); err != nil { + return Session{}, err + } + if resp.SessionToken == "" { + return Session{}, &Error{Op: "login", Msg: "response has no session token", Err: ErrFailure} + } + expires, err := time.Parse(time.RFC3339, resp.ExpiresAt) + if err != nil { + return Session{}, &Error{Op: "login", Msg: "invalid expiresAt", Err: ErrFailure} + } + return Session{Token: resp.SessionToken, ExpiresAt: expires, User: resp.User, Target: resp.Target}, nil +} + +// CheckSessions returns the tokens the API no longer accepts. It sends at +// most 500 tokens per request and uses the service token. An empty input +// makes no request. +func (c *Client) CheckSessions(ctx context.Context, tokens []string) ([]string, error) { + var revoked []string + for start := 0; start < len(tokens); start += maxCheckTokens { + end := min(start+maxCheckTokens, len(tokens)) + in := struct { + SessionTokens []string `json:"sessionTokens"` + }{SessionTokens: tokens[start:end]} + var out struct { + Revoked []string `json:"revoked"` + } + if c.serviceToken == "" { + return nil, &Error{Op: "sessions check", Msg: "service token not configured", Err: ErrUnauthorized} + } + if err := c.callJSON(ctx, "sessions check", http.MethodPost, "/sftp/v1/sessions/check", c.serviceToken, nil, in, &out, maxListBody); err != nil { + return nil, err + } + revoked = append(revoked, out.Revoked...) + } + return revoked, nil +} + +// EndSession asks the API to close one session, identified by its token. The +// server calls it for a login it created but will not use, so the session does +// not stay open until it expires. It uses the service token. +func (c *Client) EndSession(ctx context.Context, token string) error { + if token == "" { + return &Error{Op: "sessions end", Msg: "no session token", Err: ErrBadRequest} + } + if c.serviceToken == "" { + return &Error{Op: "sessions end", Msg: "service token not configured", Err: ErrUnauthorized} + } + in := struct { + SessionTokens []string `json:"sessionTokens"` + }{SessionTokens: []string{token}} + return c.exec(ctx, "sessions end", http.MethodPost, "/sftp/v1/sessions/end", c.serviceToken, nil, in) +} + +// ServerRef is one server a session may reach. +type ServerRef struct { + Namespace string `json:"namespace"` + Server string `json:"server"` +} + +// Servers lists the servers the session may reach. +func (c *Client) Servers(ctx context.Context, sessionToken string) ([]ServerRef, error) { + if sessionToken == "" { + return nil, &Error{Op: "servers", Msg: "no session token", Err: ErrUnauthorized} + } + var out struct { + Items []ServerRef `json:"items"` + } + if err := c.callJSON(ctx, "servers", http.MethodGet, "/sftp/v1/servers", sessionToken, nil, nil, &out, maxListBody); err != nil { + return nil, err + } + return out.Items, nil +} + +// Entry is one file or directory reported by the agent. +type Entry struct { + Name string + Path string + Size int64 + Mode string // os.FileMode.String() form, for example "drwxr-xr-x" + Dir bool + ModTime time.Time // zero when the API sent an unparseable time +} + +// UnmarshalJSON decodes an Entry and tolerates a bad modTime. +func (e *Entry) UnmarshalJSON(b []byte) error { + var raw struct { + Name string `json:"name"` + Path string `json:"path"` + Size int64 `json:"size"` + Mode string `json:"mode"` + Dir bool `json:"dir"` + ModTime string `json:"modTime"` + } + if err := json.Unmarshal(b, &raw); err != nil { + return err + } + e.Name = raw.Name + e.Path = raw.Path + e.Size = raw.Size + e.Mode = raw.Mode + e.Dir = raw.Dir + e.ModTime = time.Time{} + if t, err := time.Parse(time.RFC3339, raw.ModTime); err == nil { + e.ModTime = t + } + return nil +} + +// permBits maps the nine rwx characters of a FileMode string, in order, to +// their permission bits. +var permBits = [9]os.FileMode{0o400, 0o200, 0o100, 0o040, 0o020, 0o010, 0o004, 0o002, 0o001} + +// FileMode converts the Mode string back to an os.FileMode. Unknown type +// characters are ignored. +func (e Entry) FileMode() os.FileMode { + var mode os.FileMode + s := e.Mode + if len(s) > 0 { + switch s[0] { + case 'd': + mode |= os.ModeDir + case 'L': + mode |= os.ModeSymlink + case 'p': + mode |= os.ModeNamedPipe + case 'S': + mode |= os.ModeSocket + case 'D': + mode |= os.ModeDevice + case 'c': + mode |= os.ModeCharDevice + case 'u': + mode |= os.ModeSetuid + case 'g': + mode |= os.ModeSetgid + case 't': + mode |= os.ModeSticky + } + } + if len(s) >= 10 { + for i, bit := range permBits { + if s[i+1] != '-' { + mode |= bit + } + } + } + return mode +} + +// Files performs file operations for one session on one server. The zero +// namespace means the API's default namespace. +type Files struct { + c *Client + token string + namespace string + server string +} + +// Files returns a file API bound to a session token, namespace and server. +func (c *Client) Files(token, namespace, server string) *Files { + return &Files{c: c, token: token, namespace: namespace, server: server} +} + +func (f *Files) endpoint(op string) string { + return "/servers/" + url.PathEscape(f.server) + "/files/" + op +} + +// query adds the namespace, when set, to q and returns it. +func (f *Files) query(q url.Values) url.Values { + if q == nil { + q = url.Values{} + } + if f.namespace != "" { + q.Set("namespace", f.namespace) + } + return q +} + +// List returns the entries of a directory. +func (f *Files) List(ctx context.Context, path string) ([]Entry, error) { + var out []Entry + q := f.query(url.Values{"path": {path}}) + if err := f.c.callJSON(ctx, "list", http.MethodGet, f.endpoint("list"), f.token, q, nil, &out, maxListBody); err != nil { + return nil, err + } + return out, nil +} + +// Stat returns one entry. A missing path maps to ErrNotFound. +func (f *Files) Stat(ctx context.Context, path string) (Entry, error) { + var out Entry + q := f.query(url.Values{"path": {path}}) + if err := f.c.callJSON(ctx, "stat", http.MethodGet, f.endpoint("stat"), f.token, q, nil, &out, maxListBody); err != nil { + return Entry{}, err + } + return out, nil +} + +// Download returns the file body from offset onward. The caller closes it. +// An offset at or past the end maps to ErrBadOffset. A server that ignores +// the Range header is handled by discarding the first offset bytes. +func (f *Files) Download(ctx context.Context, path string, offset int64) (io.ReadCloser, error) { + if offset < 0 { + return nil, &Error{Op: "download", Msg: "negative offset", Err: ErrBadOffset} + } + h := http.Header{} + if offset > 0 { + h.Set("Range", "bytes="+strconv.FormatInt(offset, 10)+"-") + } + resp, err := f.c.send(ctx, call{ + op: "download", + method: http.MethodGet, + endpoint: f.endpoint("download"), + token: f.token, + query: f.query(url.Values{"path": {path}}), + header: h, + hc: f.c.streamHC, + length: -1, + }) + if err != nil { + return nil, err + } + if offset > 0 && resp.StatusCode == http.StatusOK { + if _, err := io.CopyN(io.Discard, resp.Body, offset); err != nil { + _ = resp.Body.Close() + return nil, &Error{Op: "download", Status: resp.StatusCode, Msg: "body shorter than offset", Err: ErrFailure} + } + } + return resp.Body, nil +} + +// plainReader hides any Len or Seek method so net/http does not infer a +// content length from the body. Stream sets the length explicitly. +type plainReader struct{ r io.Reader } + +func (p plainReader) Read(b []byte) (int, error) { return p.r.Read(b) } + +// Stream replaces the file from offset onward with body. offset 0 creates or +// replaces the file. A negative contentLength means the length is unknown and +// the body is sent chunked. +func (f *Files) Stream(ctx context.Context, path string, offset int64, body io.Reader, contentLength int64) error { + if offset < 0 { + return &Error{Op: "stream", Msg: "negative offset", Err: ErrBadOffset} + } + length := int64(-1) + if contentLength >= 0 { + length = contentLength + } + q := f.query(url.Values{"path": {path}, "offset": {strconv.FormatInt(offset, 10)}}) + resp, err := f.c.send(ctx, call{ + op: "stream", + method: http.MethodPut, + endpoint: f.endpoint("stream"), + token: f.token, + query: q, + body: plainReader{r: body}, + length: length, + contentType: "application/octet-stream", + hc: f.c.streamHC, + }) + if err != nil { + return err + } + return drainClose(resp) +} + +// Rename moves from to to. overwrite replaces an existing target; without it +// an existing target maps to ErrExists. +func (f *Files) Rename(ctx context.Context, from, to string, overwrite bool) error { + in := struct { + From string `json:"from"` + To string `json:"to"` + Overwrite bool `json:"overwrite"` + }{From: from, To: to, Overwrite: overwrite} + return f.c.exec(ctx, "rename", http.MethodPost, f.endpoint("rename"), f.token, f.query(nil), in) +} + +// Mkdir creates a directory and its parents. An existing directory is not an +// error. +func (f *Files) Mkdir(ctx context.Context, path string) error { + return f.c.exec(ctx, "mkdir", http.MethodPost, f.endpoint("mkdir"), f.token, f.query(url.Values{"path": {path}}), nil) +} + +// Delete removes one file or an empty directory. It never recurses. +func (f *Files) Delete(ctx context.Context, path string) error { + return f.c.exec(ctx, "delete", http.MethodDelete, f.endpoint("delete"), f.token, f.query(url.Values{"path": {path}}), nil) +} + +// call describes one HTTP request. +type call struct { + op string + method string + endpoint string + token string + query url.Values + header http.Header + body io.Reader + length int64 // with a body: exact length, or -1 for chunked + contentType string + hc *http.Client +} + +// send performs the request. It returns the response only for a 2xx status; +// any other status becomes an *Error and the body is consumed. +func (c *Client) send(ctx context.Context, cl call) (*http.Response, error) { + u := c.baseURL + cl.endpoint + if len(cl.query) > 0 { + u += "?" + cl.query.Encode() + } + req, err := http.NewRequestWithContext(ctx, cl.method, u, cl.body) + if err != nil { + return nil, fmt.Errorf("apiclient: %s: build request: %w", cl.op, err) + } + if cl.body != nil { + req.ContentLength = cl.length + } + req.Header.Set("User-Agent", c.userAgent) + if cl.token != "" { + req.Header.Set("Authorization", "Bearer "+cl.token) + } + if cl.contentType != "" { + req.Header.Set("Content-Type", cl.contentType) + } + for k, vs := range cl.header { + for _, v := range vs { + req.Header.Add(k, v) + } + } + resp, err := cl.hc.Do(req) + if err != nil { + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, fmt.Errorf("apiclient: %s: %w", cl.op, ctxErr) + } + return nil, &Error{Op: cl.op, Msg: err.Error(), Err: ErrUnavailable} + } + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return resp, nil + } + snippet, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody)) + _ = resp.Body.Close() + return nil, &Error{ + Status: resp.StatusCode, + Op: cl.op, + Msg: trimMessage(snippet), + Err: statusSentinel(resp.StatusCode), + } +} + +// callJSON sends a request, optionally with a JSON body, and decodes a JSON +// response into out when out is not nil. +func (c *Client) callJSON(ctx context.Context, op, method, endpoint, token string, q url.Values, in, out any, limit int64) error { + var body io.Reader + length := int64(-1) + contentType := "" + if in != nil { + b, err := json.Marshal(in) + if err != nil { + return fmt.Errorf("apiclient: %s: encode request: %w", op, err) + } + body = bytes.NewReader(b) + length = int64(len(b)) + contentType = "application/json" + } + resp, err := c.send(ctx, call{ + op: op, + method: method, + endpoint: endpoint, + token: token, + query: q, + body: body, + length: length, + contentType: contentType, + hc: c.hc, + }) + if err != nil { + return err + } + if out == nil { + return drainClose(resp) + } + defer func() { _ = resp.Body.Close() }() + if err := json.NewDecoder(io.LimitReader(resp.Body, limit)).Decode(out); err != nil { + return &Error{Op: op, Status: resp.StatusCode, Msg: "invalid response body", Err: ErrFailure} + } + return nil +} + +// exec sends a request whose response body is not used. +func (c *Client) exec(ctx context.Context, op, method, endpoint, token string, q url.Values, in any) error { + if in == nil { + resp, err := c.send(ctx, call{op: op, method: method, endpoint: endpoint, token: token, query: q, hc: c.hc}) + if err != nil { + return err + } + return drainClose(resp) + } + return c.callJSON(ctx, op, method, endpoint, token, q, in, nil, 0) +} + +// drainClose discards a small part of the body and closes it so the +// connection can be reused. +func drainClose(resp *http.Response) error { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxErrorBody)) + return resp.Body.Close() +} + +// statusSentinel maps a non-2xx HTTP status to its failure class. +func statusSentinel(code int) error { + switch code { + case http.StatusBadRequest: + return ErrBadRequest + case http.StatusUnauthorized: + return ErrUnauthorized + case http.StatusForbidden: + return ErrPermission + case http.StatusNotFound: + return ErrNotFound + case http.StatusConflict: + return ErrExists + case http.StatusRequestEntityTooLarge: + return ErrTooLarge + case http.StatusRequestedRangeNotSatisfiable: + return ErrBadOffset + case http.StatusTooManyRequests: + return ErrBusy + case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + return ErrUnavailable + case http.StatusInsufficientStorage: + return ErrNoSpace + default: + return ErrFailure + } +} + +// trimMessage returns the body as a short, valid UTF-8 message. +func trimMessage(b []byte) string { + s := strings.TrimSpace(string(b)) + if len(s) > maxMessageLen { + s = s[:maxMessageLen] + } + return strings.ToValidUTF8(s, "") +} diff --git a/internal/apiclient/client_test.go b/internal/apiclient/client_test.go new file mode 100644 index 0000000..c0ca432 --- /dev/null +++ b/internal/apiclient/client_test.go @@ -0,0 +1,740 @@ +package apiclient + +import ( + "context" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +const testServiceToken = "gpsftps_test" + +// newTestClient returns a Client whose API is the plain-HTTP server h. +func newTestClient(t *testing.T, h http.HandlerFunc) *Client { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + c, err := NewWithHTTPClient(Config{BaseURL: srv.URL, ServiceToken: testServiceToken}, srv.Client()) + if err != nil { + t.Fatalf("NewWithHTTPClient: %v", err) + } + return c +} + +func assertBearer(t *testing.T, r *http.Request, want string) { + t.Helper() + if got := r.Header.Get("Authorization"); got != "Bearer "+want { + t.Errorf("Authorization = %q, want Bearer %s", got, want) + } +} + +// assertCommon checks what every request must look like: no cluster query +// parameter (the API derives it from the token) and no problem+json Accept. +func assertCommon(t *testing.T, r *http.Request) { + t.Helper() + if _, ok := r.URL.Query()["cluster"]; ok { + t.Errorf("request sent a cluster query parameter: %s", r.URL.RawQuery) + } + if got := r.Header.Get("Accept"); strings.Contains(got, "problem+json") { + t.Errorf("request sent Accept %q", got) + } +} + +func TestLoginSendsOnlyOneCredential(t *testing.T) { + cases := []struct { + name string + req LoginRequest + wantKey string + absentKey string + resp string + wantTarget *Target + }{ + { + name: "password", + req: LoginRequest{Username: "alice+mods/survival", Password: "s3cret", RemoteAddr: "203.0.113.7:51234"}, + wantKey: "password", + absentKey: "publicKey", + resp: `{"sessionToken":"gpsftp_abc","expiresAt":"2026-11-23T10:15:00Z","user":"alice","target":{"namespace":"mods","server":"survival"}}`, + wantTarget: &Target{Namespace: "mods", Server: "survival"}, + }, + { + name: "public key", + req: LoginRequest{Username: "alice", PublicKey: "ssh-ed25519 AAAA", RemoteAddr: "203.0.113.7:51234"}, + wantKey: "publicKey", + absentKey: "password", + resp: `{"sessionToken":"gpsftp_def","expiresAt":"2026-11-23T10:15:00Z","user":"alice","target":null}`, + wantTarget: nil, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/sftp/v1/login" { + t.Errorf("got %s %s, want POST /sftp/v1/login", r.Method, r.URL.Path) + } + assertBearer(t, r, testServiceToken) + assertCommon(t, r) + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode body: %v", err) + } + if _, ok := body[tc.wantKey]; !ok { + t.Errorf("body has no %q: %v", tc.wantKey, body) + } + if _, ok := body[tc.absentKey]; ok { + t.Errorf("body unexpectedly has %q: %v", tc.absentKey, body) + } + if body["remoteAddr"] != "203.0.113.7:51234" { + t.Errorf("remoteAddr = %v", body["remoteAddr"]) + } + if _, err := w.Write([]byte(tc.resp)); err != nil { + t.Errorf("write response: %v", err) + } + }) + sess, err := c.Login(context.Background(), tc.req) + if err != nil { + t.Fatalf("Login: %v", err) + } + if !strings.HasPrefix(sess.Token, "gpsftp_") { + t.Errorf("Token = %q", sess.Token) + } + if !sess.ExpiresAt.Equal(time.Date(2026, 11, 23, 10, 15, 0, 0, time.UTC)) { + t.Errorf("ExpiresAt = %v", sess.ExpiresAt) + } + if sess.User != "alice" { + t.Errorf("User = %q", sess.User) + } + switch { + case tc.wantTarget == nil && sess.Target != nil: + t.Errorf("Target = %+v, want nil", *sess.Target) + case tc.wantTarget != nil && (sess.Target == nil || *sess.Target != *tc.wantTarget): + t.Errorf("Target = %+v, want %+v", sess.Target, *tc.wantTarget) + } + }) + } +} + +func TestLoginErrorStatuses(t *testing.T) { + cases := []struct { + status int + want error + }{ + {http.StatusUnauthorized, ErrUnauthorized}, + {http.StatusTooManyRequests, ErrBusy}, + {http.StatusServiceUnavailable, ErrUnavailable}, + } + for _, tc := range cases { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "invalid credentials", tc.status) + }) + _, err := c.Login(context.Background(), LoginRequest{Username: "alice", Password: "x"}) + if !errors.Is(err, tc.want) { + t.Fatalf("status %d: err = %v, want %v", tc.status, err, tc.want) + } + var apiErr *Error + if !errors.As(err, &apiErr) || apiErr.Status != tc.status { + t.Fatalf("status %d: err = %#v, want *Error with that status", tc.status, err) + } + } +} + +func TestLoginRejectsMissingServiceToken(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { + t.Error("no request expected without a service token") + })) + t.Cleanup(srv.Close) + c, err := NewWithHTTPClient(Config{BaseURL: srv.URL}, srv.Client()) + if err != nil { + t.Fatalf("NewWithHTTPClient: %v", err) + } + if _, err := c.Login(context.Background(), LoginRequest{Username: "alice", Password: "x"}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("Login err = %v, want ErrUnauthorized", err) + } +} + +func TestLoginRejectsBadResponse(t *testing.T) { + bodies := []string{ + `{"sessionToken":"gpsftp_x","expiresAt":"soon","user":"alice"}`, + `{"sessionToken":"","expiresAt":"2026-11-23T10:15:00Z","user":"alice"}`, + `not json`, + } + for _, body := range bodies { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + if _, err := w.Write([]byte(body)); err != nil { + t.Errorf("write: %v", err) + } + }) + if _, err := c.Login(context.Background(), LoginRequest{Username: "alice", Password: "x"}); !errors.Is(err, ErrFailure) { + t.Fatalf("body %q: err = %v, want ErrFailure", body, err) + } + } +} + +func TestCheckSessionsBatches(t *testing.T) { + tokens := make([]string, 600) + for i := range tokens { + tokens[i] = fmt.Sprintf("gpsftp_%03d", i) + } + var mu sync.Mutex + var sizes []int + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/sftp/v1/sessions/check" { + t.Errorf("path = %s", r.URL.Path) + } + assertBearer(t, r, testServiceToken) + assertCommon(t, r) + var in struct { + SessionTokens []string `json:"sessionTokens"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + t.Errorf("decode: %v", err) + } + mu.Lock() + sizes = append(sizes, len(in.SessionTokens)) + mu.Unlock() + // Report the first token of each batch as revoked. + if _, err := fmt.Fprintf(w, `{"revoked":[%q]}`, in.SessionTokens[0]); err != nil { + t.Errorf("write: %v", err) + } + }) + revoked, err := c.CheckSessions(context.Background(), tokens) + if err != nil { + t.Fatalf("CheckSessions: %v", err) + } + if len(sizes) != 2 || sizes[0] != 500 || sizes[1] != 100 { + t.Fatalf("batch sizes = %v, want [500 100]", sizes) + } + if len(revoked) != 2 || revoked[0] != "gpsftp_000" || revoked[1] != "gpsftp_500" { + t.Fatalf("revoked = %v", revoked) + } +} + +func TestCheckSessionsEmptyMakesNoRequest(t *testing.T) { + c := newTestClient(t, func(_ http.ResponseWriter, _ *http.Request) { + t.Error("no request expected for empty input") + }) + revoked, err := c.CheckSessions(context.Background(), nil) + if err != nil || len(revoked) != 0 { + t.Fatalf("CheckSessions(nil) = %v, %v", revoked, err) + } +} + +func TestServersDecodesItems(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != "/sftp/v1/servers" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + assertBearer(t, r, "gpsftp_s") + assertCommon(t, r) + if _, err := w.Write([]byte(`{"items":[{"namespace":"games","server":"survival"},{"namespace":"mods","server":"valheim"}]}`)); err != nil { + t.Errorf("write: %v", err) + } + }) + got, err := c.Servers(context.Background(), "gpsftp_s") + if err != nil { + t.Fatalf("Servers: %v", err) + } + want := []ServerRef{{Namespace: "games", Server: "survival"}, {Namespace: "mods", Server: "valheim"}} + if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("Servers = %+v, want %+v", got, want) + } + if _, err := c.Servers(context.Background(), ""); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("Servers with empty token: err = %v, want ErrUnauthorized", err) + } +} + +func TestEntryFileMode(t *testing.T) { + cases := []struct { + mode string + want os.FileMode + }{ + {"drwxr-xr-x", os.ModeDir | 0o755}, + {"-rw-r--r--", 0o644}, + {"Lrwxrwxrwx", os.ModeSymlink | 0o777}, + {"-rwxrwxrwx", 0o777}, + {"", 0}, + } + for _, tc := range cases { + if got := (Entry{Mode: tc.mode}).FileMode(); got != tc.want { + t.Errorf("FileMode(%q) = %v, want %v", tc.mode, got, tc.want) + } + } +} + +func TestListStatDecodeEntries(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + assertBearer(t, r, "gpsftp_tok") + assertCommon(t, r) + if r.URL.Query().Get("namespace") != "mods" { + t.Errorf("namespace = %q", r.URL.Query().Get("namespace")) + } + if r.URL.Query().Get("path") != "/" { + t.Errorf("path = %q", r.URL.Query().Get("path")) + } + switch r.URL.Path { + case "/servers/survival/files/list": + _, err := w.Write([]byte(`[ + {"name":"world","path":"/world","size":0,"mode":"drwxr-xr-x","dir":true,"modTime":"2026-11-23T10:00:00Z"}, + {"name":"server.properties","path":"/server.properties","size":123,"mode":"-rw-r--r--","dir":false,"modTime":"2026-11-23T10:00:00Z"}, + {"name":"link","path":"/link","size":0,"mode":"Lrwxrwxrwx","dir":false,"modTime":"not-a-time"} + ]`)) + if err != nil { + t.Errorf("write: %v", err) + } + case "/servers/survival/files/stat": + _, err := w.Write([]byte(`{"name":"","path":"/","size":0,"mode":"drwxr-xr-x","dir":true,"modTime":"2026-11-23T10:00:00Z"}`)) + if err != nil { + t.Errorf("write: %v", err) + } + default: + t.Errorf("unexpected path %s", r.URL.Path) + http.NotFound(w, r) + } + }) + f := c.Files("gpsftp_tok", "mods", "survival") + entries, err := f.List(context.Background(), "/") + if err != nil { + t.Fatalf("List: %v", err) + } + if len(entries) != 3 { + t.Fatalf("len(entries) = %d, want 3", len(entries)) + } + if entries[0].FileMode() != os.ModeDir|0o755 || !entries[0].Dir { + t.Errorf("dir entry mode = %v", entries[0].FileMode()) + } + if entries[1].FileMode() != 0o644 || entries[1].Size != 123 { + t.Errorf("file entry = %+v", entries[1]) + } + if !entries[1].ModTime.Equal(time.Date(2026, 11, 23, 10, 0, 0, 0, time.UTC)) { + t.Errorf("file ModTime = %v", entries[1].ModTime) + } + if entries[2].FileMode() != os.ModeSymlink|0o777 { + t.Errorf("symlink mode = %v", entries[2].FileMode()) + } + if !entries[2].ModTime.IsZero() { + t.Errorf("bad modTime should decode to zero, got %v", entries[2].ModTime) + } + + root, err := f.Stat(context.Background(), "/") + if err != nil { + t.Fatalf("Stat: %v", err) + } + if root.Path != "/" || root.Name != "" || !root.Dir { + t.Errorf("Stat(/) = %+v", root) + } +} + +func TestEntryUnmarshalRejectsBadJSON(t *testing.T) { + var e Entry + if err := json.Unmarshal([]byte(`{"name":1}`), &e); err == nil { + t.Fatal("expected decode error for wrong type") + } +} + +func TestDownloadOffsets(t *testing.T) { + cases := []struct { + name string + offset int64 + wantRange string + status int + serve string + want string + }{ + {"from start", 0, "", http.StatusOK, "hello world", "hello world"}, + {"range honoured", 5, "bytes=5-", http.StatusPartialContent, "world", "world"}, + {"range ignored", 5, "bytes=5-", http.StatusOK, "hello world", " world"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + assertBearer(t, r, "gpsftp_tok") + assertCommon(t, r) + if got := r.Header.Get("Range"); got != tc.wantRange { + t.Errorf("Range = %q, want %q", got, tc.wantRange) + } + if r.URL.Query().Get("path") != "/a.bin" { + t.Errorf("path = %q", r.URL.Query().Get("path")) + } + w.WriteHeader(tc.status) + if _, err := w.Write([]byte(tc.serve)); err != nil { + t.Errorf("write: %v", err) + } + }) + rc, err := c.Files("gpsftp_tok", "mods", "survival").Download(context.Background(), "/a.bin", tc.offset) + if err != nil { + t.Fatalf("Download: %v", err) + } + defer func() { _ = rc.Close() }() + got, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("read: %v", err) + } + if string(got) != tc.want { + t.Fatalf("body = %q, want %q", got, tc.want) + } + }) + } +} + +func TestDownloadErrors(t *testing.T) { + t.Run("short body", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + if _, err := w.Write([]byte("hello")); err != nil { + t.Errorf("write: %v", err) + } + }) + _, err := c.Files("gpsftp_tok", "", "survival").Download(context.Background(), "/a.bin", 50) + if !errors.Is(err, ErrFailure) { + t.Fatalf("err = %v, want ErrFailure", err) + } + }) + t.Run("range beyond end", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "range not satisfiable", http.StatusRequestedRangeNotSatisfiable) + }) + _, err := c.Files("gpsftp_tok", "", "survival").Download(context.Background(), "/a.bin", 99) + if !errors.Is(err, ErrBadOffset) { + t.Fatalf("err = %v, want ErrBadOffset", err) + } + }) + t.Run("negative offset makes no request", func(t *testing.T) { + c := newTestClient(t, func(_ http.ResponseWriter, _ *http.Request) { + t.Error("no request expected for a negative offset") + }) + _, err := c.Files("gpsftp_tok", "", "survival").Download(context.Background(), "/a.bin", -1) + if !errors.Is(err, ErrBadOffset) { + t.Fatalf("err = %v, want ErrBadOffset", err) + } + }) +} + +func TestStreamUnknownLengthIsChunked(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPut || r.URL.Path != "/servers/survival/files/stream" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + assertBearer(t, r, "gpsftp_tok") + assertCommon(t, r) + q := r.URL.Query() + if q.Get("path") != "/a/b" || q.Get("offset") != "0" || q.Get("namespace") != "mods" { + t.Errorf("query = %q", r.URL.RawQuery) + } + if r.ContentLength != -1 { + t.Errorf("ContentLength = %d, want -1 (chunked)", r.ContentLength) + } + if got := r.Header.Get("Content-Type"); got != "application/octet-stream" { + t.Errorf("Content-Type = %q", got) + } + body, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("read body: %v", err) + } + if string(body) != "payload" { + t.Errorf("body = %q", body) + } + w.WriteHeader(http.StatusNoContent) + }) + f := c.Files("gpsftp_tok", "mods", "survival") + if err := f.Stream(context.Background(), "/a/b", 0, strings.NewReader("payload"), -1); err != nil { + t.Fatalf("Stream: %v", err) + } +} + +func TestStreamKnownLengthAndOffset(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("offset") != "3" { + t.Errorf("offset = %q", r.URL.Query().Get("offset")) + } + if r.ContentLength != 7 { + t.Errorf("ContentLength = %d, want 7", r.ContentLength) + } + body, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("read body: %v", err) + } + if string(body) != "payload" { + t.Errorf("body = %q", body) + } + w.WriteHeader(http.StatusOK) + }) + err := c.Files("gpsftp_tok", "mods", "survival").Stream(context.Background(), "/a/b", 3, strings.NewReader("payload"), 7) + if err != nil { + t.Fatalf("Stream: %v", err) + } +} + +func TestStreamStatusMapping(t *testing.T) { + cases := []struct { + status int + want error + }{ + {http.StatusBadRequest, ErrBadRequest}, + {http.StatusUnauthorized, ErrUnauthorized}, + {http.StatusForbidden, ErrPermission}, + {http.StatusNotFound, ErrNotFound}, + {http.StatusConflict, ErrExists}, + {http.StatusRequestEntityTooLarge, ErrTooLarge}, + {http.StatusRequestedRangeNotSatisfiable, ErrBadOffset}, + {http.StatusTooManyRequests, ErrBusy}, + {http.StatusBadGateway, ErrUnavailable}, + {http.StatusServiceUnavailable, ErrUnavailable}, + {http.StatusGatewayTimeout, ErrUnavailable}, + {http.StatusInsufficientStorage, ErrNoSpace}, + {http.StatusInternalServerError, ErrFailure}, + {http.StatusTeapot, ErrFailure}, + } + for _, tc := range cases { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "nope", tc.status) + }) + err := c.Files("gpsftp_tok", "", "survival").Stream(context.Background(), "/a", 0, strings.NewReader("x"), -1) + if !errors.Is(err, tc.want) { + t.Fatalf("status %d: err = %v, want %v", tc.status, err, tc.want) + } + var apiErr *Error + if !errors.As(err, &apiErr) || apiErr.Status != tc.status || apiErr.Msg != "nope" { + t.Fatalf("status %d: err = %#v, want *Error{Status: %d, Msg: nope}", tc.status, err, tc.status) + } + } +} + +func TestRenameMkdirDelete(t *testing.T) { + t.Run("rename without overwrite", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/servers/survival/files/rename" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + assertBearer(t, r, "gpsftp_tok") + assertCommon(t, r) + if _, ok := r.URL.Query()["path"]; ok { + t.Errorf("rename must not send path: %s", r.URL.RawQuery) + } + var in map[string]any + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + t.Errorf("decode: %v", err) + } + if in["from"] != "/a" || in["to"] != "/b" || in["overwrite"] != false { + t.Errorf("body = %v", in) + } + w.WriteHeader(http.StatusNoContent) + }) + if err := c.Files("gpsftp_tok", "mods", "survival").Rename(context.Background(), "/a", "/b", false); err != nil { + t.Fatalf("Rename: %v", err) + } + }) + t.Run("rename with overwrite", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + var in map[string]any + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + t.Errorf("decode: %v", err) + } + if in["overwrite"] != true { + t.Errorf("overwrite = %v, want true", in["overwrite"]) + } + w.WriteHeader(http.StatusNoContent) + }) + if err := c.Files("gpsftp_tok", "", "survival").Rename(context.Background(), "/a", "/b", true); err != nil { + t.Fatalf("Rename: %v", err) + } + }) + t.Run("rename target exists", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "exists", http.StatusConflict) + }) + if err := c.Files("gpsftp_tok", "", "survival").Rename(context.Background(), "/a", "/b", false); !errors.Is(err, ErrExists) { + t.Fatalf("Rename err = %v, want ErrExists", err) + } + }) + t.Run("mkdir", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/servers/survival/files/mkdir" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + if r.URL.Query().Get("path") != "/new/dir" { + t.Errorf("path = %q", r.URL.Query().Get("path")) + } + w.WriteHeader(http.StatusNoContent) + }) + if err := c.Files("gpsftp_tok", "", "survival").Mkdir(context.Background(), "/new/dir"); err != nil { + t.Fatalf("Mkdir: %v", err) + } + }) + t.Run("delete is never recursive", func(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete || r.URL.Path != "/servers/survival/files/delete" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + if _, ok := r.URL.Query()["recursive"]; ok { + t.Errorf("delete sent recursive: %s", r.URL.RawQuery) + } + if r.URL.Query().Get("path") != "/x" { + t.Errorf("path = %q", r.URL.Query().Get("path")) + } + w.WriteHeader(http.StatusNoContent) + }) + if err := c.Files("gpsftp_tok", "", "survival").Delete(context.Background(), "/x"); err != nil { + t.Fatalf("Delete: %v", err) + } + }) +} + +func TestNewValidatesBaseURL(t *testing.T) { + for _, raw := range []string{"", "ftp://example.test", "https://", "://bad", "example.test:8080"} { + if _, err := New(Config{BaseURL: raw}); err == nil { + t.Errorf("New(%q) succeeded, want error", raw) + } + } + c, err := New(Config{BaseURL: " https://api.example.test/ "}) + if err != nil { + t.Fatalf("New: %v", err) + } + if c.baseURL != "https://api.example.test" { + t.Errorf("baseURL = %q", c.baseURL) + } + if c.hc.Timeout != defaultTimeout { + t.Errorf("default timeout = %v, want %v", c.hc.Timeout, defaultTimeout) + } + if c.streamHC.Timeout != 0 { + t.Errorf("stream client timeout = %v, want none", c.streamHC.Timeout) + } + if _, err := NewWithHTTPClient(Config{BaseURL: "https://api.example.test"}, nil); err == nil { + t.Error("NewWithHTTPClient with nil client succeeded") + } +} + +func TestNewCAFile(t *testing.T) { + dir := t.TempDir() + + badPEM := filepath.Join(dir, "bad.pem") + if err := os.WriteFile(badPEM, []byte("not a certificate\n"), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + if _, err := New(Config{BaseURL: "https://api.example.test", CAFile: badPEM}); err == nil { + t.Error("New with a PEM-free CA file succeeded") + } + if _, err := New(Config{BaseURL: "https://api.example.test", CAFile: filepath.Join(dir, "missing.pem")}); err == nil { + t.Error("New with a missing CA file succeeded") + } + + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if _, err := w.Write([]byte(`{"items":[]}`)); err != nil { + t.Errorf("write: %v", err) + } + })) + t.Cleanup(srv.Close) + + caPEM := filepath.Join(dir, "ca.pem") + if err := os.WriteFile(caPEM, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + + trusted, err := New(Config{BaseURL: srv.URL, CAFile: caPEM, ServiceToken: testServiceToken}) + if err != nil { + t.Fatalf("New with CA: %v", err) + } + if _, err := trusted.Servers(context.Background(), "gpsftp_x"); err != nil { + t.Fatalf("Servers over trusted TLS: %v", err) + } + + untrusted, err := New(Config{BaseURL: srv.URL, ServiceToken: testServiceToken}) + if err != nil { + t.Fatalf("New without CA: %v", err) + } + if _, err := untrusted.Servers(context.Background(), "gpsftp_x"); err == nil { + t.Error("Servers over an unknown certificate succeeded, want TLS failure") + } +} + +func TestLoadServiceToken(t *testing.T) { + dir := t.TempDir() + good := filepath.Join(dir, "token") + if err := os.WriteFile(good, []byte(" gpsftps_abc \n"), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + got, err := LoadServiceToken(good) + if err != nil || got != "gpsftps_abc" { + t.Fatalf("LoadServiceToken = %q, %v", got, err) + } + + empty := filepath.Join(dir, "empty") + if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + if _, err := LoadServiceToken(empty); err == nil { + t.Error("empty token file accepted") + } + if _, err := LoadServiceToken(filepath.Join(dir, "missing")); err == nil { + t.Error("missing token file accepted") + } +} + +func TestErrorMessage(t *testing.T) { + err := &Error{Status: http.StatusNotFound, Op: "stat", Msg: "no such file", Err: ErrNotFound} + msg := err.Error() + for _, want := range []string{"stat", "not found", "HTTP 404", "no such file"} { + if !strings.Contains(msg, want) { + t.Errorf("Error() = %q, missing %q", msg, want) + } + } + if !errors.Is(err, ErrNotFound) { + t.Error("errors.Is(ErrNotFound) = false") + } +} + +func TestTrimMessage(t *testing.T) { + if got := trimMessage([]byte(" hi \n")); got != "hi" { + t.Errorf("trimMessage = %q", got) + } + long := strings.Repeat("a", 1000) + if got := trimMessage([]byte(long)); len(got) != maxMessageLen { + t.Errorf("len = %d, want %d", len(got), maxMessageLen) + } + if got := trimMessage([]byte{0xff, 'o', 'k'}); got != "ok" { + t.Errorf("invalid UTF-8 not stripped: %q", got) + } +} + +func TestEndSessionSendsToken(t *testing.T) { + var got struct { + SessionTokens []string `json:"sessionTokens"` + } + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/sftp/v1/sessions/end" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + assertBearer(t, r, testServiceToken) + assertCommon(t, r) + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Errorf("decode: %v", err) + } + w.WriteHeader(http.StatusNoContent) + }) + if err := c.EndSession(context.Background(), "gpsftp_x"); err != nil { + t.Fatalf("EndSession: %v", err) + } + if len(got.SessionTokens) != 1 || got.SessionTokens[0] != "gpsftp_x" { + t.Fatalf("body tokens = %v", got.SessionTokens) + } +} + +func TestEndSessionErrors(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + if err := c.EndSession(context.Background(), "gpsftp_x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("404: err = %v, want ErrNotFound", err) + } + if err := c.EndSession(context.Background(), ""); !errors.Is(err, ErrBadRequest) { + t.Fatalf("empty token: err = %v, want ErrBadRequest", err) + } +} diff --git a/internal/sshserver/hostkeys.go b/internal/sshserver/hostkeys.go new file mode 100644 index 0000000..5584261 --- /dev/null +++ b/internal/sshserver/hostkeys.go @@ -0,0 +1,87 @@ +package sshserver + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "golang.org/x/crypto/ssh" +) + +// LoadHostKeys reads host keys from path, which is one private key file or a +// directory of them. In a directory it takes every regular file except +// hidden names (Kubernetes Secret bookkeeping such as ..data) and public +// keys (*.pub). Symlinks are followed, so a mounted Secret works. Any file +// that does not parse is an error, and so is a directory with no keys. +func LoadHostKeys(path string) ([]ssh.Signer, error) { + info, err := os.Stat(path) + if err != nil { + return nil, fmt.Errorf("host key %s: %w", path, err) + } + files := []string{path} + if info.IsDir() { + files, err = hostKeyFiles(path) + if err != nil { + return nil, err + } + } + signers := make([]ssh.Signer, 0, len(files)) + for _, f := range files { + data, err := readKeyFile(f) + if err != nil { + return nil, fmt.Errorf("read host key %s: %w", f, err) + } + signer, err := ssh.ParsePrivateKey(data) + if err != nil { + return nil, fmt.Errorf("parse host key %s: %w", f, err) + } + signers = append(signers, signer) + } + return signers, nil +} + +func hostKeyFiles(dir string) ([]string, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, fmt.Errorf("read host key dir %s: %w", dir, err) + } + var files []string + for _, e := range entries { + name := e.Name() + if strings.HasPrefix(name, ".") || strings.HasSuffix(name, ".pub") { + continue + } + full := filepath.Join(dir, name) + fi, err := os.Stat(full) + if err != nil || !fi.Mode().IsRegular() { + continue + } + files = append(files, full) + } + if len(files) == 0 { + return nil, errors.New("no host keys found in " + dir) + } + return files, nil +} + +// readKeyFile reads one key file through os.Root, so the read stays inside the +// file's directory: a path cannot leave it with ".." or an escaping symlink. +// A mounted Secret's links stay inside its directory, so they still work. +func readKeyFile(path string) ([]byte, error) { + dir, name := filepath.Split(path) + if dir == "" { + dir = "." + } + root, err := os.OpenRoot(dir) + if err != nil { + return nil, fmt.Errorf("open directory: %w", err) + } + defer func() { _ = root.Close() }() + data, err := root.ReadFile(name) + if err != nil { + return nil, fmt.Errorf("read file: %w", err) + } + return data, nil +} diff --git a/internal/sshserver/metrics.go b/internal/sshserver/metrics.go new file mode 100644 index 0000000..5742430 --- /dev/null +++ b/internal/sshserver/metrics.go @@ -0,0 +1,110 @@ +package sshserver + +import ( + "fmt" + + "github.com/prometheus/client_golang/prometheus" +) + +// Login results, the values of the result label on gameplane_sftp_logins_total. +const ( + loginOK = "ok" + loginDenied = "denied" // the API refused the credentials or rate-limited them + loginError = "error" // the API failed or was unreachable + loginLimit = "limit" // the user already has the maximum number of connections +) + +// Metrics holds the server's Prometheus collectors. Every method is safe to +// call on a nil *Metrics, so a Server without metrics needs no checks. +type Metrics struct { + sessions prometheus.Gauge + logins *prometheus.CounterVec + revokes prometheus.Counter + preAuth prometheus.Counter + bytes *prometheus.CounterVec +} + +// NewMetrics builds the collectors and registers them with reg. Use a +// private registry, not the process default. +func NewMetrics(reg prometheus.Registerer) (*Metrics, error) { + m := &Metrics{ + sessions: prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "gameplane_sftp_sessions", + Help: "Authenticated SSH connections currently open.", + }), + logins: prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "gameplane_sftp_logins_total", + Help: "Login attempts by result.", + }, []string{"result"}), + revokes: prometheus.NewCounter(prometheus.CounterOpts{ + Name: "gameplane_sftp_revoked_total", + Help: "Connections closed because their session was revoked.", + }), + preAuth: prometheus.NewCounter(prometheus.CounterOpts{ + Name: "gameplane_sftp_preauth_rejected_total", + Help: "Connections closed at once because too many were still authenticating.", + }), + bytes: prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "gameplane_sftp_bytes_total", + Help: "File bytes transferred, by direction (read or write).", + }, []string{"direction"}), + } + for _, c := range []prometheus.Collector{m.sessions, m.logins, m.revokes, m.preAuth, m.bytes} { + if err := reg.Register(c); err != nil { + return nil, fmt.Errorf("register sftp metrics: %w", err) + } + } + // Create every result series up front so each one shows as 0 from the + // first scrape. + for _, r := range []string{loginOK, loginDenied, loginError, loginLimit} { + m.logins.WithLabelValues(r) + } + for _, d := range []string{"read", "write"} { + m.bytes.WithLabelValues(d) + } + return m, nil +} + +// AddBytes counts n transferred bytes in direction "read" or "write". It +// matches the OnBytes hook of the virtual file system. +func (m *Metrics) AddBytes(direction string, n int) { + if m == nil || n <= 0 { + return + } + m.bytes.WithLabelValues(direction).Add(float64(n)) +} + +func (m *Metrics) login(result string) { + if m == nil { + return + } + m.logins.WithLabelValues(result).Inc() +} + +func (m *Metrics) sessionOpened() { + if m == nil { + return + } + m.sessions.Inc() +} + +func (m *Metrics) sessionClosed() { + if m == nil { + return + } + m.sessions.Dec() +} + +func (m *Metrics) revoked() { + if m == nil { + return + } + m.revokes.Inc() +} + +func (m *Metrics) preAuthRejected() { + if m == nil { + return + } + m.preAuth.Inc() +} diff --git a/internal/sshserver/server.go b/internal/sshserver/server.go new file mode 100644 index 0000000..45fafca --- /dev/null +++ b/internal/sshserver/server.go @@ -0,0 +1,704 @@ +// Package sshserver accepts SSH connections, authenticates them through the +// Gameplane API and serves the SFTP subsystem and nothing else. Every other +// channel type and request (shell, exec, pty, forwarding) is refused. See +// specs.md for the contract. +package sshserver + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +const ( + defaultAddr = ":2222" + defaultIdleTimeout = 15 * time.Minute + defaultMaxSessions = 4 + defaultMaxPreAuth = 64 + defaultCheckInterval = 30 * time.Second + defaultLoginTimeout = 10 * time.Second + acceptRetryDelay = 100 * time.Millisecond + serverVersion = "SSH-2.0-Gameplane-SFTP" + maxAuthTries = 3 + sftpSubsystem = "sftp" + + extSessionToken = "sessionToken" + extUser = "user" + extNamespace = "namespace" + extServer = "server" + extExpiresAt = "expiresAt" + extPublicKey = "publicKey" +) + +// errPermissionDenied is the only authentication error the SSH client ever +// sees. It never says why a login failed (core rule 3). +var errPermissionDenied = errors.New("permission denied") + +// API is the part of the Gameplane API client the server needs. *apiclient.Client +// satisfies it. +type API interface { + Login(ctx context.Context, r apiclient.LoginRequest) (apiclient.Session, error) + CheckSessions(ctx context.Context, tokens []string) ([]string, error) + // EndSession closes the API session a login created. The server calls it + // when it drops a connection whose login succeeded at the API. + EndSession(ctx context.Context, token string) error +} + +// HandlerFactory builds the SFTP request handlers for one authenticated +// SFTP subsystem. user is the login name the API returned. +type HandlerFactory func(sess apiclient.Session, user string) sftp.Handlers + +// Config configures a Server. Zero values take the defaults documented on +// each field. +type Config struct { + // Addr is the listen address the caller binds. Serve takes the listener, + // so Addr is informational. Default ":2222". + Addr string + // HostKeys are the server's host keys. At least one is required. + HostKeys []ssh.Signer + // IdleTimeout closes an authenticated connection with no traffic for + // this long. Default 15m. + IdleTimeout time.Duration + // MaxSessionsPerUser caps concurrent authenticated connections per user. + // Default 4. + MaxSessionsPerUser int + // MaxPreAuthConnections caps concurrent connections that have not yet + // finished authentication. A connection over the cap is closed at once. + // Default 64. + MaxPreAuthConnections int + // CheckInterval is how often the server asks the API which of its + // session tokens were revoked. Default 30s. + CheckInterval time.Duration + // LoginTimeout bounds each API call and the SSH handshake before + // authentication completes. Default 10s. + LoginTimeout time.Duration + // Logger receives operational logs. Never passwords, tokens or keys. + Logger *slog.Logger + // Metrics receives counters and gauges. Nil disables them. + Metrics *Metrics +} + +// Server is an SSH server that serves SFTP for authenticated users. +type Server struct { + cfg Config + api API + hf HandlerFactory + sshCfg *ssh.ServerConfig + log *slog.Logger + metrics *Metrics + + mu sync.Mutex + listener net.Listener + base context.Context // Serve's context; Background before Serve + open map[net.Conn]struct{} // every accepted connection, until it ends + tokens map[string]*connState // session token -> authenticated connection + perUser map[string]int // lowercased user -> authenticated connections + closing bool // set once Serve's context ends + preAuth int // connections still before authentication + pending map[string]apiclient.Session // remote address -> password login awaiting handshake end +} + +// New validates cfg and returns a Server. It does not listen. +func New(cfg Config, api API, hf HandlerFactory) (*Server, error) { + if api == nil { + return nil, errors.New("sshserver: nil API client") + } + if hf == nil { + return nil, errors.New("sshserver: nil handler factory") + } + if len(cfg.HostKeys) == 0 { + return nil, errors.New("sshserver: no host keys") + } + cfg, err := cfg.withDefaults() + if err != nil { + return nil, err + } + s := &Server{ + cfg: cfg, + api: api, + hf: hf, + log: cfg.Logger, + metrics: cfg.Metrics, + open: make(map[net.Conn]struct{}), + tokens: make(map[string]*connState), + perUser: make(map[string]int), + pending: make(map[string]apiclient.Session), + base: context.Background(), + } + sc := &ssh.ServerConfig{ + PasswordCallback: s.passwordCallback, + PublicKeyCallback: s.publicKeyCallback, + MaxAuthTries: maxAuthTries, + ServerVersion: serverVersion, + } + for _, k := range cfg.HostKeys { + sc.AddHostKey(k) + } + s.sshCfg = sc + return s, nil +} + +func (c Config) withDefaults() (Config, error) { + if c.Addr == "" { + c.Addr = defaultAddr + } + if c.IdleTimeout < 0 || c.CheckInterval < 0 || c.LoginTimeout < 0 { + return c, errors.New("sshserver: negative timeout") + } + if c.MaxSessionsPerUser < 0 { + return c, errors.New("sshserver: negative session cap") + } + if c.MaxPreAuthConnections < 0 { + return c, errors.New("sshserver: negative pre-auth connection cap") + } + if c.IdleTimeout == 0 { + c.IdleTimeout = defaultIdleTimeout + } + if c.MaxSessionsPerUser == 0 { + c.MaxSessionsPerUser = defaultMaxSessions + } + if c.MaxPreAuthConnections == 0 { + c.MaxPreAuthConnections = defaultMaxPreAuth + } + if c.CheckInterval == 0 { + c.CheckInterval = defaultCheckInterval + } + if c.LoginTimeout == 0 { + c.LoginTimeout = defaultLoginTimeout + } + if c.Logger == nil { + c.Logger = slog.New(slog.DiscardHandler) + } + return c, nil +} + +// Addr returns the address Serve is listening on, or nil before Serve starts. +func (s *Server) Addr() net.Addr { + s.mu.Lock() + defer s.mu.Unlock() + if s.listener == nil { + return nil + } + return s.listener.Addr() +} + +// Serve accepts connections on l until ctx ends. On shutdown it closes the +// listener and every open connection, waits for them to finish, and returns +// nil. It also runs the revocation check loop for the duration. +func (s *Server) Serve(ctx context.Context, l net.Listener) error { + s.mu.Lock() + if s.listener != nil { + s.mu.Unlock() + return errors.New("sshserver: already serving") + } + s.listener = l + s.base = ctx + s.mu.Unlock() + + stop := context.AfterFunc(ctx, s.shutdown) + defer stop() + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + s.checkLoop(ctx) + }() + + var acceptErr error + for { + raw, err := l.Accept() + if err != nil { + if ctx.Err() != nil { + break + } + if errors.Is(err, net.ErrClosed) { + acceptErr = fmt.Errorf("accept: %w", err) + break + } + s.log.Warn("accept failed", "err", err) + select { + case <-ctx.Done(): + case <-time.After(acceptRetryDelay): + } + continue + } + if !s.track(raw) { + _ = raw.Close() + continue + } + if !s.acquirePreAuth() { + s.untrack(raw) + _ = raw.Close() + s.metrics.preAuthRejected() + s.log.Info("connection refused", "remote", raw.RemoteAddr().String(), "reason", "pre-auth cap") + continue + } + wg.Add(1) + go func() { + defer wg.Done() + defer s.untrack(raw) + s.handle(ctx, raw, sync.OnceFunc(s.releasePreAuth)) + }() + } + s.shutdown() + wg.Wait() + return acceptErr +} + +// shutdown closes the listener and every open connection and marks the +// server closing so no new connection is tracked. +func (s *Server) shutdown() { + s.mu.Lock() + s.closing = true + l := s.listener + conns := make([]net.Conn, 0, len(s.open)) + for c := range s.open { + conns = append(conns, c) + } + s.mu.Unlock() + if l != nil { + _ = l.Close() + } + for _, c := range conns { + _ = c.Close() + } +} + +func (s *Server) track(c net.Conn) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.closing { + return false + } + s.open[c] = struct{}{} + return true +} + +// acquirePreAuth takes one pre-authentication slot, or reports that the cap +// is reached. +func (s *Server) acquirePreAuth() bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.preAuth >= s.cfg.MaxPreAuthConnections { + return false + } + s.preAuth++ + return true +} + +func (s *Server) releasePreAuth() { + s.mu.Lock() + defer s.mu.Unlock() + s.preAuth-- +} + +// endSession tells the API to close a session this server created but will +// not use. It keeps ctx's values but not its cancellation, so a shutdown +// does not skip it. A +// failure is only logged: the session still expires on its own. +func (s *Server) endSession(ctx context.Context, sess apiclient.Session) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), s.cfg.LoginTimeout) + defer cancel() + if err := s.api.EndSession(ctx, sess.Token); err != nil { + s.log.Debug("end session failed", "user", sess.User, "err", err) + } +} + +func (s *Server) baseCtx() context.Context { + s.mu.Lock() + defer s.mu.Unlock() + return s.base +} + +func (s *Server) takePending(remote string) (apiclient.Session, bool) { + s.mu.Lock() + defer s.mu.Unlock() + sess, ok := s.pending[remote] + delete(s.pending, remote) + return sess, ok +} + +func (s *Server) untrack(c net.Conn) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.open, c) +} + +// connState is one authenticated connection. +type connState struct { + sconn *ssh.ServerConn + sess apiclient.Session + user string // API user name as returned by login + key string // lowercased user, the per-user cap key + sftpStarted atomic.Bool + revoked atomic.Bool +} + +// handle runs one TCP connection from handshake to close. releasePreAuth +// frees the connection's pre-authentication slot; it is safe to call twice. +func (s *Server) handle(ctx context.Context, raw net.Conn, releasePreAuth func()) { + defer releasePreAuth() + remote := raw.RemoteAddr().String() + dc := &deadlineConn{Conn: raw} + dc.idle.Store(int64(s.cfg.LoginTimeout)) + // The handshake gets an absolute deadline, so a client that sends a byte + // now and then cannot keep its pre-auth slot past LoginTimeout. + dc.hard.Store(time.Now().Add(s.cfg.LoginTimeout).UnixNano()) + + sconn, chans, reqs, err := ssh.NewServerConn(dc, s.sshCfg) + // A password login already created an API session in the callback. + pwSess, hasPW := s.takePending(remote) + if err != nil { + s.log.Debug("ssh handshake ended", "remote", remote, "err", err) + _ = raw.Close() + if hasPW { + s.endSession(ctx, pwSess) + } + return + } + defer func() { _ = sconn.Close() }() + + dc.hard.Store(0) + // The SSH mux is already blocked in a read whose deadline came from the + // handshake. Push it out so a public-key login call to the API, which may + // take up to LoginTimeout, is not cut off by it. + dc.idle.Store(int64(max(s.cfg.IdleTimeout, s.cfg.LoginTimeout))) + dc.touch() + sess, err := s.establish(ctx, sconn, pwSess, hasPW) + releasePreAuth() + if err != nil { + return + } + // Switch to the idle timeout now. + dc.idle.Store(int64(s.cfg.IdleTimeout)) + dc.touch() + + st := &connState{sconn: sconn, sess: sess, user: sess.User, key: strings.ToLower(sess.User)} + if !s.admit(st) { + s.endSession(ctx, sess) + s.metrics.login(loginLimit) + s.log.Info("login refused", "user", st.user, "remote", remote, "result", loginLimit) + return + } + defer s.release(st) + s.metrics.login(loginOK) + s.metrics.sessionOpened() + defer s.metrics.sessionClosed() + s.log.Info("ssh session opened", "user", st.user, "remote", remote) + defer s.log.Info("ssh session closed", "user", st.user, "remote", remote) + + go ssh.DiscardRequests(reqs) + var channels sync.WaitGroup + for nc := range chans { + if nc.ChannelType() != "session" { + _ = nc.Reject(ssh.UnknownChannelType, "only session channels") + continue + } + channels.Add(1) + go func() { + defer channels.Done() + s.serveSession(nc, st) + }() + } + channels.Wait() +} + +// establish returns the session for a finished handshake. Password logins +// were checked in the password callback. Public-key logins are checked here, +// after the SSH layer has verified the signature, so the API only ever sees +// keys the client proved it holds. +func (s *Server) establish(ctx context.Context, sconn *ssh.ServerConn, pwSess apiclient.Session, hasPW bool) (apiclient.Session, error) { + perms := sconn.Permissions + if perms == nil { + if hasPW { + s.endSession(ctx, pwSess) + } + return apiclient.Session{}, errPermissionDenied + } + if line := perms.Extensions[extPublicKey]; line != "" { + lctx, cancel := context.WithTimeout(ctx, s.cfg.LoginTimeout) + defer cancel() + sess, err := s.api.Login(lctx, apiclient.LoginRequest{ + Username: sconn.User(), + PublicKey: line, + RemoteAddr: sconn.RemoteAddr().String(), + }) + if err != nil { + s.loginFailed(sconn.User(), sconn.RemoteAddr().String(), err) + return apiclient.Session{}, errPermissionDenied + } + return sess, nil + } + sess, err := sessionFromExtensions(perms.Extensions) + if err != nil { + if hasPW { + s.endSession(ctx, pwSess) + } + return apiclient.Session{}, errPermissionDenied + } + return sess, nil +} + +// admit records an authenticated connection and enforces the per-user cap. +func (s *Server) admit(st *connState) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.perUser[st.key] >= s.cfg.MaxSessionsPerUser { + return false + } + s.perUser[st.key]++ + s.tokens[st.sess.Token] = st + return true +} + +func (s *Server) release(st *connState) { + s.mu.Lock() + defer s.mu.Unlock() + if n := s.perUser[st.key] - 1; n > 0 { + s.perUser[st.key] = n + } else { + delete(s.perUser, st.key) + } + if s.tokens[st.sess.Token] == st { + delete(s.tokens, st.sess.Token) + } +} + +func (s *Server) atLimit(user string) bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.perUser[strings.ToLower(user)] >= s.cfg.MaxSessionsPerUser +} + +// passwordCallback logs the user in through the API. Its error is always the +// generic permission-denied error. +func (s *Server) passwordCallback(conn ssh.ConnMetadata, pw []byte) (*ssh.Permissions, error) { + ctx, cancel := context.WithTimeout(context.Background(), s.cfg.LoginTimeout) + defer cancel() + sess, err := s.api.Login(ctx, apiclient.LoginRequest{ + Username: conn.User(), + Password: string(pw), + RemoteAddr: conn.RemoteAddr().String(), + }) + if err != nil { + s.loginFailed(conn.User(), conn.RemoteAddr().String(), err) + return nil, errPermissionDenied + } + // Fast refusal for a user already at the cap. admit enforces it again + // after the handshake, which is the authoritative check. + if s.atLimit(sess.User) { + s.endSession(s.baseCtx(), sess) + s.metrics.login(loginLimit) + s.log.Info("login refused", "user", sess.User, "remote", conn.RemoteAddr().String(), "result", loginLimit) + return nil, errPermissionDenied + } + // Remember the session until the handshake ends, so a connection dropped + // before it is used can still end it. + s.mu.Lock() + s.pending[conn.RemoteAddr().String()] = sess + s.mu.Unlock() + return &ssh.Permissions{Extensions: sessionExtensions(sess)}, nil +} + +// publicKeyCallback only records the offered key. The SSH layer calls it +// before the signature is checked, so the API is not asked here; establish +// does that after the handshake. +func (s *Server) publicKeyCallback(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + line := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) + return &ssh.Permissions{Extensions: map[string]string{extPublicKey: line}}, nil +} + +func (s *Server) loginFailed(user, remote string, err error) { + result := loginError + if errors.Is(err, apiclient.ErrUnauthorized) || errors.Is(err, apiclient.ErrBusy) { + result = loginDenied + } + s.metrics.login(result) + s.log.Info("login refused", "user", user, "remote", remote, "result", result) + s.log.Debug("login error", "user", user, "err", err) +} + +// serveSession handles one session channel. Only one sftp subsystem may run +// per connection. shell and exec are refused and the channel is closed. +func (s *Server) serveSession(nc ssh.NewChannel, st *connState) { + ch, reqs, err := nc.Accept() + if err != nil { + return + } + var sftpDone sync.WaitGroup + // mine is set once this channel runs the connection's sftp subsystem. + // While another channel runs it, this one is an extra: every request is + // refused and the channel is closed right after, so it never sits idle. + mine := false + refuse := func(req *ssh.Request) { + _ = req.Reply(false, nil) + if !mine && st.sftpStarted.Load() { + _ = ch.Close() + } + } + for req := range reqs { + switch req.Type { + case "subsystem": + if name, ok := subsystemName(req.Payload); !ok || name != sftpSubsystem || !st.sftpStarted.CompareAndSwap(false, true) { + refuse(req) + continue + } + mine = true + _ = req.Reply(true, nil) + sftpDone.Add(1) + go func() { + defer sftpDone.Done() + s.serveSFTP(ch, st) + }() + case "shell", "exec": + _ = req.Reply(false, nil) + _ = ch.Close() + default: + // pty-req, env, x11-req, window-change, signal, auth-agent-req + // and anything unknown: refused. + refuse(req) + } + } + sftpDone.Wait() + _ = ch.Close() +} + +func subsystemName(payload []byte) (string, bool) { + var p struct{ Name string } + if err := ssh.Unmarshal(payload, &p); err != nil { + return "", false + } + return p.Name, true +} + +func (s *Server) serveSFTP(ch ssh.Channel, st *connState) { + srv := sftp.NewRequestServer(ch, s.hf(st.sess, st.user)) + if err := srv.Serve(); err != nil && !errors.Is(err, io.EOF) { + s.log.Debug("sftp subsystem ended", "user", st.user, "err", err) + } + _ = srv.Close() +} + +// checkLoop asks the API every CheckInterval which session tokens were +// revoked and closes those connections. +func (s *Server) checkLoop(ctx context.Context) { + t := time.NewTicker(s.cfg.CheckInterval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + s.checkOnce(ctx) + } + } +} + +func (s *Server) checkOnce(ctx context.Context) { + s.mu.Lock() + tokens := make([]string, 0, len(s.tokens)) + for tok := range s.tokens { + tokens = append(tokens, tok) + } + s.mu.Unlock() + if len(tokens) == 0 { + return + } + cctx, cancel := context.WithTimeout(ctx, s.cfg.LoginTimeout) + defer cancel() + revoked, err := s.api.CheckSessions(cctx, tokens) + if err != nil { + // Keep the connections. Failing open is not a revocation, and + // closing on a transient API error would drop healthy users. + s.log.Warn("session check failed; connections kept", "err", err) + return + } + for _, tok := range revoked { + s.mu.Lock() + st := s.tokens[tok] + s.mu.Unlock() + if st == nil || !st.revoked.CompareAndSwap(false, true) { + continue + } + s.log.Info("session revoked", "user", st.user) + s.metrics.revoked() + _ = st.sconn.Close() + } +} + +// deadlineConn pushes the connection deadline forward on every read and +// write. idle holds the timeout in nanoseconds; zero means no deadline. hard, +// when non-zero, is an absolute deadline (Unix nanoseconds) that a touch never +// moves past. +type deadlineConn struct { + net.Conn + idle atomic.Int64 + hard atomic.Int64 +} + +func (c *deadlineConn) Read(p []byte) (int, error) { + c.touch() + return c.Conn.Read(p) +} + +func (c *deadlineConn) Write(p []byte) (int, error) { + c.touch() + return c.Conn.Write(p) +} + +func (c *deadlineConn) touch() { + var deadline time.Time + if d := time.Duration(c.idle.Load()); d > 0 { + deadline = time.Now().Add(d) + } + if h := c.hard.Load(); h != 0 { + if hd := time.Unix(0, h); deadline.IsZero() || hd.Before(deadline) { + deadline = hd + } + } + if !deadline.IsZero() { + _ = c.SetDeadline(deadline) + } +} + +// sessionExtensions carries a successful login through ssh.Permissions. +func sessionExtensions(sess apiclient.Session) map[string]string { + ext := map[string]string{ + extSessionToken: sess.Token, + extUser: sess.User, + extExpiresAt: sess.ExpiresAt.Format(time.RFC3339), + } + if sess.Target != nil { + ext[extNamespace] = sess.Target.Namespace + ext[extServer] = sess.Target.Server + } + return ext +} + +func sessionFromExtensions(ext map[string]string) (apiclient.Session, error) { + tok := ext[extSessionToken] + if tok == "" { + return apiclient.Session{}, errors.New("sshserver: no session token") + } + expires, err := time.Parse(time.RFC3339, ext[extExpiresAt]) + if err != nil { + return apiclient.Session{}, fmt.Errorf("sshserver: expiresAt: %w", err) + } + sess := apiclient.Session{Token: tok, ExpiresAt: expires, User: ext[extUser]} + if ns := ext[extNamespace]; ns != "" { + sess.Target = &apiclient.Target{Namespace: ns, Server: ext[extServer]} + } + return sess, nil +} diff --git a/internal/sshserver/server_test.go b/internal/sshserver/server_test.go new file mode 100644 index 0000000..4dd59b7 --- /dev/null +++ b/internal/sshserver/server_test.go @@ -0,0 +1,832 @@ +package sshserver + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "errors" + "fmt" + "io" + "log/slog" + "net" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" + "golang.org/x/crypto/ssh" +) + +// fakeAPI stands in for the Gameplane API. Successful logins mint a new +// token per call. The user is the part of the username before "+". +type fakeAPI struct { + mu sync.Mutex + loginErr error + logins []apiclient.LoginRequest + revoke func(tokens []string) []string + ended []string + endErr error + seq int +} + +func (f *fakeAPI) Login(_ context.Context, r apiclient.LoginRequest) (apiclient.Session, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.logins = append(f.logins, r) + if f.loginErr != nil { + return apiclient.Session{}, f.loginErr + } + f.seq++ + user, target, hasTarget := strings.Cut(r.Username, "+") + sess := apiclient.Session{ + Token: fmt.Sprintf("gpsftp_test_%d", f.seq), + ExpiresAt: time.Now().Add(time.Hour).UTC().Truncate(time.Second), + User: user, + } + if hasTarget { + sess.Target = &apiclient.Target{Namespace: "games", Server: target} + } + return sess, nil +} + +func (f *fakeAPI) CheckSessions(_ context.Context, tokens []string) ([]string, error) { + f.mu.Lock() + fn := f.revoke + f.mu.Unlock() + if fn == nil { + return nil, nil + } + return fn(tokens), nil +} + +func (f *fakeAPI) EndSession(_ context.Context, token string) error { + f.mu.Lock() + defer f.mu.Unlock() + f.ended = append(f.ended, token) + return f.endErr +} + +func (f *fakeAPI) endedTokens() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.ended...) +} + +func (f *fakeAPI) setRevoke(fn func([]string) []string) { + f.mu.Lock() + defer f.mu.Unlock() + f.revoke = fn +} + +func (f *fakeAPI) lastLogin(t *testing.T) apiclient.LoginRequest { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + if len(f.logins) == 0 { + t.Fatal("no login reached the API") + } + return f.logins[len(f.logins)-1] +} + +// testFS refuses every file operation except listing an empty root. +type testFS struct{} + +func (testFS) Fileread(*sftp.Request) (io.ReaderAt, error) { return nil, sftp.ErrSSHFxOpUnsupported } +func (testFS) Filewrite(*sftp.Request) (io.WriterAt, error) { + return nil, sftp.ErrSSHFxOpUnsupported +} +func (testFS) Filecmd(*sftp.Request) error { return sftp.ErrSSHFxOpUnsupported } +func (testFS) Filelist(*sftp.Request) (sftp.ListerAt, error) { return emptyLister{}, nil } + +type emptyLister struct{} + +func (emptyLister) ListAt([]os.FileInfo, int64) (int, error) { return 0, io.EOF } + +func testHandlers(apiclient.Session, string) sftp.Handlers { + fs := testFS{} + return sftp.Handlers{FileGet: fs, FilePut: fs, FileCmd: fs, FileList: fs} +} + +func newEd25519Signer(t *testing.T) ssh.Signer { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate key: %v", err) + } + signer, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatalf("signer: %v", err) + } + return signer +} + +type harness struct { + t *testing.T + addr string + api *fakeAPI + metrics *Metrics + reg *prometheus.Registry +} + +// newHarness starts a server on a loopback port and stops it at cleanup. +func newHarness(t *testing.T, mutate func(*Config), api *fakeAPI) *harness { + t.Helper() + return newHarnessWith(t, mutate, api, testHandlers) +} + +// newHarnessWith is newHarness with a custom SFTP handler factory. +func newHarnessWith(t *testing.T, mutate func(*Config), api *fakeAPI, hf HandlerFactory) *harness { + t.Helper() + reg := prometheus.NewRegistry() + m, err := NewMetrics(reg) + if err != nil { + t.Fatalf("metrics: %v", err) + } + cfg := Config{ + HostKeys: []ssh.Signer{newEd25519Signer(t)}, + CheckInterval: time.Hour, + Logger: slog.New(slog.DiscardHandler), + Metrics: m, + } + if mutate != nil { + mutate(&cfg) + } + srv, err := New(cfg, api, hf) + if err != nil { + t.Fatalf("New: %v", err) + } + l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- srv.Serve(ctx, l) }() + t.Cleanup(func() { + cancel() + if err := <-done; err != nil { + t.Errorf("Serve returned %v", err) + } + }) + return &harness{t: t, addr: l.Addr().String(), api: api, metrics: m, reg: reg} +} + +func (h *harness) dialErr(user string, auth ...ssh.AuthMethod) (*ssh.Client, error) { + return ssh.Dial("tcp", h.addr, &ssh.ClientConfig{ + User: user, + Auth: auth, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 5 * time.Second, + }) +} + +func (h *harness) mustDial(user string, auth ...ssh.AuthMethod) *ssh.Client { + h.t.Helper() + c, err := h.dialErr(user, auth...) + if err != nil { + h.t.Fatalf("dial as %q: %v", user, err) + } + h.t.Cleanup(func() { _ = c.Close() }) + return c +} + +// readRoot opens the SFTP subsystem and lists "/". +func readRoot(c *ssh.Client) error { + sc, err := sftp.NewClient(c) + if err != nil { + return err + } + defer func() { _ = sc.Close() }() + _, err = sc.ReadDir("/") + return err +} + +func waitClosed(t *testing.T, c *ssh.Client) { + t.Helper() + done := make(chan struct{}) + go func() { + _ = c.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("connection was not closed") + } +} + +func eventually(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestPasswordLoginServesSFTP(t *testing.T) { + api := &fakeAPI{} + h := newHarness(t, nil, api) + c := h.mustDial("alice+mods/survival", ssh.Password("pw")) + if err := readRoot(c); err != nil { + t.Fatalf("sftp ReadDir: %v", err) + } + got := api.lastLogin(t) + if got.Username != "alice+mods/survival" || got.Password != "pw" || got.PublicKey != "" || got.RemoteAddr == "" { + t.Fatalf("login request = %+v", got) + } +} + +func TestWrongPasswordIsGenericallyDenied(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{loginErr: apiclient.ErrUnauthorized}) + _, err := h.dialErr("alice", ssh.Password("wrong")) + if err == nil { + t.Fatal("dial succeeded with a refused password") + } + if strings.Contains(err.Error(), "unauthorized") { + t.Fatalf("auth error leaks the cause: %v", err) + } + if got := testutil.ToFloat64(h.metrics.logins.WithLabelValues(loginDenied)); got != 1 { + t.Fatalf("denied logins = %v, want 1", got) + } +} + +func TestAPIFailureCountsAsError(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{loginErr: errors.New("api down")}) + if _, err := h.dialErr("alice", ssh.Password("pw")); err == nil { + t.Fatal("dial succeeded when the API failed") + } + if got := testutil.ToFloat64(h.metrics.logins.WithLabelValues(loginError)); got != 1 { + t.Fatalf("error logins = %v, want 1", got) + } +} + +func TestPublicKeyLoginSendsVerifiedKey(t *testing.T) { + clientKey := newEd25519Signer(t) + api := &fakeAPI{} + h := newHarness(t, nil, api) + c := h.mustDial("bob", ssh.PublicKeys(clientKey)) + if err := readRoot(c); err != nil { + t.Fatalf("sftp ReadDir: %v", err) + } + want := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(clientKey.PublicKey()))) + got := api.lastLogin(t) + if got.PublicKey != want || got.Password != "" { + t.Fatalf("login request = %+v, want public key %q", got, want) + } +} + +func TestRefusedPublicKeyClosesConnection(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{loginErr: apiclient.ErrUnauthorized}) + c, err := h.dialErr("bob", ssh.PublicKeys(newEd25519Signer(t))) + if err == nil { + // Key auth completes in the SSH layer before the API check, so the + // server closes the connection right after it. The SFTP layer then + // fails. + defer func() { _ = c.Close() }() + if readRoot(c) == nil { + t.Fatal("sftp worked for a refused key") + } + } +} + +func TestNonSFTPRequestsAreRefused(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + + if s, err := c.NewSession(); err == nil { + if err := s.Shell(); err == nil { + t.Error("shell was accepted") + } + _ = s.Close() + } + if s, err := c.NewSession(); err == nil { + if err := s.Run("ls"); err == nil { + t.Error("exec was accepted") + } + _ = s.Close() + } + if s, err := c.NewSession(); err == nil { + if err := s.RequestPty("xterm", 24, 80, ssh.TerminalModes{}); err == nil { + t.Error("pty was accepted") + } + _ = s.Close() + } + if s, err := c.NewSession(); err == nil { + if err := s.RequestSubsystem("scp"); err == nil { + t.Error("non-sftp subsystem was accepted") + } + _ = s.Close() + } + if conn, err := c.Dial("tcp", "127.0.0.1:1"); err == nil { + _ = conn.Close() + t.Error("direct-tcpip channel was accepted") + } + if l, err := c.Listen("tcp", "127.0.0.1:0"); err == nil { + _ = l.Close() + t.Error("tcpip-forward was accepted") + } +} + +func TestSecondSFTPSubsystemIsRefused(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + sc, err := sftp.NewClient(c) + if err != nil { + t.Fatalf("first sftp: %v", err) + } + defer func() { _ = sc.Close() }() + s, err := c.NewSession() + if err != nil { + t.Fatalf("NewSession: %v", err) + } + defer func() { _ = s.Close() }() + if err := s.RequestSubsystem("sftp"); err == nil { + t.Fatal("second sftp subsystem was accepted") + } +} + +func TestRevokedSessionIsClosed(t *testing.T) { + api := &fakeAPI{} + h := newHarness(t, func(c *Config) { c.CheckInterval = 20 * time.Millisecond }, api) + c := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(c); err != nil { + t.Fatalf("sftp ReadDir: %v", err) + } + api.setRevoke(func(tokens []string) []string { return tokens }) + waitClosed(t, c) + eventually(t, "session gauge back to 0", func() bool { + return testutil.ToFloat64(h.metrics.sessions) == 0 + }) + if got := testutil.ToFloat64(h.metrics.revokes); got != 1 { + t.Fatalf("revoked_total = %v, want 1", got) + } +} + +func TestConnectionSurvivesChecksWithoutRevocation(t *testing.T) { + api := &fakeAPI{} + h := newHarness(t, func(c *Config) { c.CheckInterval = 20 * time.Millisecond }, api) + c := h.mustDial("alice", ssh.Password("pw")) + // Several check runs pass with nothing revoked; the connection must + // stay open across them. + time.Sleep(100 * time.Millisecond) + if err := readRoot(c); err != nil { + t.Fatalf("connection dropped after checks: %v", err) + } +} + +func TestSessionCapPerUser(t *testing.T) { + api := &fakeAPI{} + h := newHarness(t, func(c *Config) { c.MaxSessionsPerUser = 2 }, api) + + a1 := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(a1); err != nil { + t.Fatalf("alice 1: %v", err) + } + a2 := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(a2); err != nil { + t.Fatalf("alice 2: %v", err) + } + if _, err := h.dialErr("alice", ssh.Password("pw")); err == nil { + t.Fatal("third connection for alice was accepted") + } + if got := testutil.ToFloat64(h.metrics.logins.WithLabelValues(loginLimit)); got < 1 { + t.Fatalf("limit logins = %v, want at least 1", got) + } + + bob := h.mustDial("bob", ssh.Password("pw")) + if err := readRoot(bob); err != nil { + t.Fatalf("bob should not share alice's cap: %v", err) + } + + _ = a1.Close() + eventually(t, "a slot to be freed", func() bool { + c, err := h.dialErr("alice", ssh.Password("pw")) + if err != nil { + return false + } + _ = c.Close() + return true + }) +} + +func TestIdleConnectionIsClosed(t *testing.T) { + h := newHarness(t, func(c *Config) { c.IdleTimeout = 200 * time.Millisecond }, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + waitClosed(t, c) +} + +func TestHandshakeIdleIsClosed(t *testing.T) { + h := newHarness(t, func(c *Config) { c.LoginTimeout = 100 * time.Millisecond }, &fakeAPI{}) + raw, err := (&net.Dialer{}).DialContext(context.Background(), "tcp", h.addr) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer func() { _ = raw.Close() }() + if err := raw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatalf("deadline: %v", err) + } + // The server sends its banner first. After that it must hang up on a + // client that never sends a version of its own. + buf := make([]byte, 1) + for { + if _, err := raw.Read(buf); err != nil { + if errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatal("silent pre-auth connection was not closed") + } + return + } + } +} + +func TestNewRejectsBadConfig(t *testing.T) { + key := newEd25519Signer(t) + api := &fakeAPI{} + cases := map[string]struct { + cfg Config + api API + hf HandlerFactory + }{ + "nil api": {Config{HostKeys: []ssh.Signer{key}}, nil, testHandlers}, + "nil handlers": {Config{HostKeys: []ssh.Signer{key}}, api, nil}, + "no host keys": {Config{}, api, testHandlers}, + "negative idle": {Config{HostKeys: []ssh.Signer{key}, IdleTimeout: -1}, api, testHandlers}, + "negative cap": {Config{HostKeys: []ssh.Signer{key}, MaxSessionsPerUser: -1}, api, testHandlers}, + "negative check": {Config{HostKeys: []ssh.Signer{key}, CheckInterval: -time.Second}, api, testHandlers}, + } + for name, tc := range cases { + if _, err := New(tc.cfg, tc.api, tc.hf); err == nil { + t.Errorf("%s: New accepted the config", name) + } + } +} + +func TestServeRejectsSecondCall(t *testing.T) { + srv, err := New(Config{HostKeys: []ssh.Signer{newEd25519Signer(t)}}, &fakeAPI{}, testHandlers) + if err != nil { + t.Fatalf("New: %v", err) + } + if srv.Addr() != nil { + t.Fatal("Addr before Serve should be nil") + } + l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- srv.Serve(ctx, l) }() + eventually(t, "Addr to be set", func() bool { return srv.Addr() != nil }) + if err := srv.Serve(ctx, l); err == nil { + t.Error("second Serve call succeeded") + } + cancel() + if err := <-done; err != nil { + t.Fatalf("Serve returned %v after cancel", err) + } +} + +func TestSessionExtensionsRoundTrip(t *testing.T) { + want := apiclient.Session{ + Token: "gpsftp_x", + ExpiresAt: time.Date(2026, 11, 23, 10, 0, 0, 0, time.UTC), + User: "alice", + Target: &apiclient.Target{Namespace: "mods", Server: "survival"}, + } + got, err := sessionFromExtensions(sessionExtensions(want)) + if err != nil { + t.Fatalf("round trip: %v", err) + } + if got.Token != want.Token || !got.ExpiresAt.Equal(want.ExpiresAt) || got.User != want.User || *got.Target != *want.Target { + t.Fatalf("round trip = %+v, want %+v", got, want) + } + want.Target = nil + got, err = sessionFromExtensions(sessionExtensions(want)) + if err != nil || got.Target != nil { + t.Fatalf("round trip without target = %+v, %v", got, err) + } + if _, err := sessionFromExtensions(map[string]string{}); err == nil { + t.Error("missing token accepted") + } + if _, err := sessionFromExtensions(map[string]string{extSessionToken: "t", extExpiresAt: "soon"}); err == nil { + t.Error("bad expiresAt accepted") + } +} + +func TestMetricsRegistration(t *testing.T) { + reg := prometheus.NewRegistry() + m, err := NewMetrics(reg) + if err != nil { + t.Fatalf("NewMetrics: %v", err) + } + if _, err := NewMetrics(reg); err == nil { + t.Error("registering the same metrics twice succeeded") + } + families, err := reg.Gather() + if err != nil { + t.Fatalf("gather: %v", err) + } + names := map[string]bool{} + for _, f := range families { + names[f.GetName()] = true + } + for _, want := range []string{"gameplane_sftp_sessions", "gameplane_sftp_logins_total", "gameplane_sftp_revoked_total", "gameplane_sftp_bytes_total"} { + if !names[want] { + t.Errorf("metric %s not exposed", want) + } + } + m.AddBytes("write", 5) + m.AddBytes("write", 0) + m.AddBytes("read", -3) + if got := testutil.ToFloat64(m.bytes.WithLabelValues("write")); got != 5 { + t.Fatalf("bytes write = %v, want 5", got) + } +} + +func TestNilMetricsAreSafe(_ *testing.T) { + var m *Metrics + m.AddBytes("read", 10) + m.login(loginOK) + m.sessionOpened() + m.sessionClosed() + m.revoked() +} + +func writeKey(t *testing.T, path string) { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate: %v", err) + } + block, err := ssh.MarshalPrivateKey(priv, "") + if err != nil { + t.Fatalf("marshal: %v", err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + if err := os.WriteFile(path, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatalf("write key: %v", err) + } +} + +func TestLoadHostKeysFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "ssh_host_ed25519_key") + writeKey(t, path) + signers, err := LoadHostKeys(path) + if err != nil || len(signers) != 1 { + t.Fatalf("LoadHostKeys(file) = %d keys, %v", len(signers), err) + } +} + +func TestLoadHostKeysSecretLayout(t *testing.T) { + dir := t.TempDir() + // Kubernetes Secret volumes: a hidden ..data link to a timestamped + // directory, with the visible names as links into it. + writeKey(t, filepath.Join(dir, "..2026_11_23", "ssh_host_ed25519_key")) + if err := os.Symlink("..2026_11_23", filepath.Join(dir, "..data")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if err := os.Symlink(filepath.Join("..data", "ssh_host_ed25519_key"), filepath.Join(dir, "ssh_host_ed25519_key")); err != nil { + t.Fatalf("symlink: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "ssh_host_ed25519_key.pub"), []byte("ssh-ed25519 AAAA"), 0o644); err != nil { + t.Fatalf("write pub: %v", err) + } + signers, err := LoadHostKeys(dir) + if err != nil || len(signers) != 1 { + t.Fatalf("LoadHostKeys(secret dir) = %d keys, %v; want 1", len(signers), err) + } +} + +func TestLoadHostKeysErrors(t *testing.T) { + if _, err := LoadHostKeys(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Error("missing path accepted") + } + empty := t.TempDir() + if _, err := LoadHostKeys(empty); err == nil { + t.Error("empty directory accepted") + } + junk := filepath.Join(t.TempDir(), "key") + if err := os.WriteFile(junk, []byte("not a key"), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + if _, err := LoadHostKeys(junk); err == nil { + t.Error("unparseable key accepted") + } +} + +// rawBanner dials the server without speaking SSH and reads its version +// banner, which proves the server accepted the connection into handle. +func rawBanner(t *testing.T, addr string) net.Conn { + t.Helper() + raw, err := (&net.Dialer{}).DialContext(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("dial: %v", err) + } + t.Cleanup(func() { _ = raw.Close() }) + if err := raw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatalf("deadline: %v", err) + } + buf := make([]byte, len(serverVersion)) + if _, err := io.ReadFull(raw, buf); err != nil { + t.Fatalf("read banner: %v", err) + } + return raw +} + +func TestPreAuthCapClosesExtraConnections(t *testing.T) { + h := newHarness(t, func(c *Config) { c.MaxPreAuthConnections = 1 }, &fakeAPI{}) + first := rawBanner(t, h.addr) + + // The cap is full, so the next connection is closed without a banner. + second, err := (&net.Dialer{}).DialContext(context.Background(), "tcp", h.addr) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer func() { _ = second.Close() }() + if err := second.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatalf("deadline: %v", err) + } + if n, err := second.Read(make([]byte, 1)); err == nil || errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("over-cap connection read %d bytes, err %v; want it closed", n, err) + } + if got := testutil.ToFloat64(h.metrics.preAuth); got != 1 { + t.Fatalf("preauth rejected = %v, want 1", got) + } + + // Freeing the slot admits a normal login again. + _ = first.Close() + eventually(t, "the pre-auth slot to be freed", func() bool { + c, err := h.dialErr("alice", ssh.Password("pw")) + if err != nil { + return false + } + _ = c.Close() + return true + }) +} + +func TestPreAuthSlotIsFreedAfterLogin(t *testing.T) { + h := newHarness(t, func(c *Config) { c.MaxPreAuthConnections = 1 }, &fakeAPI{}) + a := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(a); err != nil { + t.Fatalf("alice: %v", err) + } + // alice is authenticated and holds no pre-auth slot, so bob fits. + b := h.mustDial("bob", ssh.Password("pw")) + if err := readRoot(b); err != nil { + t.Fatalf("bob: %v", err) + } + if got := testutil.ToFloat64(h.metrics.preAuth); got != 0 { + t.Fatalf("preauth rejected = %v, want 0", got) + } +} + +func TestExtraSessionChannelIsClosedAfterRefusal(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + sc, err := sftp.NewClient(c) + if err != nil { + t.Fatalf("first sftp: %v", err) + } + defer func() { _ = sc.Close() }() + + // The extra channel is accepted, its requests are refused, and the + // server then closes it instead of leaving it idle. + s, err := c.NewSession() + if err != nil { + t.Fatalf("NewSession: %v", err) + } + defer func() { _ = s.Close() }() + if err := s.RequestSubsystem("sftp"); err == nil { + t.Fatal("second sftp subsystem was accepted") + } + done := make(chan struct{}) + go func() { + _ = s.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("extra session channel was not closed") + } + // The sftp channel is unaffected. + if _, err := sc.ReadDir("/"); err != nil { + t.Fatalf("first sftp after extra channel: %v", err) + } +} + +func TestPasswordLoginOverCapEndsAPISession(t *testing.T) { + api := &fakeAPI{} + h := newHarness(t, func(c *Config) { c.MaxSessionsPerUser = 1 }, api) + a := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(a); err != nil { + t.Fatalf("alice 1: %v", err) + } + if _, err := h.dialErr("alice", ssh.Password("pw")); err == nil { + t.Fatal("second connection for alice was accepted") + } + // The first login created gpsftp_test_1; the refused one gpsftp_test_2. + got := api.endedTokens() + if len(got) != 1 || got[0] != "gpsftp_test_2" { + t.Fatalf("ended sessions = %v, want [gpsftp_test_2]", got) + } +} + +func TestKeyLoginOverCapEndsAPISession(t *testing.T) { + api := &fakeAPI{} + h := newHarness(t, func(c *Config) { c.MaxSessionsPerUser = 1 }, api) + a := h.mustDial("alice", ssh.PublicKeys(newEd25519Signer(t))) + if err := readRoot(a); err != nil { + t.Fatalf("alice 1: %v", err) + } + // Key auth finishes in the SSH layer, so the dial may succeed; the server + // then drops the connection. + if c, err := h.dialErr("alice", ssh.PublicKeys(newEd25519Signer(t))); err == nil { + defer func() { _ = c.Close() }() + waitClosed(t, c) + } + eventually(t, "the refused API session to be ended", func() bool { + got := api.endedTokens() + return len(got) == 1 && got[0] == "gpsftp_test_2" + }) +} + +func TestEndSessionFailureIsTolerated(t *testing.T) { + api := &fakeAPI{endErr: errors.New("api down")} + h := newHarness(t, func(c *Config) { c.MaxSessionsPerUser = 1 }, api) + a := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(a); err != nil { + t.Fatalf("alice 1: %v", err) + } + if _, err := h.dialErr("alice", ssh.Password("pw")); err == nil { + t.Fatal("second connection for alice was accepted") + } + if got := api.endedTokens(); len(got) != 1 { + t.Fatalf("ended sessions = %v, want one attempt", got) + } +} + +func TestNewRejectsNegativePreAuthCap(t *testing.T) { + _, err := New(Config{HostKeys: []ssh.Signer{newEd25519Signer(t)}, MaxPreAuthConnections: -1}, &fakeAPI{}, testHandlers) + if err == nil { + t.Fatal("negative pre-auth cap accepted") + } +} + +func TestSlowDripHandshakeIsCutAtDeadline(t *testing.T) { + const loginTimeout = 400 * time.Millisecond + h := newHarness(t, func(c *Config) { c.LoginTimeout = loginTimeout }, &fakeAPI{}) + raw, err := (&net.Dialer{}).DialContext(context.Background(), "tcp", h.addr) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer func() { _ = raw.Close() }() + start := time.Now() + + // Send one byte of a never-ending version line every 50ms, well inside + // the per-read timeout. Only an absolute deadline can stop this. + stop := make(chan struct{}) + defer close(stop) + go func() { + tick := time.NewTicker(50 * time.Millisecond) + defer tick.Stop() + for { + select { + case <-stop: + return + case <-tick.C: + if _, err := raw.Write([]byte("x")); err != nil { + return + } + } + } + }() + + if err := raw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatalf("deadline: %v", err) + } + buf := make([]byte, 64) + for { + if _, err := raw.Read(buf); err != nil { + if errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatal("slow-drip connection was not closed") + } + break + } + } + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Fatalf("closed after %v, want about %v", elapsed, loginTimeout) + } +} diff --git a/internal/vfs/errors.go b/internal/vfs/errors.go new file mode 100644 index 0000000..b07dd1f --- /dev/null +++ b/internal/vfs/errors.go @@ -0,0 +1,76 @@ +package vfs + +import ( + "context" + "errors" + "fmt" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// statusErrors lists the SFTP status errors that pass through toSFTP +// unchanged. Anything else coming out of the API client is mapped. +var statusErrors = []error{ + sftp.ErrSSHFxEOF, + sftp.ErrSSHFxNoSuchFile, + sftp.ErrSSHFxPermissionDenied, + sftp.ErrSSHFxFailure, + sftp.ErrSSHFxBadMessage, + sftp.ErrSSHFxConnectionLost, + sftp.ErrSSHFxOpUnsupported, +} + +// toSFTP maps an error from the API client or the context to the SFTP status +// the client sees. Messages are fixed strings so no URL, token or body text +// reaches the client; the real error is logged by the caller at debug level. +func toSFTP(err error) error { + if err == nil { + return nil + } + for _, s := range statusErrors { + if errors.Is(err, s) { + return err + } + } + switch { + case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + return sftp.ErrSSHFxConnectionLost + case errors.Is(err, apiclient.ErrNotFound): + return sftp.ErrSSHFxNoSuchFile + case errors.Is(err, apiclient.ErrPermission), + errors.Is(err, apiclient.ErrUnauthorized), + errors.Is(err, apiclient.ErrBadRequest): + return sftp.ErrSSHFxPermissionDenied + case errors.Is(err, apiclient.ErrExists): + return failure("file exists") + case errors.Is(err, apiclient.ErrNoSpace): + return failure("no space left on server") + case errors.Is(err, apiclient.ErrTooLarge): + return failure("file too large") + case errors.Is(err, apiclient.ErrBadOffset): + return failure("bad offset") + case errors.Is(err, apiclient.ErrBusy): + return failure("server busy, try again") + case errors.Is(err, apiclient.ErrUnavailable): + return failure("server not available, try again") + default: + return sftp.ErrSSHFxFailure + } +} + +// failure returns a generic failure status carrying msg. pkg/sftp sends the +// error text to the client, so msg must be a fixed, non-sensitive string. +func failure(msg string) error { + return fmt.Errorf("%s: %w", msg, sftp.ErrSSHFxFailure) +} + +// fail maps err for the client and logs the original at debug level. op names +// the operation for the log line only. +func (f *FS) fail(op string, err error) error { + if err == nil { + return nil + } + f.log.Debug("sftp operation failed", "op", op, "user", f.user, "err", err.Error()) + return toSFTP(err) +} diff --git a/internal/vfs/fake_test.go b/internal/vfs/fake_test.go new file mode 100644 index 0000000..00c735e --- /dev/null +++ b/internal/vfs/fake_test.go @@ -0,0 +1,507 @@ +package vfs + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +const ( + testToken = "gpsftp_test" + testNS = DefaultNamespace + otherNS = "mods" +) + +// SFTP open and attribute flag bits, as sent on the wire. +const ( + fxfRead = 0x01 + fxfWrite = 0x02 + fxfAppend = 0x04 + fxfCreat = 0x08 + fxfTrunc = 0x10 + fxfExcl = 0x20 + + attrSize = 0x01 + attrUIDGID = 0x02 + attrPerm = 0x04 + attrModTime = 0x08 +) + +var fixedTime = time.Date(2026, 11, 23, 10, 0, 0, 0, time.UTC) + +// testServers are the servers every tree test starts from: one in the default +// namespace and one in another namespace. +var testServers = []apiclient.ServerRef{ + {Namespace: testNS, Server: "survival"}, + {Namespace: otherNS, Server: "modded"}, +} + +type node struct { + dir bool + data []byte + mod time.Time +} + +// stats is a copy of the fake's call counters, taken under its lock. +type stats struct { + serversCalls int + downloads int + ranges []string + streamQueries []url.Values + deletes []url.Values +} + +// fakeAPI is an in-memory stand-in for the Gameplane API's SFTP file routes. +// It keeps one tree per namespace and server. Like the real agent, it commits +// an upload only when the body ends cleanly. +type fakeAPI struct { + srv *httptest.Server + + mu sync.Mutex + servers []apiclient.ServerRef + trees map[string]map[string]*node + streamFail int // when non-zero, PUT answers this status without committing + st stats +} + +func newFakeAPI(t *testing.T, servers []apiclient.ServerRef) *fakeAPI { + t.Helper() + f := &fakeAPI{servers: servers, trees: map[string]map[string]*node{}} + f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(f.srv.Close) + return f +} + +// client returns a real apiclient.Client aimed at the fake. +func (f *fakeAPI) client(t *testing.T) *apiclient.Client { + t.Helper() + c, err := apiclient.NewWithHTTPClient(apiclient.Config{BaseURL: f.srv.URL, ServiceToken: "gpsftps_test"}, f.srv.Client()) + if err != nil { + t.Fatalf("new client: %v", err) + } + return c +} + +// tree returns the node map for ns/server, creating the root. Caller holds mu. +func (f *fakeAPI) tree(ns, server string) map[string]*node { + key := ns + "/" + server + m, ok := f.trees[key] + if !ok { + m = map[string]*node{"/": {dir: true, mod: fixedTime}} + f.trees[key] = m + } + return m +} + +// seedFile creates a file, and any missing parent folders, before a test runs. +func (f *fakeAPI) seedFile(ns, server, p string, data []byte) { + f.mu.Lock() + defer f.mu.Unlock() + m := f.tree(ns, server) + ensureParents(m, p) + m[p] = &node{data: append([]byte(nil), data...), mod: fixedTime} +} + +// seedDir creates a folder, and any missing parents, before a test runs. +func (f *fakeAPI) seedDir(ns, server, p string) { + f.mu.Lock() + defer f.mu.Unlock() + m := f.tree(ns, server) + ensureParents(m, p) + m[p] = &node{dir: true, mod: fixedTime} +} + +// has reports whether a path exists in ns/server. +func (f *fakeAPI) has(ns, server, p string) bool { + f.mu.Lock() + defer f.mu.Unlock() + _, ok := f.tree(ns, server)[p] + return ok +} + +// fileData returns a committed file's bytes. +func (f *fakeAPI) fileData(ns, server, p string) ([]byte, bool) { + f.mu.Lock() + defer f.mu.Unlock() + n, ok := f.tree(ns, server)[p] + if !ok || n.dir { + return nil, false + } + return n.data, true +} + +// setStreamFail makes every later PUT fail with status code, without committing. +func (f *fakeAPI) setStreamFail(code int) { + f.mu.Lock() + defer f.mu.Unlock() + f.streamFail = code +} + +// snapshot copies the call counters. +func (f *fakeAPI) snapshot() stats { + f.mu.Lock() + defer f.mu.Unlock() + s := f.st + s.ranges = append([]string(nil), f.st.ranges...) + s.streamQueries = append([]url.Values(nil), f.st.streamQueries...) + s.deletes = append([]url.Values(nil), f.st.deletes...) + return s +} + +// ensureParents creates the folders above p that do not exist yet. +func ensureParents(m map[string]*node, p string) { + for d := path.Dir(p); ; d = path.Dir(d) { + if _, ok := m[d]; !ok { + m[d] = &node{dir: true, mod: fixedTime} + } + if d == "/" || d == "." { + return + } + } +} + +// hasChildren reports whether anything lies below dir. +func hasChildren(m map[string]*node, dir string) bool { + prefix := strings.TrimSuffix(dir, "/") + "/" + for k := range m { + if k != dir && strings.HasPrefix(k, prefix) { + return true + } + } + return false +} + +// wireEntry is the JSON shape of the API's Entry. +type wireEntry struct { + Name string `json:"name"` + Path string `json:"path"` + Size int64 `json:"size"` + Mode string `json:"mode"` + Dir bool `json:"dir"` + ModTime string `json:"modTime"` +} + +func toWire(p string, n *node) wireEntry { + mode := "-rw-r--r--" + if n.dir { + mode = "drwxr-xr-x" + } + name := path.Base(p) + if p == "/" { + name = "" + } + mt := n.mod + if mt.IsZero() { + mt = fixedTime + } + return wireEntry{Name: name, Path: p, Size: int64(len(n.data)), Mode: mode, Dir: n.dir, ModTime: mt.UTC().Format(time.RFC3339)} +} + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +} + +// serve routes the SFTP-facing API paths. It holds mu for the whole request. +func (f *fakeAPI) serve(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + if r.Header.Get("Authorization") != "Bearer "+testToken { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.URL.Path == "/sftp/v1/servers" { + f.st.serversCalls++ + items := f.servers + if items == nil { + items = []apiclient.ServerRef{} + } + writeJSON(w, map[string]any{"items": items}) + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") + if len(parts) != 4 || parts[0] != "servers" || parts[2] != "files" { + http.NotFound(w, r) + return + } + q := r.URL.Query() + if q.Has("cluster") { + http.Error(w, "cluster is not a client parameter", http.StatusBadRequest) + return + } + ns := q.Get("namespace") + if ns == "" { + ns = testNS + } + server := parts[1] + if !f.serverExists(ns, server) { + http.Error(w, "not found", http.StatusNotFound) + return + } + want := map[string]string{ + "list": http.MethodGet, "stat": http.MethodGet, "download": http.MethodGet, + "mkdir": http.MethodPost, "rename": http.MethodPost, + "delete": http.MethodDelete, "stream": http.MethodPut, + }[parts[3]] + if want == "" { + http.NotFound(w, r) + return + } + if r.Method != want { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + p := path.Clean("/" + q.Get("path")) + m := f.tree(ns, server) + switch parts[3] { + case "list": + f.list(w, m, p) + case "stat": + n, ok := m[p] + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return + } + writeJSON(w, toWire(p, n)) + case "download": + f.download(w, r, m, p) + case "mkdir": + f.mkdir(w, m, p) + case "rename": + f.rename(w, r, m) + case "delete": + f.delete(w, m, p, q) + case "stream": + f.stream(w, r, m, p, q) + } +} + +func (f *fakeAPI) serverExists(ns, server string) bool { + for _, s := range f.servers { + if s.Namespace == ns && s.Server == server { + return true + } + } + return false +} + +func (f *fakeAPI) list(w http.ResponseWriter, m map[string]*node, p string) { + n, ok := m[p] + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return + } + if !n.dir { + http.Error(w, "not a directory", http.StatusBadRequest) + return + } + out := []wireEntry{} + for k, c := range m { + if k == "/" || path.Dir(k) != p || strings.HasPrefix(path.Base(k), ".") { + continue + } + out = append(out, toWire(k, c)) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + writeJSON(w, out) +} + +func (f *fakeAPI) download(w http.ResponseWriter, r *http.Request, m map[string]*node, p string) { + n, ok := m[p] + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return + } + if n.dir { + http.Error(w, "is a directory", http.StatusBadRequest) + return + } + f.st.downloads++ + f.st.ranges = append(f.st.ranges, r.Header.Get("Range")) + http.ServeContent(w, r, path.Base(p), n.mod, bytes.NewReader(n.data)) +} + +func (f *fakeAPI) mkdir(w http.ResponseWriter, m map[string]*node, p string) { + if n, ok := m[p]; ok { + if n.dir { + w.WriteHeader(http.StatusNoContent) + return + } + http.Error(w, "exists", http.StatusConflict) + return + } + ensureParents(m, p) + m[p] = &node{dir: true, mod: time.Now()} + w.WriteHeader(http.StatusNoContent) +} + +func (f *fakeAPI) rename(w http.ResponseWriter, r *http.Request, m map[string]*node) { + var in struct { + From string `json:"from"` + To string `json:"to"` + Overwrite bool `json:"overwrite"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + http.Error(w, "bad body", http.StatusBadRequest) + return + } + from := path.Clean("/" + in.From) + to := path.Clean("/" + in.To) + if from == "/" || to == "/" { + http.Error(w, "root", http.StatusBadRequest) + return + } + if _, ok := m[from]; !ok { + http.Error(w, "not found", http.StatusNotFound) + return + } + if _, ok := m[to]; ok { + if !in.Overwrite { + http.Error(w, "exists", http.StatusConflict) + return + } + for k := range m { + if k == to || strings.HasPrefix(k, to+"/") { + delete(m, k) + } + } + } + var moved []string + for k := range m { + if k == from || strings.HasPrefix(k, from+"/") { + moved = append(moved, k) + } + } + for _, k := range moved { + n := m[k] + delete(m, k) + m[to+strings.TrimPrefix(k, from)] = n + } + w.WriteHeader(http.StatusNoContent) +} + +func (f *fakeAPI) delete(w http.ResponseWriter, m map[string]*node, p string, q url.Values) { + if p == "/" { + http.Error(w, "root", http.StatusBadRequest) + return + } + n, ok := m[p] + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return + } + if n.dir && hasChildren(m, p) { + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + delete(m, p) + f.st.deletes = append(f.st.deletes, q) + w.WriteHeader(http.StatusNoContent) +} + +// stream reads the whole body, then commits it. It commits nothing when the +// body ends in an error, which is how an aborted upload stays uncommitted. +func (f *fakeAPI) stream(w http.ResponseWriter, r *http.Request, m map[string]*node, p string, q url.Values) { + off, err := strconv.ParseInt(q.Get("offset"), 10, 64) + if err != nil || off < 0 { + http.Error(w, "bad offset", http.StatusBadRequest) + return + } + if n, ok := m[p]; ok && n.dir { + http.Error(w, "is a directory", http.StatusBadRequest) + return + } + var prefix []byte + if off > 0 { + n, ok := m[p] + if !ok || off > int64(len(n.data)) { + http.Error(w, "bad offset", http.StatusRequestedRangeNotSatisfiable) + return + } + prefix = n.data[:off] + } + f.st.streamQueries = append(f.st.streamQueries, q) + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "body read", http.StatusBadRequest) + return + } + if f.streamFail != 0 { + http.Error(w, "injected", f.streamFail) + return + } + data := append(append([]byte(nil), prefix...), body...) + ensureParents(m, p) + m[p] = &node{data: data, mod: time.Now()} + w.WriteHeader(http.StatusNoContent) +} + +// fixture is one FS on top of a fresh fake API. +type fixture struct { + api *fakeAPI + fs *FS +} + +func newFixture(t *testing.T, target *apiclient.Target, opts Options, servers []apiclient.ServerRef) fixture { + t.Helper() + api := newFakeAPI(t, servers) + sess := apiclient.Session{Token: testToken, User: "Alice", Target: target} + return fixture{api: api, fs: New(api.client(t), sess, opts)} +} + +// opReq is a request for a path-only operation. +func opReq(method, p string) *sftp.Request { + return &sftp.Request{Method: method, Filepath: p} +} + +// openReq is a Put or Get request carrying open flags. +func openReq(p string, flags uint32) *sftp.Request { + return &sftp.Request{Method: "Put", Filepath: p, Flags: flags} +} + +// listNames lists everything a ListerAt holds, following pkg/sftp's paging. +func listNames(t *testing.T, l sftp.ListerAt) []os.FileInfo { + t.Helper() + var out []os.FileInfo + buf := make([]os.FileInfo, 4) + var off int64 + for { + n, err := l.ListAt(buf, off) + out = append(out, buf[:n]...) + off += int64(n) + if errors.Is(err, io.EOF) { + return out + } + if err != nil { + t.Fatalf("ListAt: %v", err) + } + if n == 0 { + t.Fatal("ListAt made no progress") + } + } +} + +// names returns the names of a ListerAt's entries. +func names(t *testing.T, l sftp.ListerAt) []string { + t.Helper() + var out []string + for _, fi := range listNames(t, l) { + out = append(out, fi.Name()) + } + return out +} diff --git a/internal/vfs/limiter.go b/internal/vfs/limiter.go new file mode 100644 index 0000000..563b114 --- /dev/null +++ b/internal/vfs/limiter.go @@ -0,0 +1,48 @@ +package vfs + +import ( + "strings" + "sync" +) + +// Limiter caps concurrent transfers per user across every connection the +// user holds. Acquire never blocks: a transfer over the cap fails at once. +// A nil Limiter, or one built with a cap of zero or less, is unlimited. +type Limiter struct { + mu sync.Mutex + max int + active map[string]int +} + +// NewLimiter returns a Limiter that allows maxPerUser concurrent transfers +// for each user. +func NewLimiter(maxPerUser int) *Limiter { + return &Limiter{max: maxPerUser, active: make(map[string]int)} +} + +// Acquire takes one transfer slot for user. It returns a release function +// that gives the slot back; release is safe to call more than once. ok is +// false when the user is at the cap, and release is then nil. +func (l *Limiter) Acquire(user string) (release func(), ok bool) { + if l == nil || l.max <= 0 { + return func() {}, true + } + key := strings.ToLower(user) + l.mu.Lock() + defer l.mu.Unlock() + if l.active[key] >= l.max { + return nil, false + } + l.active[key]++ + var once sync.Once + return func() { + once.Do(func() { + l.mu.Lock() + defer l.mu.Unlock() + l.active[key]-- + if l.active[key] <= 0 { + delete(l.active, key) + } + }) + }, true +} diff --git a/internal/vfs/ops.go b/internal/vfs/ops.go new file mode 100644 index 0000000..ce55a5a --- /dev/null +++ b/internal/vfs/ops.go @@ -0,0 +1,168 @@ +package vfs + +import ( + "context" + "errors" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// Filelist serves List (directory listing) and Stat requests. Readlink is not +// supported. +func (f *FS) Filelist(r *sftp.Request) (sftp.ListerAt, error) { + ctx := r.Context() + switch r.Method { + case "List": + loc, err := f.resolve(ctx, r.Filepath) + if err != nil { + return nil, err + } + infos, err := f.listLocation(ctx, loc) + if err != nil { + return nil, err + } + return infosToLister(infos), nil + case "Stat": + return f.stat(ctx, r.Filepath) + default: + return nil, sftp.ErrSSHFxOpUnsupported + } +} + +// Lstat answers Lstat requests. Symlinks are reported as themselves, which is +// what the API's stat does. +func (f *FS) Lstat(r *sftp.Request) (sftp.ListerAt, error) { + return f.stat(r.Context(), r.Filepath) +} + +// stat returns a one-entry lister for p. +func (f *FS) stat(ctx context.Context, p string) (sftp.ListerAt, error) { + loc, err := f.resolve(ctx, p) + if err != nil { + return nil, err + } + info, err := f.statLocation(ctx, loc) + if err != nil { + return nil, err + } + return listerAt{info}, nil +} + +// Filecmd handles Setstat, Rename, Mkdir, Rmdir and Remove. Link, Symlink and +// Readlink are refused. +func (f *FS) Filecmd(r *sftp.Request) error { + ctx := r.Context() + switch r.Method { + case "Setstat": + return f.setstat(ctx, r) + case "Rename": + return f.rename(ctx, r.Filepath, r.Target, false) + case "Mkdir": + return f.mkdir(ctx, r.Filepath) + case "Rmdir": + return f.rmdir(ctx, r.Filepath) + case "Remove": + return f.remove(ctx, r.Filepath) + default: + return sftp.ErrSSHFxOpUnsupported + } +} + +// PosixRename implements sftp.PosixRenameFileCmder. The POSIX extension +// replaces an existing target. +func (f *FS) PosixRename(r *sftp.Request) error { + return f.rename(r.Context(), r.Filepath, r.Target, true) +} + +// setstat accepts mode and time changes as no-ops, after checking the path +// exists. Owner changes are refused, and so is truncation through attributes. +func (f *FS) setstat(ctx context.Context, r *sftp.Request) error { + loc, err := f.resolve(ctx, r.Filepath) + if err != nil { + return err + } + flags := r.AttrFlags() + if flags.UidGid { + return sftp.ErrSSHFxPermissionDenied + } + if flags.Size { + return sftp.ErrSSHFxOpUnsupported + } + if loc.virtual() { + return nil + } + if _, err := f.filesFor(loc).Stat(ctx, loc.rest); err != nil { + return f.fail("setstat", err) + } + return nil +} + +// rename moves from to to inside one server. Virtual nodes and the server root +// are refused, and so is a move between servers. +func (f *FS) rename(ctx context.Context, from, to string, overwrite bool) error { + src, err := f.resolveWrite(ctx, from) + if err != nil { + return err + } + dst, err := f.resolveWrite(ctx, to) + if err != nil { + return err + } + if !src.sameServer(dst) { + return sftp.ErrSSHFxOpUnsupported + } + return f.fail("rename", f.filesFor(src).Rename(ctx, src.rest, dst.rest, overwrite)) +} + +// mkdir creates a directory. An existing path, file or directory, is an error. +func (f *FS) mkdir(ctx context.Context, p string) error { + loc, err := f.resolveWrite(ctx, p) + if err != nil { + return err + } + files := f.filesFor(loc) + _, err = files.Stat(ctx, loc.rest) + switch { + case err == nil: + return failure("file exists") + case !errors.Is(err, apiclient.ErrNotFound): + return f.fail("mkdir", err) + } + return f.fail("mkdir", files.Mkdir(ctx, loc.rest)) +} + +// rmdir removes an empty directory. A non-empty directory fails, because the +// API delete is never recursive. +func (f *FS) rmdir(ctx context.Context, p string) error { + loc, err := f.resolveWrite(ctx, p) + if err != nil { + return err + } + files := f.filesFor(loc) + e, err := files.Stat(ctx, loc.rest) + if err != nil { + return f.fail("rmdir", err) + } + if !e.Dir { + return failure("not a directory") + } + return f.fail("rmdir", files.Delete(ctx, loc.rest)) +} + +// remove deletes a file. A directory is refused; use Rmdir for those. +func (f *FS) remove(ctx context.Context, p string) error { + loc, err := f.resolveWrite(ctx, p) + if err != nil { + return err + } + files := f.filesFor(loc) + e, err := files.Stat(ctx, loc.rest) + if err != nil { + return f.fail("remove", err) + } + if e.Dir { + return failure("is a directory") + } + return f.fail("remove", files.Delete(ctx, loc.rest)) +} diff --git a/internal/vfs/read.go b/internal/vfs/read.go new file mode 100644 index 0000000..dbca83f --- /dev/null +++ b/internal/vfs/read.go @@ -0,0 +1,225 @@ +package vfs + +import ( + "context" + "errors" + "io" + "sync" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// Fileread opens a file for reading. The file is stat'ed first so a missing +// path, a directory or a virtual node fails at open with the right status. +// The transfer slot taken here is released by Close. +func (f *FS) Fileread(r *sftp.Request) (io.ReaderAt, error) { + ctx := r.Context() + loc, err := f.resolve(ctx, r.Filepath) + if err != nil { + return nil, err + } + if loc.virtual() { + return nil, failure("is a directory") + } + release, ok := f.limiter.Acquire(f.user) + if !ok { + return nil, failure("too many concurrent transfers") + } + files := f.filesFor(loc) + e, err := files.Stat(ctx, loc.rest) + if err != nil { + release() + return nil, f.fail("read stat", err) + } + if e.Dir { + release() + return nil, failure("is a directory") + } + return &readerAt{ + ctx: ctx, + fs: f, + files: files, + path: loc.rest, + size: e.Size, + release: release, + }, nil +} + +// readerAt serves ReadAt over one streamed download. Contiguous reads reuse +// the open body. A read at any other offset reopens the download there with +// a Range request. The file is never buffered whole. +type readerAt struct { + ctx context.Context + fs *FS + files *apiclient.Files + path string + size int64 // size at open; the stream is not reopened past it + release func() + + mu sync.Mutex // guards the fields below and serialises reads + cur io.ReadCloser + pos int64 // offset the next byte of cur comes from + closed bool + held []heldRange // bytes read past while jumping ahead, for late reads + heldBytes int +} + +// Limits for pipelined reads. pkg/sftp handles read packets on a pool of +// workers, so a client's sequential reads can arrive slightly out of order. +// A read a short way ahead of the stream skips forward and keeps the skipped +// bytes, so the read that arrives late is served from memory instead of +// reopening the download. +const ( + maxSkipBytes = 2 << 20 // largest forward gap bridged on the open stream + maxHeldBytes = 4 << 20 // cap on skipped bytes kept +) + +// heldRange is a run of file bytes read past and kept for a later ReadAt. +type heldRange struct { + off int64 + data []byte +} + +// ReadAt implements io.ReaderAt. A short result always comes with a non-nil +// error, as the ReaderAt contract requires. +func (r *readerAt) ReadAt(p []byte, off int64) (int, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return 0, failure("file closed") + } + if off < 0 { + return 0, failure("negative offset") + } + if len(p) == 0 { + return 0, nil + } + if r.takeHeld(p, off) { + return len(p), nil + } + n := 0 + retried := false + for n < len(p) { + pos := off + int64(n) + if r.size >= 0 && pos >= r.size { + return n, io.EOF + } + if r.cur != nil && pos > r.pos && pos-r.pos <= maxSkipBytes { + r.skipTo(pos) + } + if r.cur == nil || r.pos != pos { + if err := r.open(pos); err != nil { + return n, err + } + } + m, err := r.cur.Read(p[n:]) + n += m + r.pos += int64(m) + count(r.fs.onBytes, "read", m) + if err == nil { + continue + } + if errors.Is(err, io.EOF) && (r.size < 0 || r.pos >= r.size) { + if n == len(p) { + return n, nil + } + return n, io.EOF + } + // The stream broke, or ended before the size seen at open. Retry once + // from the current offset; a second failure is reported. + r.dropCur() + if retried { + return n, failure("transfer interrupted") + } + retried = true + } + return n, nil +} + +// skipTo reads the open stream forward to pos and keeps the bytes it passes. +// If the stream breaks, it is dropped and the caller reopens at pos. +func (r *readerAt) skipTo(pos int64) { + gap := make([]byte, pos-r.pos) + m, err := io.ReadFull(r.cur, gap) + count(r.fs.onBytes, "read", m) + if err != nil { + r.dropCur() + return + } + r.hold(r.pos, gap) + r.pos = pos +} + +// hold keeps skipped bytes, dropping the oldest when over the cap. +func (r *readerAt) hold(off int64, data []byte) { + r.held = append(r.held, heldRange{off: off, data: data}) + r.heldBytes += len(data) + for r.heldBytes > maxHeldBytes && len(r.held) > 0 { + r.heldBytes -= len(r.held[0].data) + r.held = r.held[1:] + } +} + +// takeHeld serves p at off from one held range that covers all of it, and +// keeps whatever is left of that range. It reports whether it served p. +func (r *readerAt) takeHeld(p []byte, off int64) bool { + end := off + int64(len(p)) + for i, h := range r.held { + hEnd := h.off + int64(len(h.data)) + if off < h.off || end > hEnd { + continue + } + copy(p, h.data[off-h.off:end-h.off]) + rest := make([]heldRange, 0, len(r.held)+1) + rest = append(rest, r.held[:i]...) + if off > h.off { + rest = append(rest, heldRange{off: h.off, data: h.data[:off-h.off]}) + } + if end < hEnd { + rest = append(rest, heldRange{off: end, data: h.data[end-h.off:]}) + } + rest = append(rest, r.held[i+1:]...) + r.held = rest + r.heldBytes -= len(p) + return true + } + return false +} + +// open starts a download at pos. An offset the API rejects with 416 is end of +// file, not an error. +func (r *readerAt) open(pos int64) error { + r.dropCur() + body, err := r.files.Download(r.ctx, r.path, pos) + if err != nil { + if errors.Is(err, apiclient.ErrBadOffset) { + return io.EOF + } + return r.fs.fail("read", err) + } + r.cur = body + r.pos = pos + return nil +} + +// dropCur closes the current download body, if any. +func (r *readerAt) dropCur() { + if r.cur != nil { + _ = r.cur.Close() + r.cur = nil + } +} + +// Close ends the read and releases the transfer slot. It is idempotent. +func (r *readerAt) Close() error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return nil + } + r.closed = true + r.dropCur() + r.release() + return nil +} diff --git a/internal/vfs/read_test.go b/internal/vfs/read_test.go new file mode 100644 index 0000000..70113db --- /dev/null +++ b/internal/vfs/read_test.go @@ -0,0 +1,420 @@ +package vfs + +import ( + "bytes" + "context" + "errors" + "io" + "strconv" + "testing" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +func TestTreeRootListsDefaultServersAndNamespaces(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + lister, err := fx.fs.Filelist(opReq("List", "/")) + if err != nil { + t.Fatalf("list root: %v", err) + } + got := names(t, lister) + want := []string{"_namespaces", "survival"} + if !equalStrings(got, want) { + t.Fatalf("root listing = %v, want %v", got, want) + } + if n := fx.api.snapshot().serversCalls; n < 1 { + t.Fatalf("servers calls = %d, want at least 1", n) + } +} + +func TestTreeNamespaceFolders(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(otherNS, "modded", "/mods/a.jar", []byte("jar")) + + ns, err := fx.fs.Filelist(opReq("List", "/_namespaces")) + if err != nil { + t.Fatalf("list _namespaces: %v", err) + } + if got := names(t, ns); !equalStrings(got, []string{otherNS}) { + t.Fatalf("_namespaces = %v, want [%s]", got, otherNS) + } + + servers, err := fx.fs.Filelist(opReq("List", "/_namespaces/"+otherNS)) + if err != nil { + t.Fatalf("list namespace: %v", err) + } + if got := names(t, servers); !equalStrings(got, []string{"modded"}) { + t.Fatalf("namespace servers = %v, want [modded]", got) + } + + if _, err := fx.fs.Filelist(opReq("List", "/_namespaces/nope")); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Fatalf("unknown namespace err = %v, want no such file", err) + } + + st, err := fx.fs.Filelist(opReq("Stat", "/_namespaces/"+otherNS+"/modded/mods/a.jar")) + if err != nil { + t.Fatalf("stat nested file: %v", err) + } + if info := listNames(t, st); len(info) != 1 || info[0].Size() != 3 { + t.Fatalf("nested stat = %+v, want one entry of size 3", info) + } +} + +func TestTargetLoginIsRootedAtServer(t *testing.T) { + target := &apiclient.Target{Namespace: testNS, Server: "survival"} + fx := newFixture(t, target, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/world/level.dat", []byte("x")) + + lister, err := fx.fs.Filelist(opReq("List", "/")) + if err != nil { + t.Fatalf("list target root: %v", err) + } + if got := names(t, lister); !equalStrings(got, []string{"world"}) { + t.Fatalf("target root = %v, want [world]", got) + } + if n := fx.api.snapshot().serversCalls; n != 0 { + t.Fatalf("target login called Servers %d times, want 0", n) + } +} + +func TestResolvePathTable(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + ctx := context.Background() + cases := []struct { + in string + kind kind + ns string + server string + rest string + }{ + {"/", kindRoot, "", "", ""}, + {"/survival", kindServer, testNS, "survival", "/"}, + {"/survival/a/b/c", kindRemote, testNS, "survival", "/a/b/c"}, + {"/survival/a/../b", kindRemote, testNS, "survival", "/b"}, + {"/_namespaces", kindNamespaces, "", "", ""}, + {"/_namespaces/" + otherNS, kindNamespace, otherNS, "", ""}, + {"/_namespaces/" + otherNS + "/modded/x", kindRemote, otherNS, "modded", "/x"}, + } + for _, c := range cases { + loc, err := fx.fs.resolve(ctx, c.in) + if err != nil { + t.Errorf("resolve(%q): %v", c.in, err) + continue + } + if loc.kind != c.kind || loc.namespace != c.ns || loc.server != c.server || loc.rest != c.rest { + t.Errorf("resolve(%q) = %+v, want kind=%d ns=%q server=%q rest=%q", c.in, loc, c.kind, c.ns, c.server, c.rest) + } + } +} + +func TestResolveRefusesUnknownAndHidden(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + ctx := context.Background() + for _, in := range []string{"../escape", "/unknown", "/survival/.secret", "/.hidden/x"} { + if _, err := fx.fs.resolve(ctx, in); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Errorf("resolve(%q) err = %v, want no such file", in, err) + } + } +} + +func TestDotfilesHiddenFromListAndStat(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/cfg/server.properties", []byte("a=1")) + fx.api.seedFile(testNS, "survival", "/cfg/.env", []byte("SECRET=1")) + + lister, err := fx.fs.Filelist(opReq("List", "/survival/cfg")) + if err != nil { + t.Fatalf("list: %v", err) + } + if got := names(t, lister); !equalStrings(got, []string{"server.properties"}) { + t.Fatalf("listing = %v, want only server.properties", got) + } + if _, err := fx.fs.Filelist(opReq("Stat", "/survival/cfg/.env")); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Fatalf("stat dotfile err = %v, want no such file", err) + } + if _, err := fx.fs.Fileread(opReq("Get", "/survival/cfg/.env")); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Fatalf("read dotfile err = %v, want no such file", err) + } + if _, err := fx.fs.Filewrite(openReq("/survival/cfg/.env", fxfWrite|fxfCreat)); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Fatalf("write dotfile err = %v, want permission denied", err) + } +} + +func TestVirtualNodesAreReadOnly(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/a.txt", []byte("a")) + deny := sftp.ErrSSHFxPermissionDenied + checks := map[string]error{ + "mkdir root": fx.fs.Filecmd(opReq("Mkdir", "/")), + "mkdir server": fx.fs.Filecmd(opReq("Mkdir", "/survival")), + "rmdir server": fx.fs.Filecmd(opReq("Rmdir", "/survival")), + "remove server": fx.fs.Filecmd(opReq("Remove", "/survival")), + "rename server": fx.fs.Filecmd(&sftp.Request{Method: "Rename", Filepath: "/survival", Target: "/survival/x"}), + "rename into virtual": fx.fs.Filecmd(&sftp.Request{Method: "Rename", Filepath: "/survival/a.txt", Target: "/_namespaces"}), + } + for name, err := range checks { + if !errors.Is(err, deny) { + t.Errorf("%s: err = %v, want permission denied", name, err) + } + } + if _, err := fx.fs.Filewrite(openReq("/survival", fxfWrite|fxfCreat)); !errors.Is(err, deny) { + t.Errorf("write to server folder: err = %v, want permission denied", err) + } +} + +func TestTargetServerRootIsReadOnly(t *testing.T) { + target := &apiclient.Target{Namespace: testNS, Server: "survival"} + fx := newFixture(t, target, Options{}, testServers) + if err := fx.fs.Filecmd(opReq("Mkdir", "/")); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Fatalf("mkdir / err = %v, want permission denied", err) + } + if err := fx.fs.Filecmd(opReq("Remove", "/")); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Fatalf("remove / err = %v, want permission denied", err) + } +} + +func TestReadWholeFile(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/world/a.txt", []byte("0123456789")) + + r, err := fx.fs.Fileread(opReq("Get", "/survival/world/a.txt")) + if err != nil { + t.Fatalf("open: %v", err) + } + defer closeOrFail(t, r) + buf := make([]byte, 10) + n, err := r.ReadAt(buf, 0) + if err != nil || n != 10 || string(buf) != "0123456789" { + t.Fatalf("ReadAt = %d %q %v, want 10 bytes", n, buf[:n], err) + } + if _, err := r.ReadAt(buf, 10); !errors.Is(err, io.EOF) { + t.Fatalf("read past end err = %v, want EOF", err) + } +} + +func TestRangedReadAndConnectionReuse(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + data := make([]byte, 64) + for i := range data { + data[i] = byte('a' + i%26) + } + fx.api.seedFile(testNS, "survival", "/big.bin", data) + + r, err := fx.fs.Fileread(opReq("Get", "/survival/big.bin")) + if err != nil { + t.Fatalf("open: %v", err) + } + defer closeOrFail(t, r) + + buf := make([]byte, 4) + if _, err := r.ReadAt(buf, 0); err != nil { + t.Fatalf("read at 0: %v", err) + } + if _, err := r.ReadAt(buf, 4); err != nil { + t.Fatalf("read at 4: %v", err) + } + if got := fx.api.snapshot().downloads; got != 1 { + t.Fatalf("contiguous reads opened %d downloads, want 1", got) + } + + // A short jump ahead is bridged on the open stream, not reopened. + if _, err := r.ReadAt(buf, 20); err != nil { + t.Fatalf("jump read: %v", err) + } + if string(buf) != string(data[20:24]) { + t.Fatalf("jump read = %q, want %q", buf, data[20:24]) + } + if got := fx.api.snapshot().downloads; got != 1 { + t.Fatalf("short jump opened %d downloads, want 1", got) + } + + // The bytes jumped over are kept, so a late read of them is served + // from memory. + if _, err := r.ReadAt(buf, 8); err != nil { + t.Fatalf("late read: %v", err) + } + if string(buf) != string(data[8:12]) { + t.Fatalf("late read = %q, want %q", buf, data[8:12]) + } + if got := fx.api.snapshot().downloads; got != 1 { + t.Fatalf("late read opened %d downloads, want 1", got) + } + + // A read behind the stream that was not kept reopens the download. + if _, err := r.ReadAt(buf, 0); err != nil { + t.Fatalf("read back: %v", err) + } + if got := fx.api.snapshot().downloads; got != 2 { + t.Fatalf("seek back opened %d downloads total, want 2", got) + } +} + +func TestFarSeekReopensWithRange(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + data := pattern(3 << 20) + fx.api.seedFile(testNS, "survival", "/far.bin", data) + r, err := fx.fs.Fileread(opReq("Get", "/survival/far.bin")) + if err != nil { + t.Fatalf("open: %v", err) + } + defer closeOrFail(t, r) + + buf := make([]byte, 16) + if _, err := r.ReadAt(buf, 0); err != nil { + t.Fatalf("read at 0: %v", err) + } + far := int64(3<<20 - 16) + if _, err := r.ReadAt(buf, far); err != nil && !errors.Is(err, io.EOF) { + t.Fatalf("far read: %v", err) + } + if !bytes.Equal(buf, data[far:]) { + t.Fatal("far read returned the wrong bytes") + } + st := fx.api.snapshot() + want := "bytes=" + strconv.FormatInt(far, 10) + "-" + if st.downloads != 2 || st.ranges[1] != want { + t.Fatalf("downloads=%d ranges=%q, want 2 with %s", st.downloads, st.ranges, want) + } +} + +func TestReadShortReadReturnsError(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/short.bin", []byte("abc")) + r, err := fx.fs.Fileread(opReq("Get", "/survival/short.bin")) + if err != nil { + t.Fatalf("open: %v", err) + } + defer closeOrFail(t, r) + buf := make([]byte, 10) + n, err := r.ReadAt(buf, 0) + if n != 3 || !errors.Is(err, io.EOF) { + t.Fatalf("ReadAt past end = %d %v, want 3 and EOF", n, err) + } +} + +func TestReadMissingAndDirectoryFailAtOpen(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedDir(testNS, "survival", "/world") + if _, err := fx.fs.Fileread(opReq("Get", "/survival/missing")); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Fatalf("missing err = %v, want no such file", err) + } + if _, err := fx.fs.Fileread(opReq("Get", "/survival/world")); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("directory err = %v, want failure", err) + } + if _, err := fx.fs.Fileread(opReq("Get", "/survival")); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("virtual dir err = %v, want failure", err) + } +} + +func TestListingSortedDirsFirstAndFiltered(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/d/b.txt", []byte("b")) + fx.api.seedFile(testNS, "survival", "/d/a.txt", []byte("a")) + fx.api.seedFile(testNS, "survival", "/d/.hidden", []byte("h")) + fx.api.seedDir(testNS, "survival", "/d/zdir") + + lister, err := fx.fs.Filelist(opReq("List", "/survival/d")) + if err != nil { + t.Fatalf("list: %v", err) + } + want := []string{"zdir", "a.txt", "b.txt"} + if got := names(t, lister); !equalStrings(got, want) { + t.Fatalf("listing = %v, want %v", got, want) + } +} + +func TestStatVirtualFolderIsDirectory(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + lister, err := fx.fs.Filelist(opReq("Stat", "/survival")) + if err != nil { + t.Fatalf("stat server folder: %v", err) + } + info := listNames(t, lister) + if len(info) != 1 || !info[0].IsDir() || info[0].Name() != "survival" { + t.Fatalf("stat server folder = %+v, want one dir named survival", info) + } +} + +func TestToSFTPMapping(t *testing.T) { + cases := []struct { + name string + in error + want error + }{ + {"nil", nil, nil}, + {"not found", &apiclient.Error{Status: 404, Err: apiclient.ErrNotFound}, sftp.ErrSSHFxNoSuchFile}, + {"permission", &apiclient.Error{Status: 403, Err: apiclient.ErrPermission}, sftp.ErrSSHFxPermissionDenied}, + {"bad request", &apiclient.Error{Status: 400, Err: apiclient.ErrBadRequest}, sftp.ErrSSHFxPermissionDenied}, + {"unauthorized", &apiclient.Error{Status: 401, Err: apiclient.ErrUnauthorized}, sftp.ErrSSHFxPermissionDenied}, + {"exists", &apiclient.Error{Status: 409, Err: apiclient.ErrExists}, sftp.ErrSSHFxFailure}, + {"no space", &apiclient.Error{Status: 507, Err: apiclient.ErrNoSpace}, sftp.ErrSSHFxFailure}, + {"too large", &apiclient.Error{Status: 413, Err: apiclient.ErrTooLarge}, sftp.ErrSSHFxFailure}, + {"bad offset", &apiclient.Error{Status: 416, Err: apiclient.ErrBadOffset}, sftp.ErrSSHFxFailure}, + {"busy", &apiclient.Error{Status: 429, Err: apiclient.ErrBusy}, sftp.ErrSSHFxFailure}, + {"unavailable", &apiclient.Error{Status: 503, Err: apiclient.ErrUnavailable}, sftp.ErrSSHFxFailure}, + {"canceled", context.Canceled, sftp.ErrSSHFxConnectionLost}, + {"deadline", context.DeadlineExceeded, sftp.ErrSSHFxConnectionLost}, + {"status passthrough", sftp.ErrSSHFxOpUnsupported, sftp.ErrSSHFxOpUnsupported}, + {"unknown", errors.New("boom http://secret"), sftp.ErrSSHFxFailure}, + } + for _, c := range cases { + got := toSFTP(c.in) + if !errors.Is(got, c.want) { + t.Errorf("%s: toSFTP(%v) = %v, want %v", c.name, c.in, got, c.want) + } + } + if msg := toSFTP(errors.New("boom http://secret")).Error(); msg != sftp.ErrSSHFxFailure.Error() { + t.Errorf("unknown error leaked text: %q", msg) + } +} + +func TestLimiterCapsPerUser(t *testing.T) { + l := NewLimiter(1) + release, ok := l.Acquire("Alice") + if !ok { + t.Fatal("first acquire refused") + } + if _, ok := l.Acquire("alice"); ok { + t.Fatal("second acquire for the same user (case-insensitive) allowed") + } + if _, ok := l.Acquire("bob"); !ok { + t.Fatal("other user refused") + } + release() + release() + if _, ok := l.Acquire("alice"); !ok { + t.Fatal("acquire after release refused") + } + + var unlimited *Limiter + if _, ok := unlimited.Acquire("x"); !ok { + t.Fatal("nil limiter refused") + } +} + +// equalStrings reports whether two string slices hold the same values in order. +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// closeOrFail closes a handle returned by Fileread or Filewrite and fails the +// test on error. Both handle types implement io.Closer. +func closeOrFail(t *testing.T, handle any) { + t.Helper() + c, ok := handle.(io.Closer) + if !ok { + t.Fatalf("handle %T is not an io.Closer", handle) + } + if err := c.Close(); err != nil { + t.Errorf("close: %v", err) + } +} diff --git a/internal/vfs/vfs.go b/internal/vfs/vfs.go new file mode 100644 index 0000000..6726d2e --- /dev/null +++ b/internal/vfs/vfs.go @@ -0,0 +1,472 @@ +// Package vfs presents Gameplane game servers as an SFTP file tree for one +// authenticated connection. Every file operation is forwarded to the Gameplane +// API as the signed-in user; the package never reads a game volume itself. +// +// Layout for a login without a target (tree login): +// +// //... servers in the default namespace +// /_namespaces///... servers in other namespaces +// +// Only the server folders and their contents are writable. The root, the +// _namespaces folders and each server's top folder are read-only virtual +// directories. A login with a target ("server" or "namespace/server") is +// rooted at that server, and its root is the server's files. +package vfs + +import ( + "context" + "io" + "io/fs" + "log/slog" + "os" + "path" + "slices" + "strings" + "sync" + "time" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// DefaultNamespace is the namespace the API uses when a request names none. +// It matches the API's scope.DefaultNamespace. +const DefaultNamespace = "gameplane-games" + +const ( + namespacesDir = "_namespaces" + serverCacheTTL = 5 * time.Second +) + +// API is the part of *apiclient.Client the file system uses. +type API interface { + Servers(ctx context.Context, token string) ([]apiclient.ServerRef, error) + Files(token, namespace, server string) *apiclient.Files +} + +// Options configures an FS. The zero value is usable. +type Options struct { + // DefaultNamespace is the namespace whose servers appear at the top of a + // tree login. Empty means DefaultNamespace. + DefaultNamespace string + // Limiter caps concurrent transfers per user. Nil means unlimited. + Limiter *Limiter + // OnBytes is called with "read" or "write" and the bytes moved. May be nil. + OnBytes func(direction string, n int) + // Logger receives debug logs. Nil discards them. + Logger *slog.Logger +} + +// FS is the virtual file system of one authenticated SSH connection. It is +// safe for concurrent use by the SFTP request workers. +type FS struct { + api API + token string + user string + target *apiclient.Target + started time.Time + defNS string + limiter *Limiter + onBytes func(direction string, n int) + log *slog.Logger + + mu sync.Mutex + loaded bool + servers []apiclient.ServerRef + loadedAt time.Time +} + +// New returns the file system for session. The session token is used for +// every API call the FS makes. +func New(api API, session apiclient.Session, opts Options) *FS { + ns := opts.DefaultNamespace + if ns == "" { + ns = DefaultNamespace + } + lg := opts.Logger + if lg == nil { + lg = slog.New(slog.DiscardHandler) + } + return &FS{ + api: api, + token: session.Token, + user: strings.ToLower(session.User), + target: session.Target, + started: time.Now(), + defNS: ns, + limiter: opts.Limiter, + onBytes: opts.OnBytes, + log: lg, + } +} + +// Compile-time checks that FS provides the optional pkg/sftp interfaces. +var ( + _ sftp.FileReader = (*FS)(nil) + _ sftp.FileWriter = (*FS)(nil) + _ sftp.FileCmder = (*FS)(nil) + _ sftp.PosixRenameFileCmder = (*FS)(nil) + _ sftp.FileLister = (*FS)(nil) + _ sftp.LstatFileLister = (*FS)(nil) + _ sftp.TransferError = (*writer)(nil) + _ io.ReaderAt = (*readerAt)(nil) + _ io.Closer = (*readerAt)(nil) + _ io.WriterAt = (*writer)(nil) + _ io.Closer = (*writer)(nil) +) + +// Handlers returns the pkg/sftp handler set backed by this FS. +func (f *FS) Handlers() sftp.Handlers { + return sftp.Handlers{FileGet: f, FilePut: f, FileCmd: f, FileList: f} +} + +// kind classifies a resolved path. +type kind int + +const ( + kindRoot kind = iota // "/" of a tree login (virtual) + kindNamespaces // "/_namespaces" (virtual) + kindNamespace // "/_namespaces/" (virtual) + kindServer // a server's top folder in a tree login (virtual, lists via API) + kindRemote // a path inside a server +) + +// location is a resolved path. +type location struct { + kind kind + namespace string + server string + // rest is the absolute path on the server ("/" for the server root). It is + // empty for the purely virtual kinds. + rest string +} + +// virtual reports whether the location is a synthetic directory that the API +// does not hold. Stat answers those without an API call. +func (l location) virtual() bool { return l.kind != kindRemote } + +// writable reports whether create, rename and remove may apply here. The +// server root and every virtual node are read-only. +func (l location) writable() bool { return l.kind == kindRemote && l.rest != "/" } + +// sameServer reports whether two locations live in the same server. +func (l location) sameServer(o location) bool { + return l.kind == kindRemote && o.kind == kindRemote && + l.namespace == o.namespace && l.server == o.server +} + +// splitParts returns the components of a clean absolute path. +func splitParts(clean string) []string { + trimmed := strings.Trim(clean, "/") + if trimmed == "" { + return nil + } + return strings.Split(trimmed, "/") +} + +// hiddenPath reports whether any component of the clean path starts with a +// dot. Such files are never listed, read or written through SFTP. +func hiddenPath(clean string) bool { + for _, part := range splitParts(clean) { + if strings.HasPrefix(part, ".") { + return true + } + } + return false +} + +// resolve maps a client path to a location. Dotted components and unknown +// servers or namespaces give ErrSSHFxNoSuchFile. Other failures come back as +// SFTP statuses too. +func (f *FS) resolve(ctx context.Context, p string) (location, error) { + clean := path.Clean("/" + p) + if hiddenPath(clean) { + return location{}, sftp.ErrSSHFxNoSuchFile + } + if f.target != nil { + return location{kind: kindRemote, namespace: f.target.Namespace, server: f.target.Server, rest: clean}, nil + } + parts := splitParts(clean) + if len(parts) == 0 { + return location{kind: kindRoot}, nil + } + if parts[0] != namespacesDir { + return f.serverLocation(ctx, f.defNS, parts[0], parts[1:]) + } + switch len(parts) { + case 1: + return location{kind: kindNamespaces}, nil + case 2: + ok, err := f.hasNamespace(ctx, parts[1]) + if err != nil { + return location{}, f.fail("servers", err) + } + if !ok { + return location{}, sftp.ErrSSHFxNoSuchFile + } + return location{kind: kindNamespace, namespace: parts[1]}, nil + default: + return f.serverLocation(ctx, parts[1], parts[2], parts[3:]) + } +} + +// serverLocation resolves a server and the rest of the path below it. +func (f *FS) serverLocation(ctx context.Context, ns, server string, rest []string) (location, error) { + ok, err := f.hasServer(ctx, ns, server) + if err != nil { + return location{}, f.fail("servers", err) + } + if !ok { + return location{}, sftp.ErrSSHFxNoSuchFile + } + if len(rest) == 0 { + return location{kind: kindServer, namespace: ns, server: server, rest: "/"}, nil + } + return location{kind: kindRemote, namespace: ns, server: server, rest: "/" + strings.Join(rest, "/")}, nil +} + +// resolveWrite is resolve for a path that will be changed. Dotted names are +// refused as permission errors, and so are virtual nodes and server roots. +func (f *FS) resolveWrite(ctx context.Context, p string) (location, error) { + if hiddenPath(path.Clean("/" + p)) { + return location{}, sftp.ErrSSHFxPermissionDenied + } + loc, err := f.resolve(ctx, p) + if err != nil { + return location{}, err + } + if !loc.writable() { + return location{}, sftp.ErrSSHFxPermissionDenied + } + return loc, nil +} + +// inventory returns the servers the session may reach. It is cached for +// serverCacheTTL unless force is set. +func (f *FS) inventory(ctx context.Context, force bool) ([]apiclient.ServerRef, error) { + f.mu.Lock() + defer f.mu.Unlock() + if !force && f.loaded && time.Since(f.loadedAt) < serverCacheTTL { + return f.servers, nil + } + list, err := f.api.Servers(ctx, f.token) + if err != nil { + return nil, err + } + f.servers = list + f.loaded = true + f.loadedAt = time.Now() + return list, nil +} + +// hasServer reports whether the session may reach ns/server. Tree logins +// only; target logins never call this. +func (f *FS) hasServer(ctx context.Context, ns, server string) (bool, error) { + list, err := f.inventory(ctx, false) + if err != nil { + return false, err + } + for _, s := range list { + if s.Namespace == ns && s.Server == server { + return true, nil + } + } + return false, nil +} + +// hasNamespace reports whether any reachable server is in a namespace other +// than the default one and named ns. +func (f *FS) hasNamespace(ctx context.Context, ns string) (bool, error) { + list, err := f.inventory(ctx, false) + if err != nil { + return false, err + } + for _, s := range list { + if s.Namespace == ns && ns != f.defNS { + return true, nil + } + } + return false, nil +} + +// filesFor returns the API file handle for a remote location. +func (f *FS) filesFor(loc location) *apiclient.Files { + return f.api.Files(f.token, loc.namespace, loc.server) +} + +// virtualInfo describes a synthetic directory. +func (f *FS) virtualInfo(name string) fileInfo { + return fileInfo{name: name, mode: fs.ModeDir | 0o755, modTime: f.started} +} + +// statLocation answers a stat for a location. Virtual nodes never call the API. +func (f *FS) statLocation(ctx context.Context, loc location) (fileInfo, error) { + switch loc.kind { + case kindRoot: + return f.virtualInfo("/"), nil + case kindNamespaces: + return f.virtualInfo(namespacesDir), nil + case kindNamespace: + return f.virtualInfo(loc.namespace), nil + case kindServer: + return f.virtualInfo(loc.server), nil + default: + e, err := f.filesFor(loc).Stat(ctx, loc.rest) + if err != nil { + return fileInfo{}, f.fail("stat", err) + } + info := entryInfo(e) + if info.name == "" || info.name == "." { + info.name = path.Base(loc.rest) + } + return info, nil + } +} + +// listLocation lists a directory location. Dotted names are filtered out. +func (f *FS) listLocation(ctx context.Context, loc location) ([]fileInfo, error) { + switch loc.kind { + case kindRoot: + list, err := f.inventory(ctx, true) + if err != nil { + return nil, f.fail("list", err) + } + var out []fileInfo + seenNS := false + for _, s := range list { + if s.Namespace == f.defNS { + out = append(out, f.virtualInfo(s.Server)) + } else { + seenNS = true + } + } + if seenNS { + out = append(out, f.virtualInfo(namespacesDir)) + } + return sortInfos(out), nil + case kindNamespaces: + list, err := f.inventory(ctx, false) + if err != nil { + return nil, f.fail("list", err) + } + var out []fileInfo + seen := map[string]bool{} + for _, s := range list { + if s.Namespace != f.defNS && !seen[s.Namespace] { + seen[s.Namespace] = true + out = append(out, f.virtualInfo(s.Namespace)) + } + } + return sortInfos(out), nil + case kindNamespace: + list, err := f.inventory(ctx, false) + if err != nil { + return nil, f.fail("list", err) + } + var out []fileInfo + for _, s := range list { + if s.Namespace == loc.namespace { + out = append(out, f.virtualInfo(s.Server)) + } + } + return sortInfos(out), nil + default: + entries, err := f.filesFor(loc).List(ctx, loc.rest) + if err != nil { + return nil, f.fail("list", err) + } + out := make([]fileInfo, 0, len(entries)) + for _, e := range entries { + info := entryInfo(e) + if strings.HasPrefix(info.name, ".") { + continue + } + out = append(out, info) + } + return sortInfos(out), nil + } +} + +// sortInfos orders directories first, then by name, so listings are stable. +func sortInfos(in []fileInfo) []fileInfo { + slices.SortFunc(in, func(a, b fileInfo) int { + if a.IsDir() != b.IsDir() { + if a.IsDir() { + return -1 + } + return 1 + } + return strings.Compare(a.name, b.name) + }) + return in +} + +// fileInfo is an os.FileInfo for one entry. +type fileInfo struct { + name string + size int64 + mode fs.FileMode + modTime time.Time +} + +// Name implements os.FileInfo. +func (i fileInfo) Name() string { return i.name } + +// Size implements os.FileInfo. +func (i fileInfo) Size() int64 { return i.size } + +// Mode implements os.FileInfo. +func (i fileInfo) Mode() fs.FileMode { return i.mode } + +// ModTime implements os.FileInfo. +func (i fileInfo) ModTime() time.Time { return i.modTime } + +// IsDir implements os.FileInfo. +func (i fileInfo) IsDir() bool { return i.mode.IsDir() } + +// Sys implements os.FileInfo. It is nil, so pkg/sftp reports uid and gid 0. +func (i fileInfo) Sys() any { return nil } + +// entryInfo converts an API entry to a fileInfo. +func entryInfo(e apiclient.Entry) fileInfo { + mode := e.FileMode() + if e.Dir { + mode |= os.ModeDir + } + name := e.Name + if name == "" { + name = path.Base(e.Path) + } + return fileInfo{name: name, size: e.Size, mode: mode, modTime: e.ModTime} +} + +// listerAt serves a slice of infos to pkg/sftp in pieces. +type listerAt []os.FileInfo + +// ListAt implements sftp.ListerAt. It returns io.EOF with the last entries. +func (l listerAt) ListAt(ls []os.FileInfo, off int64) (int, error) { + if off < 0 || off >= int64(len(l)) { + return 0, io.EOF + } + n := copy(ls, l[off:]) + if off+int64(n) >= int64(len(l)) { + return n, io.EOF + } + return n, nil +} + +// infosToLister converts infos to a sftp.ListerAt. +func infosToLister(in []fileInfo) listerAt { + out := make(listerAt, len(in)) + for i, info := range in { + out[i] = info + } + return out +} + +// count reports bytes moved in one direction when a hook is set. +func count(fn func(string, int), direction string, n int) { + if fn != nil && n > 0 { + fn(direction, n) + } +} diff --git a/internal/vfs/write.go b/internal/vfs/write.go new file mode 100644 index 0000000..e83227a --- /dev/null +++ b/internal/vfs/write.go @@ -0,0 +1,323 @@ +package vfs + +import ( + "context" + "errors" + "io" + "strings" + "sync" + "sync/atomic" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// errTransferAborted is the reason a pipe is closed when an upload is +// abandoned. The API sees a broken body and commits nothing. +var errTransferAborted = errors.New("transfer aborted") + +// Filewrite opens a file for writing. Creating, replacing and resuming an +// existing file at an offset are supported; appending is not. +func (f *FS) Filewrite(r *sftp.Request) (io.WriterAt, error) { + ctx := r.Context() + flags := r.Pflags() + if flags.Append { + return nil, sftp.ErrSSHFxOpUnsupported + } + loc, err := f.resolveWrite(ctx, r.Filepath) + if err != nil { + return nil, err + } + files := f.filesFor(loc) + exists := true + e, err := files.Stat(ctx, loc.rest) + switch { + case errors.Is(err, apiclient.ErrNotFound): + exists = false + case err != nil: + return nil, f.fail("write stat", err) + case e.Dir: + return nil, failure("is a directory") + } + if exists && flags.Excl { + return nil, failure("file exists") + } + if !exists && !flags.Creat { + return nil, sftp.ErrSSHFxNoSuchFile + } + release, ok := f.limiter.Acquire(f.user) + if !ok { + return nil, failure("too many concurrent transfers") + } + return newWriter(ctx, f, files, loc.rest, release, flags.Creat || flags.Trunc, !exists || flags.Trunc), nil +} + +// Limits on how far out of order a client's writes may arrive. pkg/sftp +// handles write packets on a pool of workers, so pipelined writes from one +// client can reach WriteAt a few chunks out of order. The writer holds such +// chunks until the gap before them is filled. A chunk further ahead than the +// window, or more held data than the cap, aborts the upload. +const ( + maxReorderBytes = 4 << 20 // furthest a chunk may start beyond the next expected offset, and the cap on held bytes + maxReorderChunks = 16 // most chunks held at once + baseWindow = 8 // chunks gathered before the start offset of a resume is fixed +) + +// writer turns WriteAt calls into one streamed PUT. The bytes go through an +// io.Pipe into a single request. The API commits the file only when the body +// ends cleanly, so an upload that is abandoned or has a gap in it is never +// committed. The stream runs front to back: chunks that arrive slightly out +// of order are held until their predecessors arrive. A new or truncated file +// starts at offset 0. For an existing file opened without truncation, the +// start offset is the lowest of the first few chunks, which resumes the file +// there. +type writer struct { + ctx context.Context + fs *FS + files *apiclient.Files + path string + create bool // Creat or Trunc was set: a write-less close still creates the file + baseKnown bool // the stream must start at offset 0 (new or truncated file) + release func() + pr *io.PipeReader + pw *io.PipeWriter + finished chan struct{} // closed when the stream goroutine has returned + aborted atomic.Bool + + mu sync.Mutex // guards the fields below + streaming bool // the stream goroutine is running + closed bool + next int64 // offset the stream expects next + pending map[int64][]byte // chunks held until the stream reaches them + pendingBytes int + streamErr error // result of the stream; written before finished closes + closeErr error +} + +// newWriter returns a writer that has not started its request yet. +func newWriter(ctx context.Context, fs *FS, files *apiclient.Files, p string, release func(), create, baseKnown bool) *writer { + pr, pw := io.Pipe() + return &writer{ + ctx: ctx, + fs: fs, + files: files, + path: p, + create: create, + baseKnown: baseKnown, + release: release, + pr: pr, + pw: pw, + finished: make(chan struct{}), + pending: make(map[int64][]byte), + } +} + +// WriteAt implements io.WriterAt. A chunk at the stream's position blocks +// until the stream has taken the bytes, which gives the client backpressure. +func (w *writer) WriteAt(p []byte, off int64) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.closed { + return 0, failure("file closed") + } + if w.aborted.Load() { + return 0, failure("transfer aborted") + } + if off < 0 { + return 0, failure("negative offset") + } + if len(p) == 0 { + return 0, nil + } + if !w.streaming && w.baseKnown && off == 0 { + w.begin(0) + } + switch { + case w.streaming && off == w.next: + if err := w.push(p); err != nil { + return 0, err + } + if err := w.drain(); err != nil { + return len(p), err + } + case w.streaming && off < w.next: + w.abort(errTransferAborted) + return 0, sftp.ErrSSHFxOpUnsupported + default: + if err := w.hold(p, off); err != nil { + return 0, err + } + if !w.streaming && !w.baseKnown && len(w.pending) >= baseWindow { + w.beginAtLowest() + if err := w.drain(); err != nil { + return len(p), err + } + } + } + return len(p), nil +} + +// begin starts the stream at off. +func (w *writer) begin(off int64) { + w.streaming = true + w.next = off + go w.run(off) +} + +// beginAtLowest starts the stream at the lowest held chunk. It is used for a +// resume, where the first offset the client writes is not known in advance. +func (w *writer) beginAtLowest() { + lowest := int64(-1) + for off := range w.pending { + if lowest < 0 || off < lowest { + lowest = off + } + } + w.begin(lowest) +} + +// hold keeps a copy of a chunk that is ahead of the stream. pkg/sftp reuses +// its buffer after WriteAt returns, so the bytes must be copied. +func (w *writer) hold(p []byte, off int64) error { + if _, dup := w.pending[off]; dup { + w.abort(errTransferAborted) + return sftp.ErrSSHFxOpUnsupported + } + limit := w.next + if !w.streaming && !w.baseKnown { + limit = off // a resume may start anywhere + } + if off+int64(len(p)) > limit+maxReorderBytes || + len(w.pending) >= maxReorderChunks || + w.pendingBytes+len(p) > maxReorderBytes { + w.abort(errTransferAborted) + return sftp.ErrSSHFxOpUnsupported + } + w.pending[off] = append([]byte(nil), p...) + w.pendingBytes += len(p) + return nil +} + +// push writes one chunk to the stream at its current position. +func (w *writer) push(p []byte) error { + n, err := w.pw.Write(p) + w.next += int64(n) + count(w.fs.onBytes, "write", n) + if err != nil { + // The stream ended early, for example with 413 or 507. Its error is + // the one to report. + <-w.finished + return w.streamFailure() + } + return nil +} + +// drain streams every held chunk that now continues the stream. +func (w *writer) drain() error { + for { + chunk, ok := w.pending[w.next] + if !ok { + return nil + } + delete(w.pending, w.next) + w.pendingBytes -= len(chunk) + if err := w.push(chunk); err != nil { + return err + } + } +} + +// run performs the streamed PUT. It closes the pipe reader when done, so a +// blocked WriteAt always returns. +func (w *writer) run(off int64) { + err := w.files.Stream(w.ctx, w.path, off, w.pr, -1) + if err != nil { + w.streamErr = w.fs.fail("write", err) + _ = w.pr.CloseWithError(w.streamErr) + } else { + _ = w.pr.Close() + } + close(w.finished) +} + +// streamFailure is the error to report once the stream has ended with an +// error. Call it only after finished is closed. +func (w *writer) streamFailure() error { + if w.streamErr != nil { + return w.streamErr + } + return failure("transfer failed") +} + +// abort marks the upload as abandoned and breaks the body so nothing is +// committed. It does not take mu, so it is safe during a blocked WriteAt. +func (w *writer) abort(err error) { + w.aborted.Store(true) + _ = w.pw.CloseWithError(err) +} + +// TransferError is called by pkg/sftp when the connection fails mid-transfer. +// It abandons the upload, so the half-written file is not committed. +func (w *writer) TransferError(err error) { + if err == nil { + err = errTransferAborted + } + w.abort(err) +} + +// Close ends the upload. A clean end commits it. An aborted upload, or one +// with a gap that never filled, commits nothing. An unstarted create or +// truncate with no data makes an empty file. Close is idempotent. +func (w *writer) Close() error { + w.mu.Lock() + defer w.mu.Unlock() + if w.closed { + return w.closeErr + } + w.closed = true + defer w.release() + flushErr := w.flushPending() + w.pending = nil + switch { + case w.aborted.Load(): + if w.streaming { + _ = w.pw.CloseWithError(errTransferAborted) + <-w.finished + } + w.closeErr = failure("transfer aborted") + if flushErr != nil { + w.closeErr = flushErr + } + case !w.streaming: + if w.create { + w.closeErr = w.fs.fail("create", w.files.Stream(w.ctx, w.path, 0, strings.NewReader(""), 0)) + } + default: + _ = w.pw.Close() + <-w.finished + w.closeErr = w.streamErr + } + return w.closeErr +} + +// flushPending runs at Close. Held chunks of a resume are streamed from their +// lowest offset. Anything still held after that, or held for a new file whose +// first chunk never came, is a gap: the upload is aborted. The error is the +// stream's, when the stream failed while draining. +func (w *writer) flushPending() error { + if len(w.pending) == 0 || w.aborted.Load() { + return nil + } + if !w.streaming { + if w.baseKnown { + w.abort(errTransferAborted) + return nil + } + w.beginAtLowest() + } + err := w.drain() + if err != nil || len(w.pending) > 0 { + w.abort(errTransferAborted) + } + return err +} diff --git a/internal/vfs/write_test.go b/internal/vfs/write_test.go new file mode 100644 index 0000000..b29d2c1 --- /dev/null +++ b/internal/vfs/write_test.go @@ -0,0 +1,473 @@ +package vfs + +import ( + "bytes" + "errors" + "io" + "net" + "testing" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// pattern returns n bytes that differ from one position to the next. +func pattern(n int) []byte { + b := make([]byte, n) + for i := range b { + b[i] = byte(i*7 + i/251) + } + return b +} + +func TestSequentialWriteIsOneStream(t *testing.T) { + var wrote int + fx := newFixture(t, nil, Options{OnBytes: func(dir string, n int) { + if dir == "write" { + wrote += n + } + }}, testServers) + data := pattern(1 << 20) + w, err := fx.fs.Filewrite(openReq("/survival/big.bin", fxfWrite|fxfCreat|fxfTrunc)) + if err != nil { + t.Fatalf("open for write: %v", err) + } + const chunk = 64 << 10 + for off := 0; off < len(data); off += chunk { + if n, err := w.WriteAt(data[off:off+chunk], int64(off)); err != nil || n != chunk { + t.Fatalf("WriteAt(%d) = %d, %v", off, n, err) + } + } + closeOrFail(t, w) + + st := fx.api.snapshot() + if len(st.streamQueries) != 1 || st.streamQueries[0].Get("offset") != "0" { + t.Fatalf("stream requests = %v, want one with offset=0", st.streamQueries) + } + got, ok := fx.api.fileData(testNS, "survival", "/big.bin") + if !ok || !bytes.Equal(got, data) { + t.Fatalf("committed file differs from written data (ok=%v, len=%d)", ok, len(got)) + } + if wrote != len(data) { + t.Fatalf("OnBytes(write) total = %d, want %d", wrote, len(data)) + } +} + +func TestResumeAtOffsetKeepsPrefix(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/r.bin", []byte("0123456789")) + w, err := fx.fs.Filewrite(openReq("/survival/r.bin", fxfWrite)) + if err != nil { + t.Fatalf("open for resume: %v", err) + } + if n, err := w.WriteAt([]byte("ABC"), 10); err != nil || n != 3 { + t.Fatalf("WriteAt(10) = %d, %v", n, err) + } + closeOrFail(t, w) + + st := fx.api.snapshot() + if len(st.streamQueries) != 1 || st.streamQueries[0].Get("offset") != "10" { + t.Fatalf("stream requests = %v, want one with offset=10", st.streamQueries) + } + got, _ := fx.api.fileData(testNS, "survival", "/r.bin") + if string(got) != "0123456789ABC" { + t.Fatalf("resumed file = %q, want 0123456789ABC", got) + } +} + +func TestOutOfOrderWriteAbortsWithoutCommit(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/o.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := w.WriteAt([]byte("aaaa"), 0); err != nil { + t.Fatalf("first WriteAt: %v", err) + } + if _, err := w.WriteAt([]byte("bbbb"), 1<<30); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Fatalf("far WriteAt err = %v, want op unsupported", err) + } + if err := w.(io.Closer).Close(); err == nil { + t.Fatal("Close after abort returned nil, want an error") + } + if fx.api.has(testNS, "survival", "/o.bin") { + t.Fatal("aborted upload was committed") + } +} + +func TestBackwardsWriteIsUnsupported(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/back.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := w.WriteAt([]byte("aaaa"), 0); err != nil { + t.Fatalf("first WriteAt: %v", err) + } + if _, err := w.WriteAt([]byte("bb"), 0); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Fatalf("backwards WriteAt err = %v, want op unsupported", err) + } + _ = w.(io.Closer).Close() + if fx.api.has(testNS, "survival", "/back.bin") { + t.Fatal("aborted upload was committed") + } +} + +func TestZeroLengthCreateMakesEmptyFile(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/empty.txt", fxfWrite|fxfCreat|fxfTrunc)) + if err != nil { + t.Fatalf("open: %v", err) + } + closeOrFail(t, w) + got, ok := fx.api.fileData(testNS, "survival", "/empty.txt") + if !ok || len(got) != 0 { + t.Fatalf("empty create: exists=%v len=%d, want an empty file", ok, len(got)) + } +} + +func TestExclusiveCreateOnExistingFails(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/e.txt", []byte("old")) + if _, err := fx.fs.Filewrite(openReq("/survival/e.txt", fxfWrite|fxfCreat|fxfExcl)); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("excl on existing err = %v, want failure", err) + } +} + +func TestAppendIsUnsupported(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + if _, err := fx.fs.Filewrite(openReq("/survival/a.txt", fxfWrite|fxfAppend|fxfCreat)); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Fatalf("append err = %v, want op unsupported", err) + } +} + +func TestStreamFailuresSurfaceAndDoNotCommit(t *testing.T) { + cases := []struct { + status int + want error + }{ + {413, sftp.ErrSSHFxFailure}, + {507, sftp.ErrSSHFxFailure}, + {403, sftp.ErrSSHFxPermissionDenied}, + } + for _, c := range cases { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.setStreamFail(c.status) + w, err := fx.fs.Filewrite(openReq("/survival/fail.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("status %d: open: %v", c.status, err) + } + _, err = w.WriteAt(pattern(1024), 0) + if err == nil { + err = w.(io.Closer).Close() + } + if !errors.Is(err, c.want) { + t.Errorf("status %d: err = %v, want %v", c.status, err, c.want) + } + if fx.api.has(testNS, "survival", "/fail.bin") { + t.Errorf("status %d: failed upload was committed", c.status) + } + } +} + +func TestTransferErrorDoesNotCommit(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/cut.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := w.WriteAt(pattern(4096), 0); err != nil { + t.Fatalf("WriteAt: %v", err) + } + w.(*writer).TransferError(errors.New("connection lost")) + if err := w.(io.Closer).Close(); err == nil { + t.Fatal("Close after TransferError returned nil") + } + if fx.api.has(testNS, "survival", "/cut.bin") { + t.Fatal("transfer cut mid-way was committed") + } +} + +func TestRenameVariants(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/a.txt", []byte("a")) + fx.api.seedFile(testNS, "survival", "/b.txt", []byte("b")) + + if err := fx.fs.Filecmd(&sftp.Request{Method: "Rename", Filepath: "/survival/a.txt", Target: "/survival/c.txt"}); err != nil { + t.Fatalf("plain rename: %v", err) + } + if fx.api.has(testNS, "survival", "/a.txt") || !fx.api.has(testNS, "survival", "/c.txt") { + t.Fatal("plain rename did not move the file") + } + if err := fx.fs.Filecmd(&sftp.Request{Method: "Rename", Filepath: "/survival/c.txt", Target: "/survival/b.txt"}); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("rename onto existing err = %v, want failure", err) + } + if err := fx.fs.PosixRename(&sftp.Request{Method: "PosixRename", Filepath: "/survival/c.txt", Target: "/survival/b.txt"}); err != nil { + t.Fatalf("posix rename over existing: %v", err) + } + if got, _ := fx.api.fileData(testNS, "survival", "/b.txt"); string(got) != "a" { + t.Fatalf("posix rename target = %q, want a", got) + } + if err := fx.fs.Filecmd(&sftp.Request{Method: "Rename", Filepath: "/survival/b.txt", Target: "/_namespaces/" + otherNS + "/modded/b.txt"}); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Fatalf("cross-server rename err = %v, want op unsupported", err) + } + if err := fx.fs.Filecmd(&sftp.Request{Method: "Rename", Filepath: "/survival/none", Target: "/survival/z"}); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Fatalf("missing source err = %v, want no such file", err) + } +} + +func TestMkdirRmdirRemove(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/f.txt", []byte("f")) + + if err := fx.fs.Filecmd(opReq("Mkdir", "/survival/newdir")); err != nil { + t.Fatalf("mkdir: %v", err) + } + if err := fx.fs.Filecmd(opReq("Mkdir", "/survival/newdir")); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("mkdir existing err = %v, want failure", err) + } + if err := fx.fs.Filecmd(opReq("Mkdir", "/survival/newdir/sub")); err != nil { + t.Fatalf("mkdir sub: %v", err) + } + if err := fx.fs.Filecmd(opReq("Remove", "/survival/newdir")); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("remove directory err = %v, want failure", err) + } + if err := fx.fs.Filecmd(opReq("Rmdir", "/survival/newdir")); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("rmdir non-empty err = %v, want failure", err) + } + if err := fx.fs.Filecmd(opReq("Rmdir", "/survival/newdir/sub")); err != nil { + t.Fatalf("rmdir empty: %v", err) + } + if err := fx.fs.Filecmd(opReq("Rmdir", "/survival/newdir")); err != nil { + t.Fatalf("rmdir now-empty: %v", err) + } + if err := fx.fs.Filecmd(opReq("Remove", "/survival/f.txt")); err != nil { + t.Fatalf("remove file: %v", err) + } + if err := fx.fs.Filecmd(opReq("Mkdir", "/survival")); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Fatalf("mkdir server folder err = %v, want permission denied", err) + } + for _, q := range fx.api.snapshot().deletes { + if q.Has("recursive") { + t.Fatalf("delete sent recursive: %v", q) + } + } +} + +func TestSetstatRules(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/s.txt", []byte("s")) + set := func(p string, flags uint32) error { + return fx.fs.Filecmd(&sftp.Request{Method: "Setstat", Filepath: p, Flags: flags}) + } + if err := set("/survival/s.txt", attrPerm); err != nil { + t.Errorf("chmod-style setstat: %v", err) + } + if err := set("/survival/s.txt", attrPerm|attrModTime); err != nil { + t.Errorf("time setstat: %v", err) + } + if err := set("/survival/s.txt", attrUIDGID); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Errorf("chown err = %v, want permission denied", err) + } + if err := set("/survival/s.txt", attrSize); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Errorf("truncate err = %v, want op unsupported", err) + } + if err := set("/survival/none", attrPerm); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Errorf("setstat missing err = %v, want no such file", err) + } + if err := set("/survival", attrPerm); err != nil { + t.Errorf("setstat on virtual folder: %v", err) + } +} + +func TestLinkAndReadlinkUnsupported(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + for _, m := range []string{"Link", "Symlink"} { + err := fx.fs.Filecmd(&sftp.Request{Method: m, Filepath: "/survival/a", Target: "/survival/b"}) + if !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Errorf("%s err = %v, want op unsupported", m, err) + } + } + if _, err := fx.fs.Filelist(opReq("Readlink", "/survival/a")); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) { + t.Errorf("readlink err = %v, want op unsupported", err) + } +} + +func TestTransferCapBlocksThenReleases(t *testing.T) { + fx := newFixture(t, nil, Options{Limiter: NewLimiter(1)}, testServers) + first, err := fx.fs.Filewrite(openReq("/survival/one.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("first open: %v", err) + } + if _, err := fx.fs.Filewrite(openReq("/survival/two.bin", fxfWrite|fxfCreat)); !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Fatalf("second open err = %v, want failure", err) + } + closeOrFail(t, first) + third, err := fx.fs.Filewrite(openReq("/survival/three.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open after release: %v", err) + } + closeOrFail(t, third) +} + +func TestTargetLoginWritesInsideServer(t *testing.T) { + target := &apiclient.Target{Namespace: testNS, Server: "survival"} + fx := newFixture(t, target, Options{}, testServers) + if err := fx.fs.Filecmd(opReq("Mkdir", "/mods")); err != nil { + t.Fatalf("mkdir in target root: %v", err) + } + if !fx.api.has(testNS, "survival", "/mods") { + t.Fatal("mkdir did not create the folder on the target server") + } +} + +// TestEndToEndOverSFTPProtocol drives the real pkg/sftp request server and +// client over an in-memory pipe, through the FS handlers. +func TestEndToEndOverSFTPProtocol(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + cliConn, srvConn := net.Pipe() + srv := sftp.NewRequestServer(srvConn, fx.fs.Handlers()) + served := make(chan error, 1) + go func() { served <- srv.Serve() }() + + client, err := sftp.NewClientPipe(cliConn, cliConn) + if err != nil { + t.Fatalf("client: %v", err) + } + t.Cleanup(func() { + _ = client.Close() + _ = srv.Close() + <-served + }) + + big := pattern(3 << 20) + if err := client.Mkdir("/survival/up"); err != nil { + t.Fatalf("mkdir: %v", err) + } + f, err := client.Create("/survival/up/big.bin") + if err != nil { + t.Fatalf("create: %v", err) + } + for off := 0; off < len(big); off += 32 << 10 { + end := min(off+32<<10, len(big)) + if _, err := f.Write(big[off:end]); err != nil { + t.Fatalf("write at %d: %v", off, err) + } + } + if err := f.Close(); err != nil { + t.Fatalf("close upload: %v", err) + } + if got, ok := fx.api.fileData(testNS, "survival", "/up/big.bin"); !ok || !bytes.Equal(got, big) { + t.Fatalf("uploaded file differs (ok=%v, len=%d)", ok, len(got)) + } + + rf, err := client.Open("/survival/up/big.bin") + if err != nil { + t.Fatalf("open: %v", err) + } + back, err := io.ReadAll(rf) + if err != nil { + t.Fatalf("download: %v", err) + } + if err := rf.Close(); err != nil { + t.Fatalf("close download: %v", err) + } + if !bytes.Equal(back, big) { + t.Fatalf("downloaded %d bytes, differs from upload", len(back)) + } + + if err := client.Rename("/survival/up/big.bin", "/survival/up/moved.bin"); err != nil { + t.Fatalf("rename: %v", err) + } + entries, err := client.ReadDir("/survival/up") + if err != nil { + t.Fatalf("readdir: %v", err) + } + if len(entries) != 1 || entries[0].Name() != "moved.bin" || entries[0].Size() != int64(len(big)) { + t.Fatalf("readdir = %v, want moved.bin of %d bytes", entries, len(big)) + } +} + +func TestReorderedChunksAreStreamedInOrder(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/re.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + const chunk = 1000 + data := pattern(6 * chunk) + // Chunks 2, 1, 0, 5, 3, 4: as a worker pool may deliver pipelined writes. + for _, i := range []int{2, 1, 0, 5, 3, 4} { + if n, err := w.WriteAt(data[i*chunk:(i+1)*chunk], int64(i*chunk)); err != nil || n != chunk { + t.Fatalf("WriteAt chunk %d = %d, %v", i, n, err) + } + } + closeOrFail(t, w) + st := fx.api.snapshot() + if len(st.streamQueries) != 1 || st.streamQueries[0].Get("offset") != "0" { + t.Fatalf("stream requests = %v, want one with offset=0", st.streamQueries) + } + if got, _ := fx.api.fileData(testNS, "survival", "/re.bin"); !bytes.Equal(got, data) { + t.Fatalf("reordered upload differs: got %d bytes, want %d", len(got), len(data)) + } +} + +func TestChunkGapAtCloseAbortsWithoutCommit(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/gap.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := w.WriteAt([]byte("aaaa"), 0); err != nil { + t.Fatalf("WriteAt 0: %v", err) + } + if _, err := w.WriteAt([]byte("cccc"), 8); err != nil { + t.Fatalf("WriteAt 8: %v", err) + } + if err := w.(io.Closer).Close(); err == nil { + t.Fatal("Close with a gap returned nil") + } + if fx.api.has(testNS, "survival", "/gap.bin") { + t.Fatal("upload with a gap was committed") + } +} + +func TestFirstChunkMissingForNewFileAborts(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + w, err := fx.fs.Filewrite(openReq("/survival/nofirst.bin", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := w.WriteAt([]byte("bbbb"), 4); err != nil { + t.Fatalf("WriteAt 4: %v", err) + } + if err := w.(io.Closer).Close(); err == nil { + t.Fatal("Close without the first chunk returned nil") + } + if fx.api.has(testNS, "survival", "/nofirst.bin") { + t.Fatal("upload without its first chunk was committed") + } +} + +func TestResumeWithReorderedChunksStartsAtLowest(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + fx.api.seedFile(testNS, "survival", "/res.bin", []byte("0123456789")) + w, err := fx.fs.Filewrite(openReq("/survival/res.bin", fxfWrite)) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := w.WriteAt([]byte("CC"), 12); err != nil { + t.Fatalf("WriteAt 12: %v", err) + } + if _, err := w.WriteAt([]byte("AA"), 10); err != nil { + t.Fatalf("WriteAt 10: %v", err) + } + closeOrFail(t, w) + st := fx.api.snapshot() + if len(st.streamQueries) != 1 || st.streamQueries[0].Get("offset") != "10" { + t.Fatalf("stream requests = %v, want one with offset=10", st.streamQueries) + } + if got, _ := fx.api.fileData(testNS, "survival", "/res.bin"); string(got) != "0123456789AACC" { + t.Fatalf("resumed file = %q, want 0123456789AACC", got) + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..24ab090 --- /dev/null +++ b/main.go @@ -0,0 +1,288 @@ +// Command sftp is Gameplane's optional SFTP endpoint (spec 040). It accepts +// SFTP clients on one address per cluster and sends every login and file +// operation to the Gameplane API as the signed-in user; it never reads a +// game server's volume itself. See specs.md. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "syscall" + "time" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/GameplanePanel/gameplane/sftp/internal/sshserver" + "github.com/GameplanePanel/gameplane/sftp/internal/vfs" + "github.com/pkg/sftp" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +// Version is set at build time with -ldflags "-X main.Version=...". +var Version = "dev" + +// errUsage is returned for an unknown or missing subcommand. +var errUsage = errors.New("usage: sftp serve [flags] | sftp version") + +// Defaults and environment variable names for the serve subcommand. A flag +// overrides its variable, and the variable overrides the default. +const ( + defaultListen = ":2222" + defaultMetricsAddr = ":9102" + defaultIdleTimeout = 15 * time.Minute + defaultMaxSessionsPerUser = 4 + defaultMaxTransfersPerUser = 8 + defaultMaxPreAuth = 64 + + envListen = "GAMEPLANE_SFTP_LISTEN" + envHostKey = "GAMEPLANE_SFTP_HOST_KEY" + envAPIURL = "GAMEPLANE_SFTP_API_URL" + envSvcAuthFile = "GAMEPLANE_SFTP_SERVICE_TOKEN_FILE" + envCAFile = "GAMEPLANE_SFTP_CA_FILE" + envIdleTimeout = "GAMEPLANE_SFTP_IDLE_TIMEOUT" + envMaxSessionsPerUser = "GAMEPLANE_SFTP_MAX_SESSIONS_PER_USER" + envMaxTransfersPerUser = "GAMEPLANE_SFTP_MAX_TRANSFERS_PER_USER" + envMaxPreAuth = "GAMEPLANE_SFTP_MAX_PREAUTH_CONNECTIONS" + envMetricsAddr = "GAMEPLANE_SFTP_METRICS_ADDR" + envDefaultNamespace = "GAMEPLANE_SFTP_DEFAULT_NAMESPACE" + + metricsShutdownTimeout = 5 * time.Second + metricsReadHeaderLimit = 10 * time.Second +) + +func main() { + os.Exit(exitCode(os.Args[1:], os.Stdout, os.Stderr)) +} + +// exitCode runs one subcommand and returns the process exit code: 0 on +// success, 2 after printing the error to errOut. +func exitCode(args []string, out, errOut io.Writer) int { + var err error + if len(args) > 0 && args[0] == "serve" { + err = runServe(args[1:], os.Getenv, errOut) + } else { + err = run(args, out) + } + if err != nil { + _, _ = fmt.Fprintln(errOut, err) + return 2 + } + return 0 +} + +// run dispatches the subcommands that print and return: version. serve is +// handled by exitCode, which owns the process signals. +func run(args []string, out io.Writer) error { + if len(args) != 1 || args[0] != "version" { + return errUsage + } + if _, err := fmt.Fprintln(out, Version); err != nil { + return fmt.Errorf("write version: %w", err) + } + return nil +} + +// serveConfig is the parsed serve subcommand. +type serveConfig struct { + Listen string + HostKeyPath string + APIURL string + ServiceTokenFile string + CAFile string + IdleTimeout time.Duration + MaxSessionsPerUser int + // MaxTransfersPerUser is handed to the virtual file system's per-user + // transfer limiter. + MaxTransfersPerUser int + // MaxPreAuth caps concurrent connections still before authentication. + MaxPreAuth int + MetricsAddr string + // DefaultNamespace is the namespace shown as / at the top of a + // tree login. It must match the API's default games namespace. + DefaultNamespace string +} + +// parseServeConfig reads the serve flags, falling back to the environment +// and then to the defaults. The required settings are checked here. +func parseServeConfig(args []string, getenv func(string) string, errOut io.Writer) (serveConfig, error) { + idle, err := envDuration(getenv, envIdleTimeout, defaultIdleTimeout) + if err != nil { + return serveConfig{}, err + } + maxSessions, err := envInt(getenv, envMaxSessionsPerUser, defaultMaxSessionsPerUser) + if err != nil { + return serveConfig{}, err + } + maxTransfers, err := envInt(getenv, envMaxTransfersPerUser, defaultMaxTransfersPerUser) + if err != nil { + return serveConfig{}, err + } + + maxPreAuth, err := envInt(getenv, envMaxPreAuth, defaultMaxPreAuth) + if err != nil { + return serveConfig{}, err + } + + var c serveConfig + fs := flag.NewFlagSet("serve", flag.ContinueOnError) + fs.SetOutput(errOut) + fs.StringVar(&c.Listen, "listen", envString(getenv, envListen, defaultListen), "address to accept SSH connections on") + fs.StringVar(&c.HostKeyPath, "host-key", getenv(envHostKey), "host key file or directory (required)") + fs.StringVar(&c.APIURL, "api-url", getenv(envAPIURL), "Gameplane API base URL, for example https://gameplane-api.gameplane.svc:8080 (required)") + fs.StringVar(&c.ServiceTokenFile, "service-token-file", getenv(envSvcAuthFile), "file holding the service token (required)") + fs.StringVar(&c.CAFile, "ca-file", getenv(envCAFile), "optional PEM bundle of extra CA certificates for the API") + fs.DurationVar(&c.IdleTimeout, "idle-timeout", idle, "close a connection with no traffic for this long") + fs.IntVar(&c.MaxSessionsPerUser, "max-sessions-per-user", maxSessions, "concurrent SSH connections allowed per user") + fs.IntVar(&c.MaxTransfersPerUser, "max-transfers-per-user", maxTransfers, "concurrent file transfers allowed per user") + fs.IntVar(&c.MaxPreAuth, "max-preauth-connections", maxPreAuth, "concurrent connections allowed before authentication finishes; more are closed at once") + fs.StringVar(&c.MetricsAddr, "metrics-addr", envString(getenv, envMetricsAddr, defaultMetricsAddr), "address for /metrics; empty disables it") + fs.StringVar(&c.DefaultNamespace, "default-namespace", envString(getenv, envDefaultNamespace, vfs.DefaultNamespace), "namespace whose servers appear as /; must match the API's default games namespace") + if err := fs.Parse(args); err != nil { + return serveConfig{}, fmt.Errorf("serve: %w", err) + } + if fs.NArg() > 0 { + return serveConfig{}, fmt.Errorf("serve: unexpected argument %q", fs.Arg(0)) + } + required := []struct{ flag, value string }{ + {"host-key", c.HostKeyPath}, + {"api-url", c.APIURL}, + {"service-token-file", c.ServiceTokenFile}, + } + for _, r := range required { + if r.value == "" { + return serveConfig{}, fmt.Errorf("serve: --%s is required", r.flag) + } + } + if c.IdleTimeout <= 0 { + return serveConfig{}, errors.New("serve: --idle-timeout must be positive") + } + if c.MaxSessionsPerUser < 1 { + return serveConfig{}, errors.New("serve: --max-sessions-per-user must be at least 1") + } + if c.MaxTransfersPerUser < 1 { + return serveConfig{}, errors.New("serve: --max-transfers-per-user must be at least 1") + } + if c.MaxPreAuth < 1 { + return serveConfig{}, errors.New("serve: --max-preauth-connections must be at least 1") + } + return c, nil +} + +func envString(getenv func(string) string, key, def string) string { + if v := getenv(key); v != "" { + return v + } + return def +} + +func envDuration(getenv func(string) string, key string, def time.Duration) (time.Duration, error) { + v := getenv(key) + if v == "" { + return def, nil + } + d, err := time.ParseDuration(v) + if err != nil { + return 0, fmt.Errorf("%s: %w", key, err) + } + return d, nil +} + +func envInt(getenv func(string) string, key string, def int) (int, error) { + v := getenv(key) + if v == "" { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil { + return 0, fmt.Errorf("%s: %w", key, err) + } + return n, nil +} + +// runServe starts the SSH/SFTP endpoint and blocks until SIGINT or SIGTERM. +func runServe(args []string, getenv func(string) string, errOut io.Writer) error { + cfg, err := parseServeConfig(args, getenv, errOut) + if err != nil { + return err + } + logger := slog.New(slog.NewTextHandler(errOut, nil)) + + hostKeys, err := sshserver.LoadHostKeys(cfg.HostKeyPath) + if err != nil { + return err + } + token, err := apiclient.LoadServiceToken(cfg.ServiceTokenFile) + if err != nil { + return err + } + api, err := apiclient.New(apiclient.Config{BaseURL: cfg.APIURL, ServiceToken: token, CAFile: cfg.CAFile}) + if err != nil { + return fmt.Errorf("api client: %w", err) + } + + reg := prometheus.NewRegistry() + metrics, err := sshserver.NewMetrics(reg) + if err != nil { + return err + } + limiter := vfs.NewLimiter(cfg.MaxTransfersPerUser) + factory := func(sess apiclient.Session, _ string) sftp.Handlers { + return vfs.New(api, sess, vfs.Options{ + DefaultNamespace: cfg.DefaultNamespace, + Limiter: limiter, + OnBytes: metrics.AddBytes, + Logger: logger, + }).Handlers() + } + srv, err := sshserver.New(sshserver.Config{ + Addr: cfg.Listen, + HostKeys: hostKeys, + IdleTimeout: cfg.IdleTimeout, + MaxSessionsPerUser: cfg.MaxSessionsPerUser, + MaxPreAuthConnections: cfg.MaxPreAuth, + Logger: logger, + Metrics: metrics, + }, api, factory) + if err != nil { + return err + } + l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", cfg.Listen) + if err != nil { + return fmt.Errorf("listen %s: %w", cfg.Listen, err) + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + var metricsSrv *http.Server + if cfg.MetricsAddr != "" { + metricsSrv = &http.Server{ + Addr: cfg.MetricsAddr, + Handler: promhttp.HandlerFor(reg, promhttp.HandlerOpts{}), + ReadHeaderTimeout: metricsReadHeaderLimit, + } + go func() { + if err := metricsSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + logger.Error("metrics server failed", "err", err) + } + }() + } + + logger.Info("sftp listening", "addr", l.Addr().String()) + serveErr := srv.Serve(ctx, l) + if metricsSrv != nil { + sctx, cancel := context.WithTimeout(context.Background(), metricsShutdownTimeout) + _ = metricsSrv.Shutdown(sctx) + cancel() + } + return serveErr +} diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..f29a563 --- /dev/null +++ b/main_test.go @@ -0,0 +1,182 @@ +package main + +import ( + "bytes" + "errors" + "io" + "testing" + "time" +) + +func TestRunVersion(t *testing.T) { + var out bytes.Buffer + if err := run([]string{"version"}, &out); err != nil { + t.Fatalf("run version: %v", err) + } + if got := out.String(); got != Version+"\n" { + t.Fatalf("version output = %q, want %q", got, Version+"\n") + } +} + +func TestRunRejectsUnknownSubcommands(t *testing.T) { + for _, args := range [][]string{nil, {"bogus"}, {"version", "extra"}} { + if err := run(args, &bytes.Buffer{}); !errors.Is(err, errUsage) { + t.Fatalf("run(%q) = %v, want errUsage", args, err) + } + } +} + +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("closed") } + +func TestRunVersionWriteError(t *testing.T) { + if err := run([]string{"version"}, failingWriter{}); err == nil { + t.Fatal("want an error when the output cannot be written") + } +} + +func TestExitCode(t *testing.T) { + var out, errOut bytes.Buffer + if code := exitCode([]string{"version"}, &out, &errOut); code != 0 || errOut.Len() != 0 { + t.Fatalf("exitCode(version) = %d, stderr %q", code, errOut.String()) + } + out.Reset() + if code := exitCode([]string{"bogus"}, &out, &errOut); code != 2 { + t.Fatalf("exitCode(bogus) = %d, want 2", code) + } + if got := errOut.String(); got != errUsage.Error()+"\n" { + t.Fatalf("stderr = %q, want usage", got) + } +} + +func TestExitCodeServeWithoutRequiredFlags(t *testing.T) { + var out, errOut bytes.Buffer + if code := exitCode([]string{"serve"}, &out, &errOut); code != 2 { + t.Fatalf("exitCode(serve) = %d, want 2", code) + } + if errOut.Len() == 0 { + t.Fatal("no error printed for serve without required flags") + } +} + +func fullServeEnv() map[string]string { + return map[string]string{ + envHostKey: "/keys", + envAPIURL: "https://api.example", + envSvcAuthFile: "/token", + } +} + +func envFunc(env map[string]string) func(string) string { + return func(k string) string { return env[k] } +} + +func TestParseServeConfigDefaults(t *testing.T) { + c, err := parseServeConfig(nil, envFunc(fullServeEnv()), io.Discard) + if err != nil { + t.Fatalf("parseServeConfig: %v", err) + } + if c.Listen != defaultListen || c.IdleTimeout != defaultIdleTimeout || + c.MaxSessionsPerUser != defaultMaxSessionsPerUser || c.MaxTransfersPerUser != defaultMaxTransfersPerUser || + c.MetricsAddr != defaultMetricsAddr || c.HostKeyPath != "/keys" || c.APIURL != "https://api.example" || + c.ServiceTokenFile != "/token" || c.CAFile != "" { + t.Fatalf("defaults = %+v", c) + } +} + +func TestParseServeConfigEnvAndFlagPrecedence(t *testing.T) { + env := fullServeEnv() + env[envIdleTimeout] = "3m" + env[envMaxSessionsPerUser] = "7" + env[envMaxTransfersPerUser] = "9" + env[envListen] = ":4000" + env[envMetricsAddr] = ":9999" + c, err := parseServeConfig(nil, envFunc(env), io.Discard) + if err != nil { + t.Fatalf("env: %v", err) + } + if c.IdleTimeout != 3*time.Minute || c.MaxSessionsPerUser != 7 || c.MaxTransfersPerUser != 9 || + c.Listen != ":4000" || c.MetricsAddr != ":9999" { + t.Fatalf("env values = %+v", c) + } + c, err = parseServeConfig([]string{ + "--idle-timeout", "1m", "--max-sessions-per-user", "2", "--max-transfers-per-user", "3", + "--listen", ":5000", "--metrics-addr", "", "--ca-file", "/ca.pem", + }, envFunc(env), io.Discard) + if err != nil { + t.Fatalf("flags: %v", err) + } + if c.IdleTimeout != time.Minute || c.MaxSessionsPerUser != 2 || c.MaxTransfersPerUser != 3 || + c.Listen != ":5000" || c.MetricsAddr != "" || c.CAFile != "/ca.pem" { + t.Fatalf("flag values = %+v", c) + } +} + +func TestParseServeConfigRejectsBadInput(t *testing.T) { + cases := map[string]struct { + args []string + env map[string]string + }{ + "missing host key": {nil, map[string]string{envAPIURL: "x", envSvcAuthFile: "y"}}, + "missing api url": {nil, map[string]string{envHostKey: "x", envSvcAuthFile: "y"}}, + "missing token": {nil, map[string]string{envHostKey: "x", envAPIURL: "y"}}, + "bad idle env": {nil, withEnv(fullServeEnv(), envIdleTimeout, "soon")}, + "bad sessions env": {nil, withEnv(fullServeEnv(), envMaxSessionsPerUser, "many")}, + "bad transfers env": {nil, withEnv(fullServeEnv(), envMaxTransfersPerUser, "x")}, + "zero idle": {[]string{"--idle-timeout", "0"}, fullServeEnv()}, + "zero sessions": {[]string{"--max-sessions-per-user", "0"}, fullServeEnv()}, + "zero transfers": {[]string{"--max-transfers-per-user", "0"}, fullServeEnv()}, + "unknown flag": {[]string{"--nope"}, fullServeEnv()}, + "extra argument": {[]string{"extra"}, fullServeEnv()}, + } + for name, tc := range cases { + if _, err := parseServeConfig(tc.args, envFunc(tc.env), io.Discard); err == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func withEnv(env map[string]string, k, v string) map[string]string { + env[k] = v + return env +} + +func TestParseServeConfigDefaultNamespace(t *testing.T) { + c, err := parseServeConfig(nil, envFunc(fullServeEnv()), io.Discard) + if err != nil || c.DefaultNamespace != "gameplane-games" { + t.Fatalf("default namespace = %q, %v; want gameplane-games", c.DefaultNamespace, err) + } + env := fullServeEnv() + env[envDefaultNamespace] = "from-env" + c, err = parseServeConfig(nil, envFunc(env), io.Discard) + if err != nil || c.DefaultNamespace != "from-env" { + t.Fatalf("env namespace = %q, %v", c.DefaultNamespace, err) + } + c, err = parseServeConfig([]string{"--default-namespace", "from-flag"}, envFunc(env), io.Discard) + if err != nil || c.DefaultNamespace != "from-flag" { + t.Fatalf("flag namespace = %q, %v", c.DefaultNamespace, err) + } +} + +func TestParseServeConfigMaxPreAuth(t *testing.T) { + c, err := parseServeConfig(nil, envFunc(fullServeEnv()), io.Discard) + if err != nil || c.MaxPreAuth != defaultMaxPreAuth { + t.Fatalf("default = %d, %v; want %d", c.MaxPreAuth, err, defaultMaxPreAuth) + } + env := withEnv(fullServeEnv(), envMaxPreAuth, "10") + c, err = parseServeConfig(nil, envFunc(env), io.Discard) + if err != nil || c.MaxPreAuth != 10 { + t.Fatalf("env = %d, %v; want 10", c.MaxPreAuth, err) + } + c, err = parseServeConfig([]string{"--max-preauth-connections", "5"}, envFunc(env), io.Discard) + if err != nil || c.MaxPreAuth != 5 { + t.Fatalf("flag = %d, %v; want 5", c.MaxPreAuth, err) + } + if _, err := parseServeConfig([]string{"--max-preauth-connections", "0"}, envFunc(fullServeEnv()), io.Discard); err == nil { + t.Error("zero cap accepted") + } + if _, err := parseServeConfig(nil, envFunc(withEnv(fullServeEnv(), envMaxPreAuth, "lots")), io.Discard); err == nil { + t.Error("bad env accepted") + } +} diff --git a/specs.md b/specs.md new file mode 100644 index 0000000..85527fd --- /dev/null +++ b/specs.md @@ -0,0 +1,98 @@ +# sftp — Specification + +How this component works today. The feature design is spec 040 in Gameplane (`specs/040-sftp-access/`); this file follows the code as it lands. + +## Purpose + +Optional SFTP endpoint, one per cluster, that gives users SFTP access to the files of the game servers they may access, without holding any permission or volume itself. Every login and file operation is sent to the Gameplane API as the signed-in user. + +## Responsibilities + +- Accept SSH connections, authenticate them through the API, and serve the SFTP subsystem and nothing else. +- Present the servers a user may reach as a folder tree, translate SFTP operations into API file calls, and map API errors to SFTP statuses. +- Close connections whose API session was revoked, cap sessions and transfers per user, and expose Prometheus metrics. + +## Non-goals / boundaries + +- No shell, exec, port forwarding or SCP (spec 040 FR-004). +- No direct access to game volumes or agents: all file access goes through the Gameplane API. +- No permission decisions: the API's file-access check decides (spec 040 FR-011a). +- No symlinks, hard links or `readlink`; `chown` and truncate-by-attribute are refused. + +## Directory & package layout + +- `main.go`: entrypoint, subcommand dispatch (`serve`, `version`), flag and environment parsing, wiring, metrics HTTP server. +- `internal/apiclient`: HTTP client for the API: login, session check, server list, and the file routes. Sentinel errors (`ErrNotFound`, `ErrPermission`, ...) map HTTP statuses. +- `internal/sshserver`: SSH listener, authentication callbacks, session registry, revocation loop, idle timeout, host key loading, metrics. +- `internal/vfs`: the per-connection virtual file system (`pkg/sftp` handlers), path translation, read and write streaming, transfer limiter. + +## External interface / contracts + +### Commands + +- `sftp version`: prints the build version. +- `sftp serve [flags]`: runs the endpoint until SIGINT or SIGTERM. A flag overrides its environment variable, and the variable overrides the default. + +| Flag | Environment variable | Default | Meaning | +|---|---|---|---| +| `--listen` | `GAMEPLANE_SFTP_LISTEN` | `:2222` | SSH listen address | +| `--host-key` | `GAMEPLANE_SFTP_HOST_KEY` | required | host key file, or a directory of keys (a mounted Secret works; `.pub` and hidden names are skipped) | +| `--api-url` | `GAMEPLANE_SFTP_API_URL` | required | Gameplane API base URL | +| `--service-token-file` | `GAMEPLANE_SFTP_SERVICE_TOKEN_FILE` | required | file holding the service token (`gpsftps_...`) | +| `--ca-file` | `GAMEPLANE_SFTP_CA_FILE` | none | extra PEM CA bundle for the API, added to the system roots | +| `--idle-timeout` | `GAMEPLANE_SFTP_IDLE_TIMEOUT` | `15m` | close a connection with no traffic for this long | +| `--max-sessions-per-user` | `GAMEPLANE_SFTP_MAX_SESSIONS_PER_USER` | `4` | concurrent SSH connections per user | +| `--max-preauth-connections` | `GAMEPLANE_SFTP_MAX_PREAUTH_CONNECTIONS` | `64` | concurrent connections still before authentication; further ones are closed at once | +| `--max-transfers-per-user` | `GAMEPLANE_SFTP_MAX_TRANSFERS_PER_USER` | `8` | concurrent file transfers per user, across connections | +| `--default-namespace` | `GAMEPLANE_SFTP_DEFAULT_NAMESPACE` | `gameplane-games` | namespace shown as `/`; must equal the API's default games namespace | +| `--metrics-addr` | `GAMEPLANE_SFTP_METRICS_ADDR` | `:9102` | address for `/metrics`; empty disables it | + +Exit code 2 with a message on stderr for a usage or startup error. + +### Login + +- Password: the callback sends the full SSH username (including a `+target` suffix), the password and the client address to `POST /sftp/v1/login` with the service token. +- Public key: the SSH layer verifies the signature, then the server logs in through the API with the key's authorized_keys line. Because the SSH library accepts the key before the API is asked, a refused key shows to the client as a connection that closes right after authentication, not as an authentication failure. Documented limitation. +- Every failure is a generic "permission denied" to the client; the cause is only logged at debug level and counted in metrics. +- A login as `user+server` or `user+namespace/server` roots the connection at that server. Otherwise the root lists the user's servers. + +### File tree + +- Tree login: `//...` for servers in the default namespace; `/_namespaces///...` for others. The root, `/_namespaces`, `/_namespaces/` and each server's top folder are read-only virtual directories (create, rename, remove and write are refused). Kubernetes names cannot start with `_`, so `_namespaces` never collides with a server. +- Target login: `/` is the server's root, read-only itself; the server list is never fetched. +- Paths are cleaned before use, so `..` cannot leave a server and no path can reach another server. A rename between servers is refused. +- Dotfiles: any path component starting with `.` is not found for reads and stat, refused for writes, and filtered from listings. +- Reads stream with `Range` requests. Reads a little ahead of the stream skip forward and keep the skipped bytes, because `pkg/sftp` may deliver pipelined reads slightly out of order; a far seek reopens the download. +- Writes stream to `PUT .../files/stream` through one request per open file. The API commits only when the body ends cleanly, so an aborted upload never replaces an existing file. A new or truncated file starts at offset 0. An existing file opened without truncation resumes at the lowest offset of the first chunks (the API copies the existing prefix). Chunks that arrive slightly out of order (bounded to 4 MiB ahead and 16 chunks) are held until the gap fills; a gap that never fills, a write behind the stream, or a chunk beyond the window aborts the upload with an error. Append mode is unsupported. An empty create makes an empty file. +- `chmod` and time changes are accepted as no-ops after checking the path exists; `chown` is refused; truncate by attribute is unsupported. `remove` refuses directories, `rmdir` refuses non-empty ones; the API delete is never recursive. `rename` does not overwrite; `posix-rename@openssh.com` does. +- API errors map to SFTP statuses with fixed messages: not found, permission denied, "file exists", "no space left on server", "file too large", "server busy, try again", "server not available, try again". No URL, token or response body reaches the client. + +### Metrics + +On `--metrics-addr` at `/metrics` (private registry): `gameplane_sftp_sessions` (gauge), `gameplane_sftp_logins_total{result="ok|denied|error|limit"}`, `gameplane_sftp_revoked_total`, `gameplane_sftp_preauth_rejected_total` (connections closed at once because the pre-auth cap was reached), `gameplane_sftp_bytes_total{direction="read|write"}`. + +## Key invariants + +- Only session channels with the `sftp` subsystem are served. `shell`, `exec`, `pty-req`, `env`, `x11-req`, agent forwarding and every other request are refused; `direct-tcpip` and other channel types are rejected; global forwarding requests are discarded. Only one SFTP subsystem runs per connection, and a further session channel is accepted, but its requests (including a second `sftp` subsystem) are refused and the channel is closed right after the refusal, so it never sits idle until the idle timeout. A non-`sftp` subsystem, `shell` and `exec` are refused. +- Every authenticated connection is registered by session token. Every 30 seconds the server sends the tokens to `POST /sftp/v1/sessions/check` and closes the connections whose tokens are reported revoked. A failed check keeps the connections (it never fails open into a kill, nor a grant). +- At most `--max-preauth-connections` connections may be before authentication at once (the slot is freed when the handshake and the API login finish). A connection over the cap is closed immediately, before any SSH exchange, and counted in `gameplane_sftp_preauth_rejected_total`. +- An API session the server creates but does not use is ended with `POST /sftp/v1/sessions/end` (service token, body `{"sessionTokens": ["gpsftp_…"]}`): a login refused by the per-user cap (password or key), and a password login whose SSH handshake does not finish. A failed end call is only logged; the session still expires on its own. +- Per-user caps are keyed by the lowercased API user name and enforced after authentication. +- The session token is used only as the bearer for the API calls of its own connection and is never logged. Passwords and keys are never logged. +- Before authentication completes, the handshake has an absolute deadline of `LoginTimeout` (10 s) from accept, so a client that drips bytes cannot hold a pre-auth slot longer; after it, each read or write has the idle-timeout deadline. `MaxAuthTries` is 3. + +## Dependencies + +`golang.org/x/crypto` (SSH), `github.com/pkg/sftp` (request server), `github.com/prometheus/client_golang` (metrics), and the standard library. + +## Security considerations + +- Authentication failures are generic (core rule 3); rate limiting of failed logins is done by the API per user and per source address, using the client address this server forwards. +- The service token authorises only login and session checks; file operations use the user's own short-lived session token, which the API restricts to the SFTP routes. +- Host keys must be stable across restarts (mounted from a Secret); they are read through `os.Root`, so a path cannot escape its directory. +- The API URL should be `https`; use `--ca-file` for a private CA. +- The session-end route `POST /sftp/v1/sessions/end` is not yet in the Gameplane API contract (`specs/040-sftp-access/contracts/api.md`). Until the API implements it, the call fails (logged at debug level) and an unused session expires on its own. + +## Testing & coverage + +Unit tests use in-process SSH clients and an `httptest` fake of the API; none needs a cluster. `main_test.go` covers flag parsing. The gate is `.testcoverage.yml` (total 70). diff --git a/system-deps.toml b/system-deps.toml new file mode 100644 index 0000000..5e106cc --- /dev/null +++ b/system-deps.toml @@ -0,0 +1,15 @@ +# System dependencies for sftp (spec 026). Language libraries stay in go.mod/package.json. + +component = "sftp" + +[[dep]] +name = "go" +kind = "toolchain" +version = "go" +reason = "Compiles and tests the sftp module." + +[[dep]] +name = "golangci-lint" +kind = "cli" +version = "golangci_lint" +reason = "golangci-lint runs on this module with Gameplane's root .golangci.yml (shared go-component.yaml workflow)."