|
| 1 | +package logout |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "net/url" |
| 9 | + "strings" |
| 10 | + "sync" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/google/uuid" |
| 14 | + |
| 15 | + "github.com/dexidp/dex/server/internal" |
| 16 | + "github.com/dexidp/dex/server/session" |
| 17 | + "github.com/dexidp/dex/storage" |
| 18 | +) |
| 19 | + |
| 20 | +const ( |
| 21 | + // backchannelLogoutEvent is the event identifier a logout token must carry, per |
| 22 | + // OIDC Back-Channel Logout 1.0 §2.4. |
| 23 | + backchannelLogoutEvent = "http://schemas.openid.net/event/backchannel-logout" |
| 24 | + |
| 25 | + // backchannelTokenLifetime bounds the replay window for a logout token. The spec |
| 26 | + // recommends no more than two minutes. |
| 27 | + backchannelTokenLifetime = 2 * time.Minute |
| 28 | + |
| 29 | + // backchannelTimeout caps how long dex waits on one RP. Logout must not hang on a |
| 30 | + // wedged relying party. |
| 31 | + backchannelTimeout = 5 * time.Second |
| 32 | +) |
| 33 | + |
| 34 | +// logoutTokenClaims is the JWT dex POSTs to a relying party's backchannel_logout_uri. |
| 35 | +// |
| 36 | +// Note the absences: there is no "nonce" (the spec forbids it, to keep a logout token |
| 37 | +// from being mistaken for an ID token) and no "events" payload beyond an empty object. |
| 38 | +type logoutTokenClaims struct { |
| 39 | + Issuer string `json:"iss"` |
| 40 | + Subject string `json:"sub"` |
| 41 | + Audience string `json:"aud"` |
| 42 | + IssuedAt int64 `json:"iat"` |
| 43 | + Expiry int64 `json:"exp"` |
| 44 | + JWTID string `json:"jti"` |
| 45 | + SessionID string `json:"sid"` |
| 46 | + Events map[string]json.RawMessage `json:"events"` |
| 47 | +} |
| 48 | + |
| 49 | +// notifyBackchannel tells every relying party in the session that it is over. |
| 50 | +// |
| 51 | +// Delivery is best-effort and fire-and-forget: RP-Initiated Logout treats notifying |
| 52 | +// other RPs as a courtesy, and a relying party that is down must not be able to block |
| 53 | +// or fail the user's logout. Failures are logged and dropped. |
| 54 | +// |
| 55 | +// ponytail: no retries and no durable queue. An RP that is unreachable for these few |
| 56 | +// seconds keeps its session until it expires on its own. If that becomes a real |
| 57 | +// problem, the upgrade path is to persist pending notifications and drain them from |
| 58 | +// the garbage collector, not to make the user wait here. |
| 59 | +func (h *Handler) notifyBackchannel(ctx context.Context, authSession *storage.AuthSession) { |
| 60 | + if len(authSession.ClientStates) == 0 { |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + subject, err := internal.Marshal(&internal.IDTokenSubject{ |
| 65 | + UserId: authSession.UserID, |
| 66 | + ConnId: authSession.ConnectorID, |
| 67 | + }) |
| 68 | + if err != nil { |
| 69 | + h.Logger.ErrorContext(ctx, "logout: failed to marshal backchannel subject", "err", err) |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + sid := session.SessionID(authSession.Nonce) |
| 74 | + |
| 75 | + // The request context dies the moment we redirect the browser, so deliveries get |
| 76 | + // their own bounded context rather than being canceled halfway through. |
| 77 | + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), backchannelTimeout) |
| 78 | + defer cancel() |
| 79 | + |
| 80 | + var wg sync.WaitGroup |
| 81 | + for clientID := range authSession.ClientStates { |
| 82 | + client, err := h.Storage.GetClient(ctx, clientID) |
| 83 | + if err != nil { |
| 84 | + h.Logger.DebugContext(ctx, "logout: backchannel skipped, client not found", |
| 85 | + "client_id", clientID, "err", err) |
| 86 | + continue |
| 87 | + } |
| 88 | + if client.BackchannelLogoutURI == "" { |
| 89 | + continue |
| 90 | + } |
| 91 | + |
| 92 | + wg.Go(func() { h.deliverLogoutToken(ctx, client, subject, sid) }) |
| 93 | + } |
| 94 | + wg.Wait() |
| 95 | +} |
| 96 | + |
| 97 | +// deliverLogoutToken mints a logout token for one client and POSTs it. |
| 98 | +func (h *Handler) deliverLogoutToken(ctx context.Context, client storage.Client, subject, sid string) { |
| 99 | + token, err := h.signLogoutToken(ctx, client.ID, subject, sid) |
| 100 | + if err != nil { |
| 101 | + h.Logger.ErrorContext(ctx, "logout: failed to sign logout token", |
| 102 | + "client_id", client.ID, "err", err) |
| 103 | + return |
| 104 | + } |
| 105 | + |
| 106 | + body := url.Values{"logout_token": {token}}.Encode() |
| 107 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, client.BackchannelLogoutURI, strings.NewReader(body)) |
| 108 | + if err != nil { |
| 109 | + h.Logger.ErrorContext(ctx, "logout: failed to build backchannel request", |
| 110 | + "client_id", client.ID, "err", err) |
| 111 | + return |
| 112 | + } |
| 113 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 114 | + req.Header.Set("Cache-Control", "no-cache, no-store") |
| 115 | + |
| 116 | + resp, err := h.backchannelClient().Do(req) |
| 117 | + if err != nil { |
| 118 | + h.Logger.WarnContext(ctx, "logout: backchannel delivery failed", |
| 119 | + "client_id", client.ID, "uri", client.BackchannelLogoutURI, "err", err) |
| 120 | + return |
| 121 | + } |
| 122 | + defer resp.Body.Close() |
| 123 | + |
| 124 | + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 125 | + h.Logger.WarnContext(ctx, "logout: backchannel delivery rejected", |
| 126 | + "client_id", client.ID, "uri", client.BackchannelLogoutURI, "status", resp.StatusCode) |
| 127 | + return |
| 128 | + } |
| 129 | + |
| 130 | + h.Logger.DebugContext(ctx, "logout: backchannel delivered", "client_id", client.ID) |
| 131 | +} |
| 132 | + |
| 133 | +// signLogoutToken builds and signs the logout token for one audience. |
| 134 | +func (h *Handler) signLogoutToken(ctx context.Context, clientID, subject, sid string) (string, error) { |
| 135 | + now := time.Now() |
| 136 | + if h.Now != nil { |
| 137 | + now = h.Now() |
| 138 | + } |
| 139 | + |
| 140 | + claims := logoutTokenClaims{ |
| 141 | + Issuer: h.IssuerURL.String(), |
| 142 | + Subject: subject, |
| 143 | + Audience: clientID, |
| 144 | + IssuedAt: now.Unix(), |
| 145 | + Expiry: now.Add(backchannelTokenLifetime).Unix(), |
| 146 | + JWTID: uuid.New().String(), |
| 147 | + SessionID: sid, |
| 148 | + Events: map[string]json.RawMessage{backchannelLogoutEvent: json.RawMessage(`{}`)}, |
| 149 | + } |
| 150 | + |
| 151 | + payload, err := json.Marshal(claims) |
| 152 | + if err != nil { |
| 153 | + return "", fmt.Errorf("marshal logout token: %w", err) |
| 154 | + } |
| 155 | + |
| 156 | + token, err := h.Signer.Sign(ctx, payload) |
| 157 | + if err != nil { |
| 158 | + return "", fmt.Errorf("sign logout token: %w", err) |
| 159 | + } |
| 160 | + return token, nil |
| 161 | +} |
| 162 | + |
| 163 | +// backchannelClient returns the HTTP client used for delivery, defaulting to one with |
| 164 | +// no redirect following: a logout token must reach the URI the client registered, not |
| 165 | +// wherever that URI happens to point today. |
| 166 | +func (h *Handler) backchannelClient() *http.Client { |
| 167 | + if h.HTTPClient != nil { |
| 168 | + return h.HTTPClient |
| 169 | + } |
| 170 | + return &http.Client{ |
| 171 | + CheckRedirect: func(*http.Request, []*http.Request) error { |
| 172 | + return http.ErrUseLastResponse |
| 173 | + }, |
| 174 | + } |
| 175 | +} |
0 commit comments