BlueGit

timfa bluegit

Files

bluegit / internal / auth / entra.go

entra.go

entra.go 9.7 KiB Download Raw
1package auth
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12 "sync"
13 "time"
14
15 "gitlab.com/Timfa/bluegit/internal/names"
16)
17
18// Entra is Microsoft Entra ID (OIDC, één tenant).
19// Extend en Logout doen niets op afstand: Entra kent die TimFalken-API's niet.
20type Entra struct {
21 Issuer string
22 TenantID string
23 ClientID string
24 Secret string
25 UserAgent string
26 HTTP *http.Client
27
28 mu sync.Mutex
29 authz string
30 token string
31 jwks *jwksCache
32 jwksURI string
33}
34
35// NewEntra maakt een OIDC-client. issuer is zonder slash aan het eind
36// (standaard https://login.microsoftonline.com/{tenant}/v2.0).
37func NewEntra(issuer, tenantID, clientID, secret, userAgent string) *Entra {
38 return &Entra{
39 Issuer: strings.TrimRight(issuer, "/"),
40 TenantID: tenantID,
41 ClientID: clientID,
42 Secret: secret,
43 UserAgent: userAgent,
44 HTTP: &http.Client{Timeout: 15 * time.Second},
45 jwks: &jwksCache{},
46 }
47}
48
49// AuthorizeURL stuurt de browser naar Entra met openid-profile en nonce.
50func (e *Entra) AuthorizeURL(state, nonce, redirectURI string) string {
51 authz, err := e.authorizeEndpoint(context.Background())
52 if err != nil {
53 // Zonder discovery: vaste Entra-URL zodat /login niet paniceert.
54 authz = strings.TrimSuffix(e.Issuer, "/v2.0") + "/oauth2/v2.0/authorize"
55 }
56 q := url.Values{}
57 q.Set("client_id", e.ClientID)
58 q.Set("redirect_uri", redirectURI)
59 q.Set("response_type", "code")
60 q.Set("response_mode", "query")
61 q.Set("scope", "openid profile")
62 q.Set("state", state)
63 q.Set("nonce", nonce)
64 return authz + "?" + q.Encode()
65}
66
67// Exchange wisselt de code om, valideert het ID-token (JWKS, iss, aud, exp, nonce)
68// en mapt oid/tid naar een BlueGit-identity.
69func (e *Entra) Exchange(ctx context.Context, code, redirectURI, nonce string) (Identity, error) {
70 if nonce == "" {
71 return Identity{}, fmt.Errorf("auth: nonce ontbreekt")
72 }
73 tokenURL, err := e.tokenEndpoint(ctx)
74 if err != nil {
75 return Identity{}, err
76 }
77 form := url.Values{}
78 form.Set("grant_type", "authorization_code")
79 form.Set("code", code)
80 form.Set("redirect_uri", redirectURI)
81 form.Set("client_id", e.ClientID)
82 form.Set("client_secret", e.Secret)
83 form.Set("scope", "openid profile")
84 req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
85 if err != nil {
86 return Identity{}, err
87 }
88 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
89 req.Header.Set("Accept", "application/json")
90 if e.UserAgent != "" {
91 req.Header.Set("User-Agent", e.UserAgent)
92 }
93 var body struct {
94 AccessToken string `json:"access_token"`
95 IDToken string `json:"id_token"`
96 ExpiresIn int `json:"expires_in"`
97 Error string `json:"error"`
98 ErrorDesc string `json:"error_description"`
99 }
100 if err := e.doJSON(req, &body); err != nil {
101 return Identity{}, err
102 }
103 if body.Error != "" || body.IDToken == "" {
104 msg := body.Error
105 if body.ErrorDesc != "" {
106 msg = body.ErrorDesc
107 }
108 if msg == "" {
109 msg = "lege tokenrespons"
110 }
111 return Identity{}, fmt.Errorf("auth: %s", msg)
112 }
113 claims, err := e.verifyIDToken(ctx, body.IDToken, nonce)
114 if err != nil {
115 return Identity{}, err
116 }
117 oid := claims.OID
118 if oid == "" {
119 oid = claims.Sub
120 }
121 if oid == "" {
122 return Identity{}, fmt.Errorf("auth: id_token zonder oid/sub")
123 }
124 if claims.TID != "" && !strings.EqualFold(claims.TID, e.TenantID) {
125 return Identity{}, fmt.Errorf("auth: onverwachte tenant")
126 }
127 username, err := entraUsername(claims.PreferredUsername, claims.Email, claims.Name, oid)
128 if err != nil {
129 return Identity{}, err
130 }
131 return Identity{
132 AuthID: StableAuthID(e.TenantID, oid),
133 Username: username,
134 AvatarURL: "", // Entra levert geen avatar-URL zonder Graph-foto-API.
135 IsAdmin: false,
136 AccessToken: body.AccessToken,
137 ExpiresIn: 86400, // BlueGit-sessie; Entra's access_token is korter.
138 }, nil
139}
140
141// Extend verlengt alleen lokaal: Entra heeft geen /api/session/extend.
142func (e *Entra) Extend(ctx context.Context, accessToken string) (int, error) {
143 return 86400, nil
144}
145
146// Logout doet niets op afstand; BlueGit wist de lokale sessie zelf.
147func (e *Entra) Logout(ctx context.Context, accessToken string) error {
148 return nil
149}
150
151type idClaims struct {
152 Iss string `json:"iss"`
153 Aud jsonAudience `json:"aud"`
154 Exp int64 `json:"exp"`
155 Nbf int64 `json:"nbf"`
156 Nonce string `json:"nonce"`
157 OID string `json:"oid"`
158 Sub string `json:"sub"`
159 TID string `json:"tid"`
160 PreferredUsername string `json:"preferred_username"`
161 Email string `json:"email"`
162 Name string `json:"name"`
163}
164
165func (e *Entra) verifyIDToken(ctx context.Context, raw, nonce string) (idClaims, error) {
166 hdr, payload, err := parseJWT(raw)
167 if err != nil {
168 return idClaims{}, err
169 }
170 var claims idClaims
171 if err := json.Unmarshal(payload, &claims); err != nil {
172 return idClaims{}, fmt.Errorf("auth: id_token claims: %w", err)
173 }
174 if claims.Iss != e.Issuer {
175 return idClaims{}, fmt.Errorf("auth: ongeldige issuer")
176 }
177 if !claims.Aud.includes(e.ClientID) {
178 return idClaims{}, fmt.Errorf("auth: ongeldige audience")
179 }
180 now := time.Now().Unix()
181 if claims.Exp > 0 && now >= claims.Exp {
182 return idClaims{}, fmt.Errorf("auth: id_token verlopen")
183 }
184 if claims.Nbf > 0 && now < claims.Nbf-60 {
185 return idClaims{}, fmt.Errorf("auth: id_token nog niet geldig")
186 }
187 if claims.Nonce == "" || claims.Nonce != nonce {
188 return idClaims{}, fmt.Errorf("auth: ongeldige nonce")
189 }
190 if hdr.Alg != "RS256" {
191 return idClaims{}, fmt.Errorf("auth: onverwacht jwt-algorithme %q", hdr.Alg)
192 }
193 key, err := e.signingKey(ctx, hdr.Kid)
194 if err != nil {
195 return idClaims{}, err
196 }
197 if err := verifyRS256(raw, key); err != nil {
198 return idClaims{}, err
199 }
200 return claims, nil
201}
202
203func (e *Entra) signingKey(ctx context.Context, kid string) (any, error) {
204 if err := e.ensureDiscovery(ctx); err != nil {
205 return nil, err
206 }
207 return e.jwks.key(ctx, e.HTTP, e.jwksURI, kid)
208}
209
210func (e *Entra) authorizeEndpoint(ctx context.Context) (string, error) {
211 if err := e.ensureDiscovery(ctx); err != nil {
212 return "", err
213 }
214 e.mu.Lock()
215 defer e.mu.Unlock()
216 return e.authz, nil
217}
218
219func (e *Entra) tokenEndpoint(ctx context.Context) (string, error) {
220 if err := e.ensureDiscovery(ctx); err != nil {
221 return "", err
222 }
223 e.mu.Lock()
224 defer e.mu.Unlock()
225 return e.token, nil
226}
227
228func (e *Entra) ensureDiscovery(ctx context.Context) error {
229 e.mu.Lock()
230 if e.authz != "" && e.token != "" && e.jwksURI != "" {
231 e.mu.Unlock()
232 return nil
233 }
234 e.mu.Unlock()
235
236 req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Issuer+"/.well-known/openid-configuration", nil)
237 if err != nil {
238 return err
239 }
240 if e.UserAgent != "" {
241 req.Header.Set("User-Agent", e.UserAgent)
242 }
243 var doc struct {
244 AuthorizationEndpoint string `json:"authorization_endpoint"`
245 TokenEndpoint string `json:"token_endpoint"`
246 JWKSURI string `json:"jwks_uri"`
247 Issuer string `json:"issuer"`
248 }
249 if err := e.doJSON(req, &doc); err != nil {
250 return fmt.Errorf("auth: oidc discovery: %w", err)
251 }
252 if doc.AuthorizationEndpoint == "" || doc.TokenEndpoint == "" || doc.JWKSURI == "" {
253 return fmt.Errorf("auth: onvolledige oidc discovery")
254 }
255 if doc.Issuer != "" && doc.Issuer != e.Issuer {
256 return fmt.Errorf("auth: discovery-issuer wijkt af")
257 }
258 e.mu.Lock()
259 e.authz = doc.AuthorizationEndpoint
260 e.token = doc.TokenEndpoint
261 e.jwksURI = doc.JWKSURI
262 e.mu.Unlock()
263 return nil
264}
265
266func (e *Entra) doJSON(req *http.Request, dest any) error {
267 res, err := e.HTTP.Do(req)
268 if err != nil {
269 return fmt.Errorf("auth: %w", err)
270 }
271 defer res.Body.Close()
272 raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
273 if err != nil {
274 return err
275 }
276 if res.StatusCode >= 400 {
277 var env struct {
278 Error string `json:"error"`
279 ErrorDesc string `json:"error_description"`
280 }
281 _ = json.Unmarshal(raw, &env)
282 msg := env.ErrorDesc
283 if msg == "" {
284 msg = env.Error
285 }
286 if msg == "" {
287 msg = res.Status
288 }
289 return fmt.Errorf("auth: %s", msg)
290 }
291 if dest == nil {
292 return nil
293 }
294 if err := json.Unmarshal(raw, dest); err != nil {
295 return fmt.Errorf("auth-antwoord: %w", err)
296 }
297 return nil
298}
299
300// StableAuthID maakt een positieve int64 uit tenant + object-id.
301// Collisie is theoretisch mogelijk; bij een botsing krijgt de tweede gebruiker
302// dezelfde auth_id (upsert op bestaande rij).
303func StableAuthID(tenantID, objectID string) int64 {
304 sum := sha256.Sum256([]byte(tenantID + "\x00" + objectID))
305 var n uint64
306 for i := 0; i < 8; i++ {
307 n = n<<8 | uint64(sum[i])
308 }
309 n &^= 1 << 63
310 if n == 0 {
311 n = 1
312 }
313 return int64(n)
314}
315
316// entraUsername maakt een BlueGit-gebruikersnaam uit Entra-claims.
317func entraUsername(preferred, email, display, oid string) (string, error) {
318 raw := strings.TrimSpace(preferred)
319 if raw == "" {
320 raw = strings.TrimSpace(email)
321 }
322 if i := strings.IndexByte(raw, '@'); i > 0 {
323 raw = raw[:i]
324 }
325 if raw == "" {
326 raw = strings.TrimSpace(display)
327 }
328 s := sanitizeUsername(raw)
329 if s == "" || names.ValidUsername(s) != nil {
330 sum := sha256.Sum256([]byte(oid))
331 s = fmt.Sprintf("u%x", sum[:4])
332 }
333 if err := names.ValidUsername(s); err != nil {
334 return "", fmt.Errorf("auth: geen bruikbare gebruikersnaam")
335 }
336 return s, nil
337}
338
339func sanitizeUsername(raw string) string {
340 s := strings.ToLower(strings.TrimSpace(raw))
341 var b strings.Builder
342 for _, r := range s {
343 switch {
344 case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '_', r == '-':
345 b.WriteRune(r)
346 case r == '.' || r == ' ':
347 b.WriteByte('-')
348 }
349 }
350 out := strings.Trim(b.String(), "-_")
351 for strings.Contains(out, "--") {
352 out = strings.ReplaceAll(out, "--", "-")
353 }
354 if len(out) > 63 {
355 out = strings.Trim(out[:63], "-_")
356 }
357 return out
358}