diff --git a/api/internal/handlers/sftp_login.go b/api/internal/handlers/sftp_login.go index 4a7eedfc0..1b4dc53e3 100644 --- a/api/internal/handlers/sftp_login.go +++ b/api/internal/handlers/sftp_login.go @@ -10,6 +10,8 @@ import ( "net/netip" "strings" "time" + "unicode" + "unicode/utf8" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" @@ -95,20 +97,24 @@ func (h *sftpLoginHandler) login(w http.ResponseWriter, req *http.Request) { base, rawTarget, hasTarget := splitSFTPUsername(body.Username) actor := truncateRunes(base, sftpActorMaxRunes) refuse := func(cause string) { - slog.Debug("sftp login refused", "cause", cause) + // The client and the audit trail get one generic reason; the operator's log names the cause so a + // refused login can be diagnosed (key not registered, wrong account, no access to the target, …). + slog.Info("sftp login refused", "user", actor, "cluster", caller.Cluster, "cause", cause) h.auditLoginFailure(ctx, req, actor) httperr.WriteMessage(w, req, messages.New("server.sftp.login_failed", nil)) } // Rate limits run before any validation or credential work (so refusals cannot flood the audit // trail either), keyed like /auth/login: the source address the endpoint reports and the - // username. The request IP is always the SFTP pod, so it is not used. actor is the username - // capped to 64 runes, identical to base for every valid username. + // full username. The request IP is always the SFTP pod, so it is not used. actor is the username + // capped to 64 runes for the audit trail only; the username budget keys on the full base, so two + // long SSO email names that share a 64-rune prefix do not share a budget. The key is capped one rune + // past the longest valid name, so an oversized name cannot grow the limiter's keys. auth.SetActor(ctx, actor) if !auth.LoginLimiter.RequestBudget(w, req, sftpSourceKey(body.RemoteAddr, req)) { return } - if !auth.LoginUserLimiter.RequestBudget(w, req, actor) { + if !auth.LoginUserLimiter.RequestBudget(w, req, truncateRunes(base, sftpUsernameMaxRunes+1)) { return } @@ -116,7 +122,7 @@ func (h *sftpLoginHandler) login(w http.ResponseWriter, req *http.Request) { refuse("credential-shape") return } - if !identifierRE.MatchString(base) { + if !validSFTPUsername(base) { refuse("username") return } @@ -350,6 +356,26 @@ func (h *sftpServersHandler) list(w http.ResponseWriter, req *http.Request) { writeJSON(w, map[string]any{"items": items}) } +// sftpUsernameMaxRunes bounds an SFTP login name: long enough for an SSO account named by its email +// address (RFC 5321 caps a path at 254), far below anything that costs real work. +const sftpUsernameMaxRunes = 254 + +// validSFTPUsername reports whether name can be a panel username. Local accounts follow identifierRE, +// but SSO accounts are named by the identity provider (usually an email address), so the check only +// refuses what no account can hold: an empty or overlong name, whitespace, control characters and "/". +// The user lookup decides the rest. +func validSFTPUsername(name string) bool { + if name == "" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > sftpUsernameMaxRunes { + return false + } + for _, r := range name { + if unicode.IsSpace(r) || unicode.IsControl(r) || r == '/' { + return false + } + } + return true +} + // splitSFTPUsername splits "name+target" at the last "+". The base is what authenticates. func splitSFTPUsername(raw string) (base, target string, hasTarget bool) { i := strings.LastIndex(raw, "+") diff --git a/api/internal/handlers/sftp_login_sso_username_test.go b/api/internal/handlers/sftp_login_sso_username_test.go new file mode 100644 index 000000000..2167f30ae --- /dev/null +++ b/api/internal/handlers/sftp_login_sso_username_test.go @@ -0,0 +1,46 @@ +package handlers + +import ( + "net/http" + "strings" + "testing" +) + +// An SSO account is named by its email address. Such a user can log in over SFTP with that name. +func TestSFTPLogin_SSOEmailUsername(t *testing.T) { + env := newSFTPLoginEnv(t) + h := sftpLoginRouter(env) + const name = "valgul.sso@example.com" + if _, err := env.store.DB.ExecContext(t.Context(), + `INSERT INTO users(username, display_name, email, role, pw_hash) VALUES (?, ?, ?, ?, ?)`, + name, "valgul", name, "viewer", "x"); err != nil { + t.Fatalf("insert sso user: %v", err) + } + uid := userIDOf(t, env, name) + pw, err := env.sessions.GenerateAndStoreSFTPPassword(t.Context(), uid, 24) + if err != nil { + t.Fatalf("set sftp password: %v", err) + } + if rr := env.login(t, h, map[string]any{"username": name, "password": pw}); rr.Code != http.StatusOK { + t.Fatalf("login as %s: status %d body %s", name, rr.Code, rr.Body.String()) + } +} + +func TestValidSFTPUsername(t *testing.T) { + for name, want := range map[string]bool{ + "alice": true, + "valgul.sso@example.com": true, + "": false, + "has space": false, + "tab\tname": false, + "ctrl\x01": false, + "a/b": false, + "\xff": false, + strings.Repeat("a", sftpUsernameMaxRunes): true, + strings.Repeat("a", sftpUsernameMaxRunes+1): false, + } { + if got := validSFTPUsername(name); got != want { + t.Errorf("validSFTPUsername(%q) = %v, want %v", name, got, want) + } + } +} diff --git a/api/specs.md b/api/specs.md index 989a43b31..7d4521eff 100644 --- a/api/specs.md +++ b/api/specs.md @@ -352,7 +352,7 @@ trust assumptions, rotation behavior and surfaces outside this protocol. - `POST /clusters/{name}/sftp-token`: mint a `gpsftps_` service token, returned once (201). At most two active per cluster; a third returns 409 `server.sftp.token_limit_reached`. Only the digest is stored. - `DELETE /clusters/{name}/sftp-token/{id}`: revoke (204). Tokens of other clusters are not found. -**Endpoint-facing routes** (`sftp_login.go`, mounted under `/sftp/v1` outside the protected group, authenticated by the service token or the session token the endpoint holds, never by a dashboard cookie): `POST /sftp/v1/login` resolves username and credential to a session; `POST /sftp/v1/sessions/check` re-validates open sessions (revocation and user disable end them within 60 s, SC-006); `POST /sftp/v1/sessions/end`; `GET /sftp/v1/servers` lists the servers the session can read. Every file operation after login goes to the agent through the normal file routes as the signed-in user, with the same RBAC checks as the Files tab, and is audited with `source: sftp`. +**Endpoint-facing routes** (`sftp_login.go`, mounted under `/sftp/v1` outside the protected group, authenticated by the service token or the session token the endpoint holds, never by a dashboard cookie): `POST /sftp/v1/login` resolves username and credential to a session; `POST /sftp/v1/sessions/check` re-validates open sessions (revocation and user disable end them within 60 s, SC-006); `POST /sftp/v1/sessions/end`; `GET /sftp/v1/servers` lists the servers the session can read. Login accepts the panel username as the part before the last `+` (local accounts and SSO accounts named by email address alike): non-empty valid UTF-8, at most 254 runes, no whitespace, control characters or `/`; the user lookup then decides whether the account exists. The username rate-limit budget keys on that full name. Every refusal gives the endpoint and the audit trail one generic `server.sftp.login_failed`, and the API logs the cause at info level with the username and calling cluster. Every file operation after login goes to the agent through the normal file routes as the signed-in user, with the same RBAC checks as the Files tab, and is audited with `source: sftp`. **Permissions:** reading needs `servers:read` (or ownership or collaborator access); writing, renaming and deleting need `servers:write` (or the same ownership or collaborator access). The data-root and server folders are read-only over SFTP. diff --git a/changelog/unreleased/1086-sftp-sso-usernames.md b/changelog/unreleased/1086-sftp-sso-usernames.md new file mode 100644 index 000000000..f44819e95 --- /dev/null +++ b/changelog/unreleased/1086-sftp-sso-usernames.md @@ -0,0 +1,3 @@ +# SFTP login works for SSO accounts + +Accounts created through SSO are named by their email address, and the SFTP login refused every such name before checking the password or key. They can now log in with their panel username, for example `sftp -P 2222 alice@example.com@sftp.example.com`. An SSH key that is not registered no longer drops the connection: the client falls back to the password prompt. The API log now names the cause of each refused SFTP login, for operators. [PR #1086](https://github.com/GameplanePanel/Gameplane/pull/1086) diff --git a/docs/sftp.md b/docs/sftp.md index dccb70d3e..e4344b43a 100644 --- a/docs/sftp.md +++ b/docs/sftp.md @@ -128,6 +128,14 @@ The username chooses where the session starts. Both forms use the same password or key and the same permission checks. You only see the servers you can read. +`alice` stands for your panel username, shown on the profile page. An account +created through SSO is usually named by its email address, for example +`alice@example.com`. OpenSSH splits the host at the last `@`, so +`sftp -P 2222 alice@example.com@sftp.example.com` and +`sftp -P 2222 alice@example.com+survival@sftp.example.com` work as written. +A username that itself contains `+` cannot be used over SFTP, because `+` +starts the server part. + Permissions: - Reading needs `servers:read` on the server, or the usual ownership or diff --git a/sftp b/sftp index 2d695cc3f..c5baacfc5 160000 --- a/sftp +++ b/sftp @@ -1 +1 @@ -Subproject commit 2d695cc3f72b176691bbfbe5ec0af4410920c16a +Subproject commit c5baacfc522d5b5b193764b1472135f866ddd574