|
| 1 | +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package storage |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "net/url" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + lru "github.com/hashicorp/golang-lru/v2" |
| 14 | + "github.com/ory/fosite" |
| 15 | + "golang.org/x/sync/singleflight" |
| 16 | + |
| 17 | + "github.com/stacklok/toolhive/pkg/authserver/server/registration" |
| 18 | + "github.com/stacklok/toolhive/pkg/oauthproto" |
| 19 | + "github.com/stacklok/toolhive/pkg/oauthproto/cimd" |
| 20 | +) |
| 21 | + |
| 22 | +// CIMDStorageDecorator wraps storage.Storage and intercepts GetClient calls |
| 23 | +// for HTTPS client_id values, fetching and caching the corresponding Client |
| 24 | +// ID Metadata Document instead of requiring prior DCR registration. |
| 25 | +// |
| 26 | +// All other Storage methods delegate to the underlying storage unchanged. |
| 27 | +// Only GetClient is overridden. DCR clients (opaque IDs) continue to work |
| 28 | +// exactly as before. |
| 29 | +type CIMDStorageDecorator struct { |
| 30 | + Storage // embed full interface — all methods delegate |
| 31 | + sf singleflight.Group // deduplicates concurrent fetches for the same URL |
| 32 | + cache *lru.Cache[string, *cimdCacheEntry] |
| 33 | + ttl time.Duration |
| 34 | +} |
| 35 | + |
| 36 | +type cimdCacheEntry struct { |
| 37 | + client fosite.Client |
| 38 | + expires time.Time |
| 39 | +} |
| 40 | + |
| 41 | +// NewCIMDStorageDecorator wraps base with CIMD client lookup. When enabled=false |
| 42 | +// it returns base unchanged (no allocation). cacheMaxSize must be >= 1; |
| 43 | +// fallbackTTL is the fixed TTL applied to every cache entry (Cache-Control |
| 44 | +// header parsing is not yet implemented; all entries use this value). |
| 45 | +func NewCIMDStorageDecorator( |
| 46 | + base Storage, |
| 47 | + enabled bool, |
| 48 | + cacheMaxSize int, |
| 49 | + fallbackTTL time.Duration, |
| 50 | +) (Storage, error) { |
| 51 | + if !enabled { |
| 52 | + return base, nil |
| 53 | + } |
| 54 | + |
| 55 | + if cacheMaxSize < 1 { |
| 56 | + return nil, fmt.Errorf("CIMD storage decorator cacheMaxSize must be >= 1, got %d", cacheMaxSize) |
| 57 | + } |
| 58 | + |
| 59 | + c, err := lru.New[string, *cimdCacheEntry](cacheMaxSize) |
| 60 | + if err != nil { |
| 61 | + return nil, fmt.Errorf("failed to create CIMD LRU cache: %w", err) |
| 62 | + } |
| 63 | + |
| 64 | + return &CIMDStorageDecorator{ |
| 65 | + Storage: base, |
| 66 | + cache: c, |
| 67 | + ttl: fallbackTTL, |
| 68 | + }, nil |
| 69 | +} |
| 70 | + |
| 71 | +// GetClient intercepts HTTPS client_id values to resolve them via CIMD. |
| 72 | +// Opaque DCR-issued IDs are delegated to the underlying storage unchanged. |
| 73 | +func (d *CIMDStorageDecorator) GetClient(ctx context.Context, id string) (fosite.Client, error) { |
| 74 | + if !oauthproto.IsClientIDMetadataDocumentURL(id) { |
| 75 | + return d.Storage.GetClient(ctx, id) |
| 76 | + } |
| 77 | + return d.fetchOrCached(ctx, id) |
| 78 | +} |
| 79 | + |
| 80 | +// Unwrap returns the underlying storage so that type assertions (e.g. for |
| 81 | +// storage.DCRCredentialStore in server_impl.go) can reach the concrete type. |
| 82 | +func (d *CIMDStorageDecorator) Unwrap() Storage { |
| 83 | + return d.Storage |
| 84 | +} |
| 85 | + |
| 86 | +func (d *CIMDStorageDecorator) fetchOrCached(ctx context.Context, id string) (fosite.Client, error) { |
| 87 | + // Check cache first (outside singleflight to avoid holding the group lock for cache hits) |
| 88 | + if entry, ok := d.cache.Get(id); ok && time.Now().Before(entry.expires) { |
| 89 | + return entry.client, nil |
| 90 | + } |
| 91 | + |
| 92 | + // Deduplicate concurrent fetches for the same URL. The shared fetch uses a |
| 93 | + // context detached from the caller so that one caller cancelling does not |
| 94 | + // abort the in-flight request for other waiters. The HTTP client inside |
| 95 | + // FetchClientMetadataDocument enforces its own 5-second timeout. |
| 96 | + fetchCtx := context.WithoutCancel(ctx) |
| 97 | + result, err, _ := d.sf.Do(id, func() (interface{}, error) { |
| 98 | + // Re-check cache inside singleflight (another goroutine may have populated it) |
| 99 | + if entry, ok := d.cache.Get(id); ok && time.Now().Before(entry.expires) { |
| 100 | + return entry.client, nil |
| 101 | + } |
| 102 | + return d.fetch(fetchCtx, id) |
| 103 | + }) |
| 104 | + if err != nil { |
| 105 | + return nil, err |
| 106 | + } |
| 107 | + client, ok := result.(fosite.Client) |
| 108 | + if !ok { |
| 109 | + return nil, fmt.Errorf("CIMD singleflight returned unexpected type %T", result) |
| 110 | + } |
| 111 | + return client, nil |
| 112 | +} |
| 113 | + |
| 114 | +func (d *CIMDStorageDecorator) fetch(ctx context.Context, id string) (fosite.Client, error) { |
| 115 | + doc, err := cimd.FetchClientMetadataDocument(ctx, id) |
| 116 | + if err != nil { |
| 117 | + return nil, fmt.Errorf("%w: %w", fosite.ErrNotFound.WithHint("CIMD fetch failed"), err) |
| 118 | + } |
| 119 | + |
| 120 | + // Reject documents that declare an auth method this AS does not support. |
| 121 | + // The embedded AS only advertises "none"; accepting a doc that says |
| 122 | + // "private_key_jwt" and then silently treating the client as public would |
| 123 | + // mislead operators and break clients that actually try to use JWT assertions. |
| 124 | + if m := doc.TokenEndpointAuthMethod; m != "" && m != defaultCIMDTokenEndpointAuthMethod { |
| 125 | + return nil, fmt.Errorf("%w: CIMD document at %s claims token_endpoint_auth_method %q "+ |
| 126 | + "but this server only supports %q", |
| 127 | + fosite.ErrNotFound.WithHint("unsupported token_endpoint_auth_method"), |
| 128 | + id, m, defaultCIMDTokenEndpointAuthMethod) |
| 129 | + } |
| 130 | + |
| 131 | + client := buildFositeClient(doc) |
| 132 | + |
| 133 | + d.cache.Add(id, &cimdCacheEntry{ |
| 134 | + client: client, |
| 135 | + expires: time.Now().Add(d.ttl), |
| 136 | + }) |
| 137 | + |
| 138 | + return client, nil |
| 139 | +} |
| 140 | + |
| 141 | +// defaultCIMDGrantTypes are the OAuth 2.0 grant types applied when the CIMD |
| 142 | +// document omits grant_types. CIMD clients are typically public native apps |
| 143 | +// that use the authorization code flow with refresh token rotation. |
| 144 | +var defaultCIMDGrantTypes = []string{"authorization_code", "refresh_token"} |
| 145 | + |
| 146 | +// defaultCIMDResponseTypes are the OAuth 2.0 response types applied when the |
| 147 | +// CIMD document omits response_types. |
| 148 | +var defaultCIMDResponseTypes = []string{"code"} |
| 149 | + |
| 150 | +// defaultCIMDTokenEndpointAuthMethod is the token endpoint authentication |
| 151 | +// method applied when the CIMD document omits token_endpoint_auth_method. |
| 152 | +// Documents that declare any other value are rejected by fetch() before |
| 153 | +// buildFositeClient is called. |
| 154 | +const defaultCIMDTokenEndpointAuthMethod = "none" |
| 155 | + |
| 156 | +// buildFositeClient converts a ClientMetadataDocument into a fosite.Client. |
| 157 | +// Redirect URIs containing http://localhost are wrapped in a LoopbackClient |
| 158 | +// so that RFC 8252 §7.3 dynamic port matching applies. |
| 159 | +func buildFositeClient(doc *cimd.ClientMetadataDocument) fosite.Client { |
| 160 | + grantTypes := doc.GrantTypes |
| 161 | + if len(grantTypes) == 0 { |
| 162 | + grantTypes = defaultCIMDGrantTypes |
| 163 | + } |
| 164 | + |
| 165 | + responseTypes := doc.ResponseTypes |
| 166 | + if len(responseTypes) == 0 { |
| 167 | + responseTypes = defaultCIMDResponseTypes |
| 168 | + } |
| 169 | + |
| 170 | + tokenEndpointAuthMethod := doc.TokenEndpointAuthMethod |
| 171 | + if tokenEndpointAuthMethod == "" { |
| 172 | + tokenEndpointAuthMethod = defaultCIMDTokenEndpointAuthMethod |
| 173 | + } |
| 174 | + |
| 175 | + var scopes []string |
| 176 | + if doc.Scope != "" { |
| 177 | + scopes = strings.Fields(doc.Scope) |
| 178 | + } |
| 179 | + |
| 180 | + defaultClient := &fosite.DefaultClient{ |
| 181 | + ID: doc.ClientID, |
| 182 | + RedirectURIs: doc.RedirectURIs, |
| 183 | + GrantTypes: grantTypes, |
| 184 | + ResponseTypes: responseTypes, |
| 185 | + Scopes: scopes, |
| 186 | + // CIMD clients don't pre-declare audience; leave empty so the AS |
| 187 | + // applies its own audience policy rather than rejecting all values. |
| 188 | + Audience: nil, |
| 189 | + Public: true, |
| 190 | + } |
| 191 | + |
| 192 | + openIDClient := &fosite.DefaultOpenIDConnectClient{ |
| 193 | + DefaultClient: defaultClient, |
| 194 | + TokenEndpointAuthMethod: tokenEndpointAuthMethod, |
| 195 | + } |
| 196 | + |
| 197 | + // Wrap in LoopbackClient when any redirect URI targets localhost so that |
| 198 | + // RFC 8252 §7.3 dynamic port matching works for native app clients. |
| 199 | + // Pass openIDClient directly so TokenEndpointAuthMethod is preserved — |
| 200 | + // LoopbackClient now embeds *fosite.DefaultOpenIDConnectClient. |
| 201 | + if hasLoopbackRedirectURI(doc.RedirectURIs) { |
| 202 | + return registration.NewLoopbackClient(openIDClient) |
| 203 | + } |
| 204 | + |
| 205 | + return openIDClient |
| 206 | +} |
| 207 | + |
| 208 | +// hasLoopbackRedirectURI returns true when any of the redirect URIs in the |
| 209 | +// list targets a loopback address over HTTP. The host is parsed from each URI |
| 210 | +// to prevent bypass via hosts like "http://localhost.evil.com/". |
| 211 | +func hasLoopbackRedirectURI(uris []string) bool { |
| 212 | + for _, uri := range uris { |
| 213 | + parsed, err := url.Parse(uri) |
| 214 | + if err != nil { |
| 215 | + continue |
| 216 | + } |
| 217 | + if parsed.Scheme == "http" && oauthproto.IsLoopbackHost(parsed.Hostname()) { |
| 218 | + return true |
| 219 | + } |
| 220 | + } |
| 221 | + return false |
| 222 | +} |
0 commit comments