mirror of
https://github.com/netbirdio/netbird.git
synced 2026-10-10 07:29:06 +02:00
* [client] Force interactive login when extending the auth session A session extend must be answered from the account the peer is registered under. With a silent PKCE flow (DisablePromptLogin or max_age=0) the IdP answers from whatever session it already holds, which need not be the peer's account when several are signed in; the token then fails the user match in ExtendAuthSession with no way to pick another account. Mark the PKCE flow request as a session extend so the management server can force prompt=login for it, overriding the configured silent flow. * [client] Reduce cognitive complexity of Server.Login Login sat at cognitive complexity 27, over the 25 the linter allows. Extract the interactive SSO branch into startSSOLogin, and split the nested in-flight-flow reuse check out of it into reuseOAuthFlow, which flattens the original if/else into early returns: it returns the cached auth info when the previous flow targets the same client and still has more than 90s left, otherwise cancels the stale wait and returns nil so the caller requests a fresh flow. The helpers take the contextState through a small statusSetter interface, since internal.contextState is unexported and re-deriving it with CtxGetState inside the helper would resolve against callerCtx rather than rootCtx. No behavior change: same ordering of state transitions, same mutex scope around the oauthAuthFlow write, same error paths. Login is now at 21. * [client] Respect DisablePromptLogin when extending the auth session Forcing prompt=login on a session extend overrode DisablePromptLogin, which is set for IdPs that break on it: Authentik triggers a double authentication and social logins fail outright. Overriding it there trades a recoverable extend for a login that cannot complete at all. Keep the LoginFlag override, which only replaces max_age=0 or none with prompt=login so the IdP honours login_hint, and leave DisablePromptLogin as configured. Those deployments keep the silent flow, and with several accounts signed in an extend answered from the wrong one still fails the user match. * [client] Guard the shared OAuth flow state with the server mutex reuseOAuthFlow read flow, expiresAt, waitCancel and info without holding s.mutex, while startSSOLogin and WaitSSOLogin write them under it. Reading the fields one at a time could also answer with auth info from a flow that was already replaced, or cancel a wait that no longer belongs to the flow just judged stale. Take one snapshot under the lock and decide from it. WaitSSOLogin read oauthAuthFlow.flow twice outside the lock; both now use a value snapshotted in the critical section that already installs actCancel. Its stale waitCancel was read and called in a separate section from the one installing the new one, so two racing calls could read the same predecessor and leave one wait uncancelled. Swap the two in a single critical section. Both cancels run after unlocking: the displaced wait takes s.mutex as it unwinds. * [client] Verify the SSO login came back for the hinted account login_hint is a suggestion the IdP may ignore: with a silent flow configured (DisablePromptLogin or max_age=0) and a live IdP session for another account, the login completes with that account's token. On a registered peer the management server rejects it as a user mismatch, but on a fresh profile the peer silently registers under the wrong account and the profile is then bound to it — every later login follows the stored hint straight back. After the token exchange, compare the ID token's email against the hint the flow was sent with. On a mismatch, do not log in to management with the token; run one more round asking the IdP to re-decide the account (prompt=login, via ForceAccountPrompt — DisablePromptLogin still wins there). If the prompted round also comes back different, proceed with a warning: the address may legitimately have changed, and refusing forever would lock the user out of the profile while the management server still rejects a token that does not own the peer. A token or profile with no email to compare is not judged. The retry differs per platform because of who opens the browser: - CLI (netbird login foreground) and Android run the whole flow in one process, so the mismatch retries automatically: the browser reopens with the account prompt within the same login attempt. - On desktop the login is split between the daemon and the GUI: Login hands the authorize URL to the GUI, WaitSSOLogin blocks for the token, and only the GUI can open a browser. A new URL cannot be handed out from inside WaitSSOLogin (its response has no field for one, kept that way to avoid a proto change), so the daemon arms forceAccountPrompt, fails the round with "connect again to choose the account", and builds the next Login's flow with the prompt — the user's next connect is the retry. The flag and the flow annotations live in daemon memory only; SwitchProfile drops them so the previous profile's hint cannot judge the next profile's token. The device code flow has no prompt parameter (RFC 8628), so a prompted round there runs as-is and a repeated mismatch is let through with the warning rather than looping. * [client] Address review comments on PKCE session extend flow Fail the PKCE authorization flow test on request error instead of continuing into a nil dereference, and make the godoc comments on the touched exported symbols identifier-leading full sentences. * [client] Match accounts only on the email claim of the ID token The name-claim fallback in the ID token parsing is kept for the login hint and display, but account matching now only considers a value that came from the email claim, so a token without one no longer produces a false account mismatch. * [client] Drop the pending session extend on a profile switch The profile-switch cleanup dropped the pending login flow and the account-prompt flag, but left extendAuthSessionFlow untouched. Its device code was issued by the previous profile's IdP client, so a WaitExtendAuthSession still parked on the browser leg would submit the resulting token against the new profile's engine. * [client] Judge the SSO account against the flow that produced the token WaitSSOLogin snapshotted the flow on entry but re-read the info, hint and accountPrompted from the live s.oauthAuthFlow afterwards, in separate critical sections. WaitToken blocks for the whole browser leg, so a concurrent Login or RequestJWTAuth could replace the flow meanwhile and the mismatch check would compare this wait's token against another flow's account: either arming the prompt spuriously or letting a wrong-account token through against an unrelated profile's hint. Take all of it in the entry snapshot. * [client] Keep the forced account prompt from being lost to flow reuse startSSOLogin consumed forceAccountPrompt and applied the prompt to the freshly built flow, but reuseOAuthFlow could then answer from a cached flow for the same client — one built without prompt=login, e.g. by RequestJWTAuth. The user got the same silent authorization URL that produced the mismatch, with the flag already spent, so no later round asked either. Rule reuse out when the prompt is forced, while still cancelling the predecessor's wait. RequestJWTAuth also wrote the flow fields one by one, leaving the previous login's hint and accountPrompted behind for WaitSSOLogin to judge a later token against. Both sites now replace the whole record. * [client] Consume the forced account prompt after the retry forceAccountPrompt was never cleared, so a flow that outlived the retry it was armed for kept sending prompt=login on every later authorization request and re-authenticated the user each time. RequestAuthInfo now takes the flag as it builds the request. * [client] Cancel the caller context in the SSO login tests WaitSSOLogin parks a goroutine on the caller's context for the whole browser leg. The tests passed context.Background(), which never cancels, so each left one goroutine behind for the lifetime of the test binary. * [client] Cancel the wait displaced by an OAuth flow replacement Replacing the shared record with a whole struct value dropped the previous flow's waitCancel, so an SSO browser wait still parked on it lost its cancel: nothing could preempt it, and it could go on to run attemptLogin or mutate the record behind the new flow. Both replacement sites now take the displaced cancel over in the same critical section, via a shared replaceOAuthFlow, and invoke it after the unlock. * [client] Guard OAuth flow mutations by the flow that owns the wait * [client] Arm the account prompt only from the wait that owns the flow * [client] Adopt the three-value parseEmailFromIDToken in the device flow The main merge brought in the device flow's email extraction from #7193, which still used the two-value signature this branch replaced when account matching was narrowed to the email claim. Git merged the files without a textual conflict, so the branch stopped compiling. Take the fromEmailClaim result and fill EmailClaim from it, the same way the PKCE path does, so device-flow clients get the same account matching. * [client] Populate the pending extend flow in the test server helper SwitchProfile cancels and clears the pending session extend flow unconditionally, the same way it clears the SSH JWT cache. New always populates the field, but the hand-assembled test server did not, so TestSwitchProfile_ClearsJWTCache panicked on a nil PendingFlow.
244 lines
7.9 KiB
Go
244 lines
7.9 KiB
Go
//go:build android
|
|
|
|
package android
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/netbirdio/netbird/client/internal"
|
|
"github.com/netbirdio/netbird/client/internal/auth"
|
|
)
|
|
|
|
// StateChangeListener receives client state notifications.
|
|
//
|
|
// OnStateChanged is a payload-free wake-up whenever the state snapshot
|
|
// changed: connection state, the run-loop status label (e.g. NeedsLogin) or
|
|
// the session deadline. It mirrors the daemon's SubscribeStatus stream
|
|
// trigger — on each signal the consumer pulls the fresh values via
|
|
// Status() / SessionExpiresAtUnix(). The engine arms no expiry-warning
|
|
// timers on Android; the app schedules the warnings from the deadline it
|
|
// reads here.
|
|
type StateChangeListener interface {
|
|
OnStateChanged()
|
|
}
|
|
|
|
// Status returns the connect run-loop's status label — the same value the
|
|
// desktop daemon serves in StatusResponse.Status. "NeedsLogin" means the
|
|
// management server rejected the peer and an interactive login is required.
|
|
//
|
|
// The label is latched: the run loop keeps its status in a per-run context
|
|
// state, which a restart replaces with a fresh Idle one, so an engine restart
|
|
// (network change, always-on) would otherwise erase the fact that the peer
|
|
// still needs to log in. Only a successful interactive login or extend clears
|
|
// it — see clearLoginRequired.
|
|
func (c *Client) Status() string {
|
|
latched, generation := c.loginRequiredState()
|
|
if latched {
|
|
return string(internal.StatusNeedsLogin)
|
|
}
|
|
cc := c.getConnectClient()
|
|
if cc == nil {
|
|
return string(internal.StatusIdle)
|
|
}
|
|
status := cc.Status()
|
|
if status == internal.StatusNeedsLogin {
|
|
c.latchLoginRequired(generation)
|
|
}
|
|
return string(status)
|
|
}
|
|
|
|
func (c *Client) loginRequiredState() (bool, uint64) {
|
|
c.loginRequiredMu.Lock()
|
|
defer c.loginRequiredMu.Unlock()
|
|
return c.loginRequired, c.loginCleared
|
|
}
|
|
|
|
// latchLoginRequired records a NeedsLogin observation, unless a clear landed
|
|
// while the caller was reading the run loop's status: cc.Status() is read
|
|
// outside the lock, so a login or extend completing in that window would
|
|
// otherwise be undone by this stale observation, stranding the UI on
|
|
// "login required" over a healthy session.
|
|
func (c *Client) latchLoginRequired(observedGeneration uint64) {
|
|
c.loginRequiredMu.Lock()
|
|
defer c.loginRequiredMu.Unlock()
|
|
if c.loginCleared != observedGeneration {
|
|
return
|
|
}
|
|
c.loginRequired = true
|
|
}
|
|
|
|
// clearLoginRequired releases the latch after a successful interactive login
|
|
// or session extend, and invalidates any observation already in flight.
|
|
func (c *Client) clearLoginRequired() {
|
|
c.loginRequiredMu.Lock()
|
|
defer c.loginRequiredMu.Unlock()
|
|
c.loginRequired = false
|
|
c.loginCleared++
|
|
}
|
|
|
|
// SessionExpiresAtUnix returns the SSO session deadline as unix seconds, or 0
|
|
// when no deadline is known (not SSO-registered, expiry disabled, or the
|
|
// engine has not received one yet). A past value means the session expired.
|
|
// Mirror of StatusResponse.sessionExpiresAt on the desktop daemon.
|
|
func (c *Client) SessionExpiresAtUnix() int64 {
|
|
deadline := c.recorder.GetSessionExpiresAt()
|
|
if deadline.IsZero() {
|
|
return 0
|
|
}
|
|
return deadline.Unix()
|
|
}
|
|
|
|
// SetStateChangeListener registers the state notification listener.
|
|
// Replaces any previously registered listener; remove it with
|
|
// RemoveStateChangeListener.
|
|
func (c *Client) SetStateChangeListener(listener StateChangeListener) {
|
|
c.stateChangeMu.Lock()
|
|
defer c.stateChangeMu.Unlock()
|
|
c.stopStateChangeWatchLocked()
|
|
if listener == nil {
|
|
return
|
|
}
|
|
|
|
// The subscription is buffered (one pending tick), so unsubscribing is
|
|
// not enough to stop callbacks: the loop would drain what is already
|
|
// queued and deliver it to a listener the caller has already removed or
|
|
// replaced. Gate every callback on this registration's own signal, which
|
|
// is closed before unsubscribing.
|
|
done := make(chan struct{})
|
|
c.stateChangeDone = done
|
|
|
|
id, ch := c.recorder.SubscribeToStateChanges()
|
|
c.stateChangeSubID = id
|
|
// The channel is closed by UnsubscribeFromStateChanges, which ends the
|
|
// goroutine. Ticks are coalesced (buffer of one), so a burst of changes
|
|
// wakes the listener once.
|
|
go func() {
|
|
for range ch {
|
|
select {
|
|
case <-done:
|
|
return
|
|
default:
|
|
}
|
|
listener.OnStateChanged()
|
|
}
|
|
}()
|
|
}
|
|
|
|
// RemoveStateChangeListener unregisters the state notification listener.
|
|
func (c *Client) RemoveStateChangeListener() {
|
|
c.stateChangeMu.Lock()
|
|
defer c.stateChangeMu.Unlock()
|
|
c.stopStateChangeWatchLocked()
|
|
}
|
|
|
|
// ExtendAuthSession runs the interactive SSO flow to obtain a fresh JWT and
|
|
// asks the management server to extend the session deadline. The tunnel is
|
|
// untouched: no resync, no reconnect. Async; the result arrives on the
|
|
// listener. Mirror of the daemon's RequestExtendAuthSession /
|
|
// WaitExtendAuthSession RPC pair, with URLOpener playing the "UI opens the
|
|
// browser" role.
|
|
//
|
|
// Only one flow may be in flight: the PKCE step binds a fixed loopback port,
|
|
// so a second concurrent flow would fail on that bind. Call
|
|
// CancelExtendAuthSession when the user abandons the browser.
|
|
func (c *Client) ExtendAuthSession(urlOpener URLOpener, isAndroidTV bool, resultListener ErrListener) {
|
|
ctx, err := c.beginExtend()
|
|
if err != nil {
|
|
resultListener.OnError(err)
|
|
return
|
|
}
|
|
|
|
go func() {
|
|
defer c.endExtend()
|
|
if err := c.extendAuthSession(ctx, urlOpener, isAndroidTV); err != nil {
|
|
resultListener.OnError(err)
|
|
return
|
|
}
|
|
resultListener.OnSuccess()
|
|
}()
|
|
}
|
|
|
|
// CancelExtendAuthSession aborts an in-flight ExtendAuthSession. The tunnel is
|
|
// left alone — unlike the login flow, which cancels the whole client context
|
|
// by stopping the engine. Without this the abandoned PKCE wait keeps its
|
|
// loopback port for the full flow timeout and blocks every later attempt.
|
|
// No-op when no flow is running.
|
|
func (c *Client) CancelExtendAuthSession() {
|
|
c.extendMu.Lock()
|
|
defer c.extendMu.Unlock()
|
|
if c.extendCancel != nil {
|
|
c.extendCancel()
|
|
}
|
|
}
|
|
|
|
func (c *Client) stopStateChangeWatchLocked() {
|
|
// Signal first, unsubscribe second: closing the channel only stops new
|
|
// items, and the loop would still hand whatever is buffered to a listener
|
|
// that is no longer registered.
|
|
if c.stateChangeDone != nil {
|
|
close(c.stateChangeDone)
|
|
c.stateChangeDone = nil
|
|
}
|
|
if c.stateChangeSubID != "" {
|
|
c.recorder.UnsubscribeFromStateChanges(c.stateChangeSubID)
|
|
c.stateChangeSubID = ""
|
|
}
|
|
}
|
|
|
|
func (c *Client) beginExtend() (context.Context, error) {
|
|
c.extendMu.Lock()
|
|
defer c.extendMu.Unlock()
|
|
if c.extendCancel != nil {
|
|
return nil, fmt.Errorf("session extend already in progress")
|
|
}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
c.extendCancel = cancel
|
|
return ctx, nil
|
|
}
|
|
|
|
func (c *Client) endExtend() {
|
|
c.extendMu.Lock()
|
|
defer c.extendMu.Unlock()
|
|
if c.extendCancel != nil {
|
|
c.extendCancel()
|
|
c.extendCancel = nil
|
|
}
|
|
}
|
|
|
|
func (c *Client) extendAuthSession(ctx context.Context, urlOpener URLOpener, isAndroidTV bool) error {
|
|
cfg, cfgPath, cc := c.authSnapshot()
|
|
if cfg == nil || cc == nil {
|
|
return fmt.Errorf("engine is not running")
|
|
}
|
|
engine := cc.Engine()
|
|
if engine == nil {
|
|
return fmt.Errorf("engine is not initialized")
|
|
}
|
|
|
|
authClient, err := auth.NewAuth(ctx, cfg.PrivateKey, cfg.ManagementURL, cfg)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create auth client: %v", err)
|
|
}
|
|
defer authClient.Close()
|
|
|
|
// Passing the config path makes the flow pick up the login_hint. That alone
|
|
// cannot keep the IdP on this profile's account though — a hint is only a
|
|
// suggestion, and a silent authorization is answered from whatever session the
|
|
// IdP already has, which need not be this peer's when several accounts are
|
|
// signed in. Marking the flow as an extend lets the server rule that out.
|
|
a := NewAuthWithConfig(ctx, cfg, cfgPath)
|
|
tokenInfo, err := a.foregroundGetTokenInfoFlow(authClient, urlOpener, isAndroidTV, true)
|
|
if err != nil {
|
|
return fmt.Errorf("interactive sso login failed: %v", err)
|
|
}
|
|
|
|
if _, err := engine.ExtendAuthSession(ctx, tokenInfo.GetTokenToUse()); err != nil {
|
|
return err
|
|
}
|
|
c.clearLoginRequired()
|
|
|
|
go urlOpener.OnLoginSuccess()
|
|
return nil
|
|
}
|