Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .testcoverage.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 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).
# main() is process wiring and is not unit-tested; the SSH server, API client
# and virtual file system are covered by their own package tests.
profile: coverage/unit.out
github-action-output: false

Expand Down
21 changes: 5 additions & 16 deletions internal/apiclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,6 @@ type Config struct {
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.
Expand Down Expand Up @@ -141,17 +136,15 @@ func New(cfg Config) (*Client, error) {
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, CheckRedirect: refuseRedirect}
// Streaming calls (Download and Stream) use the second client and are
// bounded by their context only.
hc := &http.Client{Transport: tr, Timeout: defaultTimeout, CheckRedirect: refuseRedirect}
stream := &http.Client{Transport: tr, CheckRedirect: refuseRedirect}
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
// is meant for tests; CAFile in cfg is ignored because hc owns
// TLS and timeouts.
func NewWithHTTPClient(cfg Config, hc *http.Client) (*Client, error) {
base, err := validateBaseURL(cfg.BaseURL)
Expand Down Expand Up @@ -179,14 +172,10 @@ func LoadServiceToken(path string) (string, error) {
}

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,
userAgent: defaultUserAgent,
hc: hc,
streamHC: stream,
}
Expand Down
33 changes: 9 additions & 24 deletions internal/sshserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
)

const (
defaultAddr = ":2222"
defaultIdleTimeout = 15 * time.Minute
defaultMaxSessions = 4
defaultMaxPreAuth = 64
Expand Down Expand Up @@ -69,9 +68,6 @@ 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
Expand Down Expand Up @@ -170,9 +166,6 @@ func New(cfg Config, api API, hf HandlerFactory) (*Server, error) {
}

func (c Config) withDefaults() (Config, error) {
if c.Addr == "" {
c.Addr = defaultAddr
}
if c.IdleTimeout < 0 || c.CheckInterval < 0 || c.LoginTimeout < 0 || c.RevalidateWithin < 0 {
return c, errors.New("sshserver: negative timeout")
}
Expand Down Expand Up @@ -554,13 +547,16 @@ func (s *Server) atLimit(user string) bool {
// 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) {
return s.login(conn, apiclient.LoginRequest{Password: string(pw)})
}

// login asks the API to accept the credential in req for the connecting user.
func (s *Server) login(conn ssh.ConnMetadata, req apiclient.LoginRequest) (*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(),
})
req.Username = conn.User()
req.RemoteAddr = conn.RemoteAddr().String()
sess, err := s.api.Login(ctx, req)
if err != nil {
s.loginFailed(conn.User(), conn.RemoteAddr().String(), err)
return nil, errPermissionDenied
Expand Down Expand Up @@ -608,18 +604,7 @@ func (s *Server) verifiedPublicKeyCallback(conn ssh.ConnMetadata, _ ssh.PublicKe
if line == "" {
return nil, errPermissionDenied
}
ctx, cancel := context.WithTimeout(context.Background(), s.cfg.LoginTimeout)
defer cancel()
sess, err := s.api.Login(ctx, apiclient.LoginRequest{
Username: conn.User(),
PublicKey: line,
RemoteAddr: conn.RemoteAddr().String(),
})
if err != nil {
s.loginFailed(conn.User(), conn.RemoteAddr().String(), err)
return nil, errPermissionDenied
}
return s.loggedIn(conn, sess)
return s.login(conn, apiclient.LoginRequest{PublicKey: line})
}

func (s *Server) loginFailed(user, remote string, err error) {
Expand Down
1 change: 0 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,6 @@ func runServe(args []string, getenv func(string) string, errOut io.Writer) error
}).Handlers()
}
srv, err = sshserver.New(sshserver.Config{
Addr: cfg.Listen,
HostKeys: hostKeys,
IdleTimeout: cfg.IdleTimeout,
MaxSessionsPerUser: cfg.MaxSessionsPerUser,
Expand Down
5 changes: 2 additions & 3 deletions specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Optional SFTP endpoint, one per cluster, that gives users SFTP access to the fil
## 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/apiclient`: HTTP client for the API: login, session check, session end, 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.

Expand Down Expand Up @@ -93,11 +93,10 @@ On `--metrics-addr` at `GET /metrics` only (private registry; read, write and id
## 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.
- The service token authorises only login, session checks and session end; 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 must be `https`, with the certificate checked against the system roots plus `--ca-file`; plain `http` needs `--allow-insecure-api`, which the chart sets only in local mode, where the hop is pod to pod inside the cluster behind the SFTP NetworkPolicy. The client never follows a redirect: a 3xx answer fails the call, so the password, key or token is never re-sent to another URL.
- `/metrics` has no authentication and is loopback-only by default. The chart binds it to the pod address only when a ServiceMonitor scrapes it, behind a NetworkPolicy rule for the scrape namespace, and never adds it to the public SFTP Service.
- 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

Expand Down