Feature: Add admin-only SSO bridge to web UI
Bridge an already-authenticated portal session into a YAMA web session via a new /sso endpoint, so portal administrators can enter the remote-desktop UI without a second login. Only the "admin" portal role is bridged; any other role (viewer, unknown) still falls back to the built-in login form, so a low-privileged portal account cannot bypass authentication. - wsauth: extract IssueToken from VerifyLogin so an out-of-band-authenticated identity (SSO) can mint a session token without the challenge/response. - web: add the SSODetector interface, a fail-closed JWT detector (HMAC-only), and the /sso handler gated to the admin role. - cmd: enable the JWT detector via YAMA_SSO_JWT_SECRET, the shared HS256 secret matching the parent portal. - web UI: attempt SSO before showing the login form, falling back to login when the server returns 401. - docs: document SSO (admin-only) and license trial-vs-paid troubleshooting in README and the env example. Co-Authored-By: deepseek-v4-pro
This commit is contained in:
1 parent
d2149851b2
commit
53b7151fb7
9 files changed
+499
-11
No files matched your search
@@ -32,6 +32,7 @@ type Server struct {
|
||||
loginUserLimit *wsauth.RateLimiter
|
||||
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
|
||||
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
|
||||
sso SSODetector // nil = SSO disabled
|
||||
}
|
||||
|
||||
// Config tunes the server's exposed-on-public-HTTPS hardening knobs.
|
||||
@@ -60,6 +61,10 @@ type Config struct {
|
||||
// https://example.com/remoter). Must be empty or a leading-slash,
|
||||
// no-trailing-slash path; "" (default) serves from the domain root.
|
||||
BasePath string
|
||||
// SSO is an optional detector that maps an already-authenticated portal
|
||||
// session (cookie/header) into a YAMA web session via /sso. nil disables
|
||||
// SSO and the front-end falls back to the built-in login form.
|
||||
SSO SSODetector
|
||||
}
|
||||
|
||||
// New creates an HTTP server bound to the given port. port=0 disables the server.
|
||||
@@ -77,6 +82,7 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
||||
s.loginUserLimit = cfg.LoginUserLimit
|
||||
s.trustForwardedFor = cfg.TrustForwardedFor
|
||||
s.basePath = cfg.BasePath
|
||||
s.sso = cfg.SSO
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -98,6 +104,7 @@ func (s *Server) Start() error {
|
||||
mux.HandleFunc("/health", s.handleHealth)
|
||||
mux.HandleFunc("/manifest.json", s.handleManifest)
|
||||
mux.HandleFunc("/api/devices", s.requireBearer(s.handleDevices))
|
||||
mux.HandleFunc("/sso", s.handleSSO)
|
||||
mux.HandleFunc("/ws", s.ws.serve)
|
||||
mux.HandleFunc("/static/xterm.js", staticHandler(xtermJS, "application/javascript; charset=utf-8"))
|
||||
mux.HandleFunc("/static/xterm.css", staticHandler(xtermCSS, "text/css; charset=utf-8"))
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// SSODetector maps an incoming HTTP request from an already-authenticated
|
||||
// portal session into a YAMA web identity (username + role). Implementations
|
||||
// are portal-specific: each one knows how to recognize its portal's session
|
||||
// credential (a cookie, a header, a JWT, ...) and translate the caller to
|
||||
// YAMA's two roles, "admin" and "viewer".
|
||||
//
|
||||
// Detect returns ok=false when the request carries no usable credential, or
|
||||
// the credential is invalid/expired; the caller then falls back to the
|
||||
// built-in login form. username is used only for audit/logging. Whether a
|
||||
// detected identity is actually bridged into a session is handleSSO's policy:
|
||||
// currently only "admin" is bridged, everyone else falls back to the login form.
|
||||
type SSODetector interface {
|
||||
Detect(r *http.Request) (username, role string, ok bool)
|
||||
}
|
||||
|
||||
// handleSSO bridges a detected portal identity into a YAMA session token.
|
||||
// Only administrators are bridged: a valid portal session for any other role
|
||||
// (viewer, unknown) still returns 401 and the front-end falls back to the
|
||||
// built-in login form, so a low-privileged portal account cannot walk straight
|
||||
// into the remote-desktop console. When no detector is configured, or the
|
||||
// request is not recognized, it also returns 401.
|
||||
func (s *Server) handleSSO(w http.ResponseWriter, r *http.Request) {
|
||||
if s.sso == nil {
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
username, role, ok := s.sso.Detect(r)
|
||||
if !ok {
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
// Only the "admin" role may skip the login form via SSO. Every other role
|
||||
// (viewer, unknown) must authenticate against YAMA's own login, even with
|
||||
// a valid portal session.
|
||||
if role != "admin" {
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
|
||||
token, err := s.auth.IssueToken(username, role)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`{"error":"internal error"}`))
|
||||
return
|
||||
}
|
||||
|
||||
s.log.Info("sso: user=%s role=%s", username, role)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"token": token,
|
||||
"role": role,
|
||||
"username": username,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// JWTDetector is an SSODetector for portals that hand the browser a signed
|
||||
// JWT as an HttpOnly session cookie (or an Authorization: Bearer header). It
|
||||
// verifies the token with a shared HMAC secret and maps the identity claims
|
||||
// to a YAMA role. It is portal-agnostic: the secret, cookie name, claim keys
|
||||
// and the role value that means "admin" are all supplied at construction, so
|
||||
// the same detector serves any portal using this pattern.
|
||||
type JWTDetector struct {
|
||||
secret []byte
|
||||
cookieName string
|
||||
usernameClaim string
|
||||
roleClaim string
|
||||
adminRole string
|
||||
}
|
||||
|
||||
// JWTDetectorConfig configures a JWTDetector. Secret is the shared HMAC key
|
||||
// (required). The remaining fields have defaults for a typical portal:
|
||||
// CookieName "auth_token", UsernameClaim "username", RoleClaim "rolename",
|
||||
// AdminRole "admin".
|
||||
type JWTDetectorConfig struct {
|
||||
Secret string
|
||||
CookieName string
|
||||
UsernameClaim string
|
||||
RoleClaim string
|
||||
AdminRole string
|
||||
}
|
||||
|
||||
// NewJWTDetector builds a JWTDetector, applying defaults for any unset
|
||||
// optional field.
|
||||
func NewJWTDetector(cfg JWTDetectorConfig) *JWTDetector {
|
||||
if cfg.CookieName == "" {
|
||||
cfg.CookieName = "auth_token"
|
||||
}
|
||||
if cfg.UsernameClaim == "" {
|
||||
cfg.UsernameClaim = "username"
|
||||
}
|
||||
if cfg.RoleClaim == "" {
|
||||
cfg.RoleClaim = "rolename"
|
||||
}
|
||||
if cfg.AdminRole == "" {
|
||||
cfg.AdminRole = "admin"
|
||||
}
|
||||
return &JWTDetector{
|
||||
secret: []byte(cfg.Secret),
|
||||
cookieName: cfg.CookieName,
|
||||
usernameClaim: cfg.UsernameClaim,
|
||||
roleClaim: cfg.RoleClaim,
|
||||
adminRole: cfg.AdminRole,
|
||||
}
|
||||
}
|
||||
|
||||
// Detect reads the JWT from the configured cookie (falling back to a Bearer
|
||||
// header), verifies its signature and expiry, and maps the identity to a YAMA
|
||||
// role. Only HMAC algorithms are accepted, rejecting algorithm-confusion
|
||||
// attempts (alg=none / asymmetric algorithms).
|
||||
func (d *JWTDetector) Detect(r *http.Request) (username, role string, ok bool) {
|
||||
tokenString := d.extract(r)
|
||||
if tokenString == "" {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
claims, ok := d.parse(tokenString)
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
username, _ = claims[d.usernameClaim].(string)
|
||||
if username == "" {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
rolename, _ := claims[d.roleClaim].(string)
|
||||
if rolename == d.adminRole {
|
||||
role = "admin"
|
||||
} else {
|
||||
role = "viewer"
|
||||
}
|
||||
return username, role, true
|
||||
}
|
||||
|
||||
// extract returns the raw JWT from the configured cookie, or from a Bearer
|
||||
// header as a fallback.
|
||||
func (d *JWTDetector) extract(r *http.Request) string {
|
||||
if d.cookieName != "" {
|
||||
if ck, err := r.Cookie(d.cookieName); err == nil && ck.Value != "" {
|
||||
return ck.Value
|
||||
}
|
||||
}
|
||||
if hdr := r.Header.Get("Authorization"); strings.HasPrefix(hdr, "Bearer ") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(hdr, "Bearer "))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parse verifies a JWT against the shared HMAC secret and returns its claims.
|
||||
func (d *JWTDetector) parse(tokenString string) (jwt.MapClaims, bool) {
|
||||
if len(d.secret) == 0 {
|
||||
// Fail closed: an unset shared secret must never accept a token.
|
||||
// A detector wired up with an empty secret is a misconfiguration, and
|
||||
// accepting an empty-key-signed token here would be a trivial auth
|
||||
// bypass. Rejecting everything means SSO silently falls back to login.
|
||||
return nil, false
|
||||
}
|
||||
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("invalid signing algorithm")
|
||||
}
|
||||
return d.secret, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
return nil, false
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return claims, true
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth"
|
||||
)
|
||||
|
||||
const testSSOSecret = "test-shared-secret"
|
||||
|
||||
func signTestToken(t *testing.T, secret string, claims jwt.MapClaims) string {
|
||||
t.Helper()
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
s, err := tok.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
t.Fatalf("sign test token: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// noneToken builds a base64url header/claims JWT with alg "none" and no
|
||||
// signature, to exercise the algorithm-confusion rejection path.
|
||||
func noneToken(claims jwt.MapClaims) string {
|
||||
h, _ := json.Marshal(map[string]string{"alg": "none", "typ": "JWT"})
|
||||
c, _ := json.Marshal(claims)
|
||||
enc := base64.RawURLEncoding.EncodeToString
|
||||
return strings.TrimRight(enc(h), "=") + "." + strings.TrimRight(enc(c), "=") + "."
|
||||
}
|
||||
|
||||
func cookieReq(token string) *http.Request {
|
||||
r := &http.Request{Header: http.Header{}}
|
||||
r.AddCookie(&http.Cookie{Name: "auth_token", Value: token})
|
||||
return r
|
||||
}
|
||||
|
||||
func bearerReq(token string) *http.Request {
|
||||
r := &http.Request{Header: http.Header{}}
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestJWTDetector(t *testing.T) {
|
||||
d := NewJWTDetector(JWTDetectorConfig{Secret: testSSOSecret})
|
||||
|
||||
valid := func(rolename string) jwt.MapClaims {
|
||||
return jwt.MapClaims{
|
||||
"username": "alice",
|
||||
"rolename": rolename,
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
req *http.Request
|
||||
wantUser string
|
||||
wantRole string
|
||||
wantOK bool
|
||||
}{
|
||||
{"admin maps to admin", cookieReq(signTestToken(t, testSSOSecret, valid("admin"))), "alice", "admin", true},
|
||||
{"viewer maps to viewer", cookieReq(signTestToken(t, testSSOSecret, valid("viewer"))), "alice", "viewer", true},
|
||||
{"empty rolename maps to viewer", cookieReq(signTestToken(t, testSSOSecret, valid(""))), "alice", "viewer", true},
|
||||
{"unknown rolename maps to viewer", cookieReq(signTestToken(t, testSSOSecret, valid("operator"))), "alice", "viewer", true},
|
||||
{"bearer header accepted", bearerReq(signTestToken(t, testSSOSecret, valid("admin"))), "alice", "admin", true},
|
||||
{"no credential", &http.Request{Header: http.Header{}}, "", "", false},
|
||||
{"wrong secret rejected", cookieReq(signTestToken(t, "other-secret", valid("admin"))), "", "", false},
|
||||
{"expired token rejected", cookieReq(signTestToken(t, testSSOSecret, jwt.MapClaims{
|
||||
"username": "alice", "rolename": "admin", "exp": time.Now().Add(-time.Hour).Unix(),
|
||||
})), "", "", false},
|
||||
{"missing username rejected", cookieReq(signTestToken(t, testSSOSecret, jwt.MapClaims{
|
||||
"rolename": "admin", "exp": time.Now().Add(time.Hour).Unix(),
|
||||
})), "", "", false},
|
||||
{"alg none rejected", cookieReq(noneToken(valid("admin"))), "", "", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
user, role, ok := d.Detect(tt.req)
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("ok = %v, want %v (user=%q role=%q)", ok, tt.wantOK, user, role)
|
||||
}
|
||||
if !tt.wantOK {
|
||||
return
|
||||
}
|
||||
if user != tt.wantUser || role != tt.wantRole {
|
||||
t.Fatalf("got (%q, %q), want (%q, %q)", user, role, tt.wantUser, tt.wantRole)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A detector with no shared secret must never accept a token, even one signed
|
||||
// with an empty key — otherwise a misconfigured deployment would silently
|
||||
// accept forged sessions.
|
||||
func TestJWTDetectorEmptySecretFailClosed(t *testing.T) {
|
||||
d := NewJWTDetector(JWTDetectorConfig{})
|
||||
tok := signTestToken(t, "", jwt.MapClaims{
|
||||
"username": "alice", "rolename": "admin", "exp": time.Now().Add(time.Hour).Unix(),
|
||||
})
|
||||
if _, _, ok := d.Detect(cookieReq(tok)); ok {
|
||||
t.Fatal("empty-secret detector accepted a token; expected fail-closed")
|
||||
}
|
||||
}
|
||||
|
||||
// Non-default config keys must be honored, so a different portal can reuse the
|
||||
// detector with no code changes.
|
||||
func TestJWTDetectorCustomConfig(t *testing.T) {
|
||||
d := NewJWTDetector(JWTDetectorConfig{
|
||||
Secret: testSSOSecret,
|
||||
CookieName: "session",
|
||||
UsernameClaim: "sub",
|
||||
RoleClaim: "role",
|
||||
AdminRole: "root",
|
||||
})
|
||||
tok := signTestToken(t, testSSOSecret, jwt.MapClaims{
|
||||
"sub": "bob", "role": "root", "exp": time.Now().Add(time.Hour).Unix(),
|
||||
})
|
||||
r := &http.Request{Header: http.Header{}}
|
||||
r.AddCookie(&http.Cookie{Name: "session", Value: tok})
|
||||
user, role, ok := d.Detect(r)
|
||||
if !ok || user != "bob" || role != "admin" {
|
||||
t.Fatalf("got (%q, %q, %v), want (%q, %q, true)", user, role, ok, "bob", "admin")
|
||||
}
|
||||
}
|
||||
|
||||
// fakeSSODetector lets the /sso handler's role policy be exercised without a
|
||||
// real portal JWT.
|
||||
type fakeSSODetector struct {
|
||||
username, role string
|
||||
ok bool
|
||||
}
|
||||
|
||||
func (f *fakeSSODetector) Detect(*http.Request) (string, string, bool) {
|
||||
return f.username, f.role, f.ok
|
||||
}
|
||||
|
||||
// The /sso handler must only bridge administrators. A valid portal session for
|
||||
// any other role — or no session at all — returns 401 so the front-end falls
|
||||
// back to the built-in login form.
|
||||
func TestHandleSSOAdminOnly(t *testing.T) {
|
||||
newSrv := func(d SSODetector) *Server {
|
||||
return &Server{
|
||||
log: logger.New(logger.Config{}),
|
||||
auth: wsauth.New(),
|
||||
sso: d,
|
||||
}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
detector SSODetector
|
||||
wantStatus int
|
||||
}{
|
||||
{"admin is bridged", &fakeSSODetector{"alice", "admin", true}, http.StatusOK},
|
||||
{"viewer is rejected", &fakeSSODetector{"bob", "viewer", true}, http.StatusUnauthorized},
|
||||
{"unknown role is rejected", &fakeSSODetector{"carol", "operator", true}, http.StatusUnauthorized},
|
||||
{"no credential is rejected", &fakeSSODetector{ok: false}, http.StatusUnauthorized},
|
||||
{"SSO disabled", nil, http.StatusUnauthorized},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := newSrv(tt.detector)
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleSSO(rec, httptest.NewRequest(http.MethodPost, "/sso", nil))
|
||||
if rec.Code != tt.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body=%s)", rec.Code, tt.wantStatus, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user