-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmsgraph.go
More file actions
395 lines (353 loc) · 14 KB
/
Copy pathmsgraph.go
File metadata and controls
395 lines (353 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Package msgraph is a minimal Microsoft Graph client for the chat Teams
// integration. It supports the client-credentials (app-only) OAuth2 flow and
// creating an onlineMeeting. Only the surface room-service needs is exposed,
// and it sits behind the Client interface so the meetings RPC can be unit
// tested against a mock without reaching Azure.
package msgraph
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// Client is the Graph surface room-service depends on. Only the meetings RPC
// touches Graph, so this is intentionally tiny. Mocked in tests.
type Client interface {
// CreateOnlineMeeting creates (or returns the existing) onlineMeeting on
// behalf of the configured organizer and returns its ID and join URL. It
// uses Graph's idempotent createOrGet endpoint keyed on req.ExternalID, so
// concurrent or repeated calls with the same ExternalID return the same
// meeting — Graph itself is the idempotency source of truth.
CreateOnlineMeeting(ctx context.Context, req CreateOnlineMeetingRequest) (*OnlineMeeting, error)
}
// DirectoryReader resolves accounts to directory users. Kept separate from
// Client so consumers that only need meetings (room-service) don't depend on
// the user-lookup surface. App-only (User.Read.All).
type DirectoryReader interface {
// GetUsersByAccounts resolves account local-parts to users by matching
// startsWith(userPrincipalName,'account@') — domain-agnostic, so accounts
// under different domains still resolve. Accounts are batched into chunked
// $filter queries.
GetUsersByAccounts(ctx context.Context, accounts []string) ([]GraphUser, error)
}
// NewDirectoryClient returns an app-only directory reader (shares the graph
// client used for meetings; New always returns a *graphClient).
func NewDirectoryClient(cfg Config, opts ...Option) DirectoryReader {
return New(cfg, opts...).(*graphClient)
}
// GraphUser is the subset of a Graph user resource the presence sync needs.
type GraphUser struct {
ID string `json:"id"`
Mail string `json:"mail"`
UserPrincipalName string `json:"userPrincipalName"`
}
// CreateOnlineMeetingRequest carries the attributes used to create a meeting.
type CreateOnlineMeetingRequest struct {
// ExternalID is the stable per-room idempotency key passed to Graph's
// createOrGet endpoint. Graph guarantees exactly one meeting per
// (organizer, externalId), so repeated/concurrent calls with the same
// ExternalID return the same meeting instead of creating duplicates.
// Required: createOrGet rejects an empty externalId.
ExternalID string
// Subject is the meeting title shown in Teams.
Subject string
// OrganizerEmail is the user the meeting is created for (the organizer).
// When empty the application-context default mailbox is used.
OrganizerEmail string
// AttendeeEmails are the invited attendees (excluding the organizer).
AttendeeEmails []string
}
// OnlineMeeting is the subset of the Graph onlineMeeting resource we return.
type OnlineMeeting struct {
ID string `json:"id"`
JoinURL string `json:"joinWebUrl"`
}
// Config holds the Azure app-registration credentials and tenant.
type Config struct {
TenantID string
ClientID string
ClientSecret string
// TLSInsecureSkipVerify disables Graph TLS verification. Opt-in, dev/on-prem
// only (e.g. a self-signed cert fronting Graph). Never enable in production.
TLSInsecureSkipVerify bool
}
const (
defaultGraphBaseURL = "https://graph.microsoft.com/v1.0"
graphScope = "https://graph.microsoft.com/.default"
// tokenExpirySkew is subtracted from the token's reported lifetime so the
// cached token is refreshed before the server-side expiry.
tokenExpirySkew = 60 * time.Second
)
// graphClient is the live (*Client) implementation.
type graphClient struct {
cfg Config
httpClient *http.Client
baseURL string
tokenURL string
mu sync.Mutex
token string
tokenAt time.Time // when the cached token expires
}
// Option customizes the client (used in tests to point at an httptest server).
type Option func(*graphClient)
// WithHTTPClient overrides the HTTP client.
func WithHTTPClient(c *http.Client) Option {
return func(g *graphClient) { g.httpClient = c }
}
// WithBaseURL overrides the Graph API base URL (no trailing slash).
func WithBaseURL(u string) Option {
return func(g *graphClient) { g.baseURL = strings.TrimRight(u, "/") }
}
// WithTokenURL overrides the OAuth2 token endpoint.
func WithTokenURL(u string) Option {
return func(g *graphClient) { g.tokenURL = u }
}
// New constructs a live Graph client for the given config.
func New(cfg Config, opts ...Option) Client {
hc := &http.Client{Timeout: 30 * time.Second}
if cfg.TLSInsecureSkipVerify {
// Clone the default transport so proxy (ProxyFromEnvironment) and dial
// settings survive — an on-prem Graph behind a self-signed cert is the
// scenario most likely to also sit behind a corporate proxy.
tr := http.DefaultTransport.(*http.Transport).Clone()
// #nosec G402 -- InsecureSkipVerify is opt-in via TLSInsecureSkipVerify config for dev/on-prem environments
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12} //nolint:gosec
hc.Transport = tr
}
g := &graphClient{
cfg: cfg,
httpClient: hc,
baseURL: defaultGraphBaseURL,
tokenURL: fmt.Sprintf(
"https://login.microsoftonline.com/%s/oauth2/v2.0/token",
url.PathEscape(cfg.TenantID),
),
}
for _, opt := range opts {
opt(g)
}
return g
}
type tokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Error string `json:"error"`
ErrorDesc string `json:"error_description"`
}
// accessToken returns a cached bearer token, fetching a fresh one via the
// client-credentials grant when the cache is empty or near expiry.
func (g *graphClient) accessToken(ctx context.Context) (string, error) {
g.mu.Lock()
defer g.mu.Unlock()
if g.token != "" && time.Now().Before(g.tokenAt) {
return g.token, nil
}
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", g.cfg.ClientID)
form.Set("client_secret", g.cfg.ClientSecret)
form.Set("scope", graphScope)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.tokenURL, strings.NewReader(form.Encode()))
if err != nil {
return "", fmt.Errorf("build token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := g.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request token: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return "", fmt.Errorf("read token response: %w", err)
}
var tr tokenResponse
if err := json.Unmarshal(body, &tr); err != nil {
return "", fmt.Errorf("decode token response (status %d): %w", resp.StatusCode, err)
}
if resp.StatusCode != http.StatusOK || tr.AccessToken == "" {
// Never log the credentials; surface the OAuth error code/description only.
return "", fmt.Errorf("token endpoint returned status %d: %s", resp.StatusCode, tr.Error)
}
g.token = tr.AccessToken
lifetime := time.Duration(tr.ExpiresIn) * time.Second
if lifetime <= tokenExpirySkew {
lifetime = tokenExpirySkew
}
g.tokenAt = time.Now().Add(lifetime - tokenExpirySkew)
return g.token, nil
}
// maxUserFilterClauses caps startsWith clauses per $filter query. Microsoft
// Graph rejects overly complex filters, so accounts are looked up in chunks.
const maxUserFilterClauses = 15
// maxAccountsPerQuery bounds accounts per query. Each account emits both a
// lower- and upper-cased startsWith clause (see casedVariants), so up to two
// clauses each — keep the total within maxUserFilterClauses.
const maxAccountsPerQuery = maxUserFilterClauses / 2
// GetUsersByAccounts resolves account local-parts to users, matching
// startsWith(userPrincipalName,'account@') so any domain resolves. Both the
// lower- and upper-cased account are matched (rather than relying on Graph's
// case-insensitivity). Accounts are batched into chunked $filter queries.
func (g *graphClient) GetUsersByAccounts(ctx context.Context, accounts []string) ([]GraphUser, error) {
if len(accounts) == 0 {
return nil, nil
}
token, err := g.accessToken(ctx)
if err != nil {
return nil, fmt.Errorf("acquire graph token: %w", err)
}
var out []GraphUser
for start := 0; start < len(accounts); start += maxAccountsPerQuery {
end := min(start+maxAccountsPerQuery, len(accounts))
batch, err := g.usersByAccountChunk(ctx, token, accounts[start:end])
if err != nil {
return nil, err
}
out = append(out, batch...)
}
return out, nil
}
// casedVariants returns the lower- and upper-cased forms of s (deduped when the
// value has no cased letters), so the startsWith filter matches accounts stored
// in either case.
func casedVariants(s string) []string {
lower, upper := strings.ToLower(s), strings.ToUpper(s)
if lower == upper {
return []string{lower}
}
return []string{lower, upper}
}
func (g *graphClient) usersByAccountChunk(ctx context.Context, token string, chunk []string) ([]GraphUser, error) {
clauses := make([]string, 0, len(chunk)*2)
for _, a := range chunk {
for _, variant := range casedVariants(a) {
// Escape single quotes for the OData string literal.
esc := strings.ReplaceAll(variant, "'", "''")
clauses = append(clauses, fmt.Sprintf("startsWith(userPrincipalName,'%s@')", esc))
}
}
q := url.Values{}
q.Set("$filter", strings.Join(clauses, " or "))
q.Set("$select", "id,mail,userPrincipalName")
q.Set("$count", "true")
q.Set("$top", "999")
endpoint := g.baseURL + "/users?" + q.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("build get-users request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
// startsWith on userPrincipalName is an advanced query — Graph requires
// eventual consistency (paired with $count).
req.Header.Set("ConsistencyLevel", "eventual")
resp, err := g.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("get users: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<22))
if err != nil {
return nil, fmt.Errorf("read get-users response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("get users: graph returned status %d", resp.StatusCode)
}
var page struct {
Value []GraphUser `json:"value"`
}
if err := json.Unmarshal(body, &page); err != nil {
return nil, fmt.Errorf("decode get-users response: %w", err)
}
return page.Value, nil
}
// onlineMeetingPayload is the Graph createOrGet-onlineMeeting request body.
// externalId is required by createOrGet and is the per-room idempotency key.
type onlineMeetingPayload struct {
ExternalID string `json:"externalId"`
Subject string `json:"subject,omitempty"`
Participants *meetingParticipants `json:"participants,omitempty"`
}
type meetingParticipants struct {
Attendees []meetingAttendee `json:"attendees,omitempty"`
}
type meetingAttendee struct {
Upn string `json:"upn"`
}
func (g *graphClient) CreateOnlineMeeting(ctx context.Context, req CreateOnlineMeetingRequest) (*OnlineMeeting, error) {
if req.ExternalID == "" {
return nil, fmt.Errorf("create onlineMeeting: externalId is required for createOrGet idempotency")
}
token, err := g.accessToken(ctx)
if err != nil {
return nil, fmt.Errorf("acquire graph token: %w", err)
}
// createOrGet pushes idempotency to Graph: it returns the existing meeting
// for an (organizer, externalId) pair if one exists, otherwise creates one.
// App-only context requires targeting a specific organizer mailbox via the
// /users/{id}/onlineMeetings/createOrGet path; delegated context uses /me.
// We use the organizer-scoped path when an organizer email is supplied.
var endpoint string
if req.OrganizerEmail != "" {
endpoint = fmt.Sprintf("%s/users/%s/onlineMeetings/createOrGet", g.baseURL, url.PathEscape(req.OrganizerEmail))
} else {
endpoint = g.baseURL + "/me/onlineMeetings/createOrGet"
}
payload := onlineMeetingPayload{ExternalID: req.ExternalID, Subject: req.Subject}
if len(req.AttendeeEmails) > 0 {
attendees := make([]meetingAttendee, 0, len(req.AttendeeEmails))
for _, email := range req.AttendeeEmails {
attendees = append(attendees, meetingAttendee{Upn: email})
}
payload.Participants = &meetingParticipants{Attendees: attendees}
}
bodyBytes, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("marshal onlineMeeting payload: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(bodyBytes))
if err != nil {
return nil, fmt.Errorf("build onlineMeeting request: %w", err)
}
httpReq.Header.Set("Authorization", "Bearer "+token)
httpReq.Header.Set("Content-Type", "application/json")
resp, err := g.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("create onlineMeeting: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return nil, fmt.Errorf("read onlineMeeting response: %w", err)
}
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
// Never wrap the raw response body into the error/cause — it can carry
// upstream payload. Parse the Graph error envelope and surface only the
// status + sanitized error code.
var graphErr struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
_ = json.Unmarshal(respBody, &graphErr)
if graphErr.Error.Code != "" {
return nil, fmt.Errorf("create onlineMeeting: graph returned status %d (%s)", resp.StatusCode, graphErr.Error.Code)
}
return nil, fmt.Errorf("create onlineMeeting: graph returned status %d", resp.StatusCode)
}
var meeting OnlineMeeting
if err := json.Unmarshal(respBody, &meeting); err != nil {
return nil, fmt.Errorf("decode onlineMeeting response: %w", err)
}
if meeting.JoinURL == "" {
return nil, fmt.Errorf("create onlineMeeting: graph response missing joinWebUrl")
}
return &meeting, nil
}