add SSO session extend flow

Adds an end-to-end SSO session-extension feature: the management server
publishes per-peer session deadlines on every Login/Sync, a new
ExtendAuthSession RPC refreshes the deadline using a fresh JWT without
tearing down the tunnel, and the daemon tracks the deadline locally so
the UI can fire a T-10min warning toast with an interactive "Extend now"
action.
This commit is contained in:
Zoltán Papp
2026-05-20 16:43:14 +02:00
parent 2aea1f7bb5
commit ef6b4f7538
47 changed files with 6506 additions and 2603 deletions
+126
View File
@@ -0,0 +1,126 @@
//go:build !android && !ios && !freebsd && !js
package authsession
import (
"context"
"time"
"github.com/netbirdio/netbird/client/proto"
)
// ExtendStartParams optionally pre-fills the IdP login form.
type ExtendStartParams struct {
// Hint is the OIDC login_hint, typically the user's email.
Hint string `json:"hint"`
}
// ExtendStartResult tells the UI what to open and how to match the
// follow-up Wait call to the daemon's pending flow.
type ExtendStartResult struct {
VerificationURI string `json:"verificationUri"`
VerificationURIComplete string `json:"verificationUriComplete"`
UserCode string `json:"userCode"`
DeviceCode string `json:"deviceCode"`
ExpiresIn int64 `json:"expiresIn"`
}
// ExtendWaitParams identifies the pending flow by the device/user code
// the UI received from RequestExtend.
type ExtendWaitParams struct {
DeviceCode string `json:"deviceCode"`
UserCode string `json:"userCode"`
}
// ExtendResult carries the refreshed deadline. ExpiresAt is nil when the
// management server reported the peer is not eligible for session
// extension.
type ExtendResult struct {
ExpiresAt *time.Time `json:"sessionExpiresAt,omitempty"`
}
// DaemonConn yields a lazy daemon gRPC client. Mirrors services.DaemonConn
// in the Wails services package; duplicated here so the Session can be
// owned by authsession without an import cycle.
type DaemonConn interface {
Client() (proto.DaemonServiceClient, error)
}
// Session bundles the session-auth daemon RPCs the UI drives — the
// interactive extend flow (RequestExtend + WaitExtend) and the Dismiss
// hand-off. The tray uses it directly; the Wails-bound wrapper in
// client/ui/services exposes only the subset the React frontend needs.
type Session struct {
conn DaemonConn
}
// NewSession returns a Session backed by the shared daemon connection.
func NewSession(conn DaemonConn) *Session {
return &Session{conn: conn}
}
// RequestExtend starts the SSO session-extension flow on the daemon and
// returns the verification URI for the UI to open.
func (s *Session) RequestExtend(ctx context.Context, p ExtendStartParams) (ExtendStartResult, error) {
cli, err := s.conn.Client()
if err != nil {
return ExtendStartResult{}, err
}
req := &proto.RequestExtendAuthSessionRequest{}
if p.Hint != "" {
h := p.Hint
req.Hint = &h
}
resp, err := cli.RequestExtendAuthSession(ctx, req)
if err != nil {
return ExtendStartResult{}, err
}
return ExtendStartResult{
VerificationURI: resp.GetVerificationURI(),
VerificationURIComplete: resp.GetVerificationURIComplete(),
UserCode: resp.GetUserCode(),
DeviceCode: resp.GetDeviceCode(),
ExpiresIn: resp.GetExpiresIn(),
}, nil
}
// WaitExtend blocks until the user completes the SSO flow started by
// RequestExtend, then returns the new session deadline (or nil when the
// management server reports the peer ineligible).
func (s *Session) WaitExtend(ctx context.Context, p ExtendWaitParams) (ExtendResult, error) {
cli, err := s.conn.Client()
if err != nil {
return ExtendResult{}, err
}
resp, err := cli.WaitExtendAuthSession(ctx, &proto.WaitExtendAuthSessionRequest{
DeviceCode: p.DeviceCode,
UserCode: p.UserCode,
})
if err != nil {
return ExtendResult{}, err
}
out := ExtendResult{}
if ts := resp.GetSessionExpiresAt(); ts.IsValid() && !ts.AsTime().IsZero() {
t := ts.AsTime().UTC()
out.ExpiresAt = &t
}
return out, nil
}
// DismissWarning records the user's "Dismiss" click on the T-WarningLead
// notification so the daemon suppresses the T-FinalWarningLead fallback
// dialog for the current deadline. Best-effort: the daemon never reports
// a "deadline not found" error — a stale or no-op call is silently swallowed.
func (s *Session) DismissWarning(ctx context.Context) error {
cli, err := s.conn.Client()
if err != nil {
return err
}
_, err = cli.DismissSessionWarning(ctx, &proto.DismissSessionWarningRequest{})
return err
}
+83
View File
@@ -0,0 +1,83 @@
//go:build !android && !ios && !freebsd && !js
// Package authsession holds the UI-side domain logic for the SSO
// session-extend feature. Wails service facades in
// client/ui/services/session*.go are thin adapters around the types and
// functions defined here; the parsing, request shapes, and constants
// live in this package so future-us can reason about (and test) the
// feature without dragging the Wails service surface around with it.
package authsession
import (
"time"
"github.com/netbirdio/netbird/client/internal/auth/sessionwatch"
)
// Metadata keys the daemon attaches to session-warning SystemEvents.
// Re-exported from sessionwatch (single source of truth on the daemon
// side) so UI-side consumers don't have to import the daemon-internal
// package directly.
const (
MetaWarning = sessionwatch.MetaSessionWarning
MetaFinal = sessionwatch.MetaSessionFinal
MetaExpiresAt = sessionwatch.MetaSessionExpiresAt
MetaLeadMinutes = sessionwatch.MetaSessionLeadMinutes
)
// Warning is the typed payload emitted on the session-warning Wails
// events. The React side subscribes to "netbird:session:warning" and
// "netbird:session:final-warning" and receives this shape.
//
// ExpiresAt is best-effort: when the metadata is missing or malformed
// (e.g. an older daemon emits the event without the timestamp) it stays
// zero — the UI can fall back to the Status snapshot.
type Warning struct {
// ExpiresAt is the absolute UTC deadline the warning was fired
// against. The UI displays remaining time relative to its own clock.
ExpiresAt time.Time `json:"sessionExpiresAt"`
// LeadMinutes is the warning's configured lead time in minutes
// (WarningLead for the T-10 event, FinalWarningLead for the T-2
// event). Exposed so the UI can show "expires in ~N minutes" without
// hardcoding either constant on its side.
LeadMinutes int `json:"leadMinutes"`
// Final is true on the T-FinalWarningLead fallback event and false
// on the regular T-WarningLead notification. Exposed so a frontend
// listener bound to the dedicated final-warning Wails event still
// receives a payload it can self-describe (and so a tray that
// happens to see both event streams can branch in one place).
Final bool `json:"final"`
}
// WarningFromMetadata parses the daemon's SystemEvent metadata into a
// Warning payload. Returns (nil, false) when the event is not a
// session-warning at all (the common case). When the metadata flag is
// set but a field fails to parse, the field stays at its zero value and
// the event is still surfaced — the UI gets to decide how to handle it.
func WarningFromMetadata(meta map[string]string) (*Warning, bool) {
if meta == nil || meta[MetaWarning] != "true" {
return nil, false
}
out := &Warning{
Final: meta[MetaFinal] == "true",
}
if raw := meta[MetaExpiresAt]; raw != "" {
if t, err := sessionwatch.ParseExpiresAt(raw); err == nil {
out.ExpiresAt = t
}
}
if raw := meta[MetaLeadMinutes]; raw != "" {
if n, err := sessionwatch.ParseLeadMinutes(raw); err == nil {
out.LeadMinutes = n
}
}
return out, true
}
// ParseExpiresAt decodes a MetaExpiresAt metadata value to a UTC time.
// Thin re-export of sessionwatch.ParseExpiresAt so UI-side call sites
// (tray, frontend bindings) don't import the daemon-internal package.
func ParseExpiresAt(s string) (time.Time, error) {
return sessionwatch.ParseExpiresAt(s)
}
+82
View File
@@ -0,0 +1,82 @@
//go:build !android && !ios && !freebsd && !js
package authsession
import (
"testing"
"time"
)
func TestWarningFromMetadata_NotASessionWarning(t *testing.T) {
cases := []struct {
name string
meta map[string]string
}{
{"nil metadata", nil},
{"empty map", map[string]string{}},
{"unrelated event", map[string]string{"new_version_available": "0.65.0"}},
{"flag not 'true'", map[string]string{"session_warning": "1"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if w, ok := WarningFromMetadata(tc.meta); ok {
t.Fatalf("expected (nil, false), got (%+v, %v)", w, ok)
}
})
}
}
func TestWarningFromMetadata_FullPayload(t *testing.T) {
ts := "2026-05-18T13:30:00Z"
meta := map[string]string{
"session_warning": "true",
"session_expires_at": ts,
"lead_minutes": "10",
}
got, ok := WarningFromMetadata(meta)
if !ok {
t.Fatalf("expected the warning to be recognised, got ok=false")
}
want, _ := time.Parse(time.RFC3339, ts)
if !got.ExpiresAt.Equal(want.UTC()) {
t.Errorf("ExpiresAt = %v, want %v", got.ExpiresAt, want.UTC())
}
if got.LeadMinutes != 10 {
t.Errorf("LeadMinutes = %d, want 10", got.LeadMinutes)
}
}
func TestWarningFromMetadata_BadFieldsStillEmits(t *testing.T) {
// Older or buggy daemon: the flag is set but the timestamp/lead are
// missing or malformed. The UI should still get a warning so it can
// at least surface "session expires soon"; field zero-values are fine.
meta := map[string]string{
"session_warning": "true",
"session_expires_at": "not-a-timestamp",
"lead_minutes": "abc",
}
got, ok := WarningFromMetadata(meta)
if !ok {
t.Fatalf("warning should still be recognised even with malformed fields")
}
if !got.ExpiresAt.IsZero() {
t.Errorf("malformed timestamp should leave field zero, got %v", got.ExpiresAt)
}
if got.LeadMinutes != 0 {
t.Errorf("malformed lead_minutes should leave field 0, got %d", got.LeadMinutes)
}
}
func TestWarningFromMetadata_MissingFieldsStillEmits(t *testing.T) {
// Only the flag is present (e.g. future-trimmed event). Still emit.
meta := map[string]string{"session_warning": "true"}
got, ok := WarningFromMetadata(meta)
if !ok {
t.Fatalf("warning should still be recognised when only flag is present")
}
if got.ExpiresAt.IsZero() != true || got.LeadMinutes != 0 {
t.Errorf("missing fields should be zero-valued, got %+v", got)
}
}