From 187b7df0d4a5f8ef8c314edb10980fff8f26d613 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:00:49 +0000 Subject: [PATCH] chore: remove unused config fields and duplicate login code - Drop sshserver.Config.Addr and its default: Serve takes the listener, so nothing read the field. - Drop apiclient.Config.Timeout and UserAgent: no caller set them, so the defaults always applied; the client now uses the constants directly. - Share the API login call between the password and public key callbacks through one login helper. - specs.md and .testcoverage.yml: the session-end route exists in the API now, and the coverage note no longer describes a scaffold. No behaviour change. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Claude --- .testcoverage.yml | 4 ++-- internal/apiclient/client.go | 21 +++++---------------- internal/sshserver/server.go | 33 +++++++++------------------------ main.go | 1 - specs.md | 5 ++--- 5 files changed, 18 insertions(+), 46 deletions(-) diff --git a/.testcoverage.yml b/.testcoverage.yml index 15079d0..5058651 100644 --- a/.testcoverage.yml +++ b/.testcoverage.yml @@ -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 diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go index 900e66f..fced816 100644 --- a/internal/apiclient/client.go +++ b/internal/apiclient/client.go @@ -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. @@ -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) @@ -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, } diff --git a/internal/sshserver/server.go b/internal/sshserver/server.go index 4259078..d73fa1e 100644 --- a/internal/sshserver/server.go +++ b/internal/sshserver/server.go @@ -22,7 +22,6 @@ import ( ) const ( - defaultAddr = ":2222" defaultIdleTimeout = 15 * time.Minute defaultMaxSessions = 4 defaultMaxPreAuth = 64 @@ -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 @@ -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") } @@ -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 @@ -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) { diff --git a/main.go b/main.go index 7869998..57574e7 100644 --- a/main.go +++ b/main.go @@ -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, diff --git a/specs.md b/specs.md index 85790e3..5edba91 100644 --- a/specs.md +++ b/specs.md @@ -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. @@ -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