-
Notifications
You must be signed in to change notification settings - Fork 28
/
domain.go
473 lines (401 loc) · 11 KB
/
domain.go
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package service
import (
"context"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net"
"sort"
"strings"
"time"
"github.com/lib/pq"
"golang.org/x/net/publicsuffix"
"github.com/authgear/authgear-server/pkg/api/apierrors"
apimodel "github.com/authgear/authgear-server/pkg/api/model"
"github.com/authgear/authgear-server/pkg/lib/infra/db"
"github.com/authgear/authgear-server/pkg/lib/infra/db/globaldb"
"github.com/authgear/authgear-server/pkg/util/clock"
"github.com/authgear/authgear-server/pkg/util/httputil"
corerand "github.com/authgear/authgear-server/pkg/util/rand"
"github.com/authgear/authgear-server/pkg/util/uuid"
)
const DomainVerificationTimeout = 10 * time.Second
var ErrDomainDuplicated = apierrors.AlreadyExists.WithReason("DuplicatedDomain").
New("requested domain is already in use")
var ErrDomainVerified = apierrors.AlreadyExists.WithReason("DomainVerified").
New("requested domain is already verified")
var ErrDomainNotFound = apierrors.NotFound.WithReason("DomainNotFound").
New("domain not found")
var ErrDomainNotCustom = apierrors.Forbidden.WithReason("DomainNotCustom").
New("requested domain is not a custom domain")
var DomainVerificationFailed = apierrors.Forbidden.WithReason("DomainVerificationFailed")
var InvalidDomain = apierrors.Invalid.WithReason("InvalidDomain")
type DomainConfigService interface {
CreateDomain(appID string, domainID string, domain string, isCustom bool) error
DeleteDomain(domain *apimodel.Domain) error
}
type DomainService struct {
Context context.Context
Clock clock.Clock
DomainConfig DomainConfigService
SQLBuilder *globaldb.SQLBuilder
SQLExecutor *globaldb.SQLExecutor
}
func (s *DomainService) GetMany(ids []string) ([]*apimodel.Domain, error) {
var rawIDs []string
for _, id := range ids {
_, rawID, ok := parseDomainID(id)
if ok {
rawIDs = append(rawIDs, rawID)
}
}
pendingDomains, err := s.listDomains(rawIDs, false)
if err != nil {
return nil, err
}
domains, err := s.listDomains(rawIDs, true)
if err != nil {
return nil, err
}
var out []*apimodel.Domain
out = append(out, pendingDomains...)
out = append(out, domains...)
return out, nil
}
func (s *DomainService) ListDomains(appID string) ([]*apimodel.Domain, error) {
pendingDomains, err := s.listDomainsByAppID(appID, false)
if err != nil {
return nil, err
}
domains, err := s.listDomainsByAppID(appID, true)
if err != nil {
return nil, err
}
result := append(pendingDomains, domains...)
sort.Slice(result, func(i, j int) bool {
return result[i].Domain < result[j].Domain
})
return result, nil
}
func (s *DomainService) CreateCustomDomain(appID string, domain string) (*apimodel.Domain, error) {
return s.CreateDomain(appID, domain, false, true)
}
func (s *DomainService) CreateDomain(appID string, domain string, isVerified bool, isCustom bool) (*apimodel.Domain, error) {
d, err := newDomain(appID, domain, s.Clock.NowUTC(), isCustom)
if err != nil {
return nil, err
}
if !isCustom {
// For non-custom domain, assume the domain is always an apex domain,
// in case the domain suffix is not yet in PSL.
d.ApexDomain = d.Domain
}
err = s.createDomain(d, isVerified)
if err != nil {
return nil, err
}
domainModel := d.toModel(isVerified)
if isVerified {
err = s.DomainConfig.CreateDomain(appID, domainModel.ID, domainModel.Domain, domainModel.IsCustom)
if err != nil {
return nil, err
}
}
return domainModel, nil
}
func (s *DomainService) DeleteDomain(appID string, id string) error {
isVerified, id, ok := parseDomainID(id)
if !ok {
return ErrDomainNotFound
}
d, err := s.getDomain(appID, id, isVerified)
if err != nil {
return err
}
err = s.deleteDomain(d, isVerified)
if err != nil {
return err
}
err = s.DomainConfig.DeleteDomain(d.toModel(isVerified))
if err != nil {
return err
}
return nil
}
func (s *DomainService) listDomains(ids []string, isVerified bool) ([]*apimodel.Domain, error) {
rows, err := s.SQLExecutor.QueryWith(
s.SQLBuilder.
Select("id", "app_id", "created_at", "domain", "apex_domain", "verification_nonce", "is_custom").
Where("id = ANY (?)", pq.Array(ids)).
From(s.SQLBuilder.TableName(domainTableName(isVerified))),
)
if err != nil {
return nil, err
}
defer rows.Close()
var domains []*apimodel.Domain
for rows.Next() {
d, err := scanDomain(rows)
if err != nil {
return nil, err
}
domains = append(domains, d.toModel(isVerified))
}
return domains, nil
}
func (s *DomainService) listDomainsByAppID(appID string, isVerified bool) ([]*apimodel.Domain, error) {
rows, err := s.SQLExecutor.QueryWith(
s.SQLBuilder.
Select("id", "app_id", "created_at", "domain", "apex_domain", "verification_nonce", "is_custom").
Where("app_id = ?", appID).
From(s.SQLBuilder.TableName(domainTableName(isVerified))),
)
if err != nil {
return nil, err
}
defer rows.Close()
var domains []*apimodel.Domain
for rows.Next() {
d, err := scanDomain(rows)
if err != nil {
return nil, err
}
domains = append(domains, d.toModel(isVerified))
}
return domains, nil
}
func (s *DomainService) VerifyDomain(appID string, id string) (*apimodel.Domain, error) {
isVerified, id, ok := parseDomainID(id)
if !ok {
return nil, ErrDomainNotFound
}
if isVerified {
return nil, ErrDomainVerified
}
d, err := s.getDomain(appID, id, false)
if err != nil {
return nil, err
}
err = s.verifyDomain(d)
if err != nil {
return nil, DomainVerificationFailed.Errorf("domain verification failed: %w", err)
}
// Migrate the domain from pending domains to domains
err = s.deleteDomain(d, false)
if err != nil {
return nil, err
}
d.CreatedAt = s.Clock.NowUTC()
err = s.createDomain(d, true)
if err != nil {
return nil, err
}
domainModel := d.toModel(true)
err = s.DomainConfig.CreateDomain(appID, domainModel.ID, domainModel.Domain, domainModel.IsCustom)
if err != nil {
return nil, err
}
return domainModel, nil
}
func (s *DomainService) verifyDomain(domain *domain) error {
ctx, cancel := context.WithTimeout(s.Context, DomainVerificationTimeout)
defer cancel()
resolver := &net.Resolver{}
txtRecords, err := resolver.LookupTXT(ctx, domain.ApexDomain)
if err != nil {
return fmt.Errorf("failed to fetch TXT record: %w", err)
}
expectedRecord := domainVerificationDNSRecord(domain.VerificationNonce)
found := false
for _, record := range txtRecords {
if record == expectedRecord {
found = true
break
}
}
if !found {
return errors.New("expected TXT record not found")
}
return nil
}
func (s *DomainService) getDomain(appID string, id string, isVerified bool) (*domain, error) {
row, err := s.SQLExecutor.QueryRowWith(
s.SQLBuilder.
Select("id", "app_id", "created_at", "domain", "apex_domain", "verification_nonce", "is_custom").
Where("app_id = ? AND id = ?", appID, id).
From(s.SQLBuilder.TableName(domainTableName(isVerified))),
)
if err != nil {
return nil, err
}
return scanDomain(row)
}
func (s *DomainService) createDomain(d *domain, isVerified bool) error {
tableName := domainTableName(isVerified)
dupeQuery := s.SQLBuilder.
Select("COUNT(*)").
From(s.SQLBuilder.TableName(tableName))
dupeQuery = dupeQuery.Where("apex_domain = ?", d.ApexDomain)
if !isVerified {
// Limit duplication query to within app for pending domains
dupeQuery = dupeQuery.Where("app_id = ?", d.AppID)
}
scanner, err := s.SQLExecutor.QueryRowWith(dupeQuery)
if err != nil {
return err
}
var count uint64
if err = scanner.Scan(&count); err != nil {
return err
}
if count >= 1 {
return ErrDomainDuplicated
}
_, err = s.SQLExecutor.ExecWith(s.SQLBuilder.
Insert(s.SQLBuilder.TableName(tableName)).
Columns(
"id",
"app_id",
"created_at",
"domain",
"apex_domain",
"verification_nonce",
"is_custom",
).
Values(
d.ID,
d.AppID,
d.CreatedAt,
d.Domain,
d.ApexDomain,
d.VerificationNonce,
d.IsCustom,
),
)
if err != nil {
return err
}
return nil
}
func (s *DomainService) deleteDomain(d *domain, isVerified bool) error {
if !d.IsCustom {
return ErrDomainNotCustom
}
_, err := s.SQLExecutor.ExecWith(s.SQLBuilder.
Delete(s.SQLBuilder.TableName(domainTableName(isVerified))).
Where("id = ?", d.ID),
)
if err != nil {
return err
}
return nil
}
type domain struct {
ID string
AppID string
CreatedAt time.Time
Domain string
ApexDomain string
VerificationNonce string
IsCustom bool
}
func scanDomain(scn db.Scanner) (*domain, error) {
d := &domain{}
err := scn.Scan(
&d.ID,
&d.AppID,
&d.CreatedAt,
&d.Domain,
&d.ApexDomain,
&d.VerificationNonce,
&d.IsCustom,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrDomainNotFound
} else if err != nil {
return nil, err
}
return d, nil
}
func MakeVerificationNonce() string {
nonce := make([]byte, 16)
corerand.SecureRand.Read(nonce)
verificationNonce := hex.EncodeToString(nonce)
return verificationNonce
}
func newDomain(appID string, domainName string, createdAt time.Time, isCustom bool) (*domain, error) {
verificationNonce := MakeVerificationNonce()
apexDomain, err := publicsuffix.EffectiveTLDPlusOne(domainName)
if err != nil {
return nil, InvalidDomain.Errorf("invalid domain: %w", err)
}
return &domain{
ID: uuid.New(),
AppID: appID,
CreatedAt: createdAt,
Domain: domainName,
ApexDomain: apexDomain,
VerificationNonce: verificationNonce,
IsCustom: isCustom,
}, nil
}
func (d *domain) toModel(isVerified bool) *apimodel.Domain {
var prefix string
if isVerified {
prefix = "verified:"
} else {
prefix = "pending:"
}
// for default domain, original domain will be used for cookie domain
// for custom domain, cookie domain is derived from the
// CookieDomainWithoutPort function
cookieDomain := d.Domain
if d.IsCustom {
cookieDomain = httputil.CookieDomainWithoutPort(d.Domain)
}
return &apimodel.Domain{
// Base64-encoded to avoid invalid k8s resource label invalid chars
ID: base64.RawURLEncoding.EncodeToString([]byte(prefix + d.ID)),
AppID: d.AppID,
CreatedAt: d.CreatedAt,
Domain: d.Domain,
CookieDomain: cookieDomain,
ApexDomain: d.ApexDomain,
VerificationDNSRecord: domainVerificationDNSRecord(d.VerificationNonce),
IsCustom: d.IsCustom,
IsVerified: isVerified,
}
}
func parseDomainID(modelID string) (isVerified bool, id string, ok bool) {
// Base64-encoded to avoid invalid k8s resource label invalid chars
rawID, err := base64.RawURLEncoding.DecodeString(modelID)
if err != nil {
return
}
parts := strings.Split(string(rawID), ":")
if len(parts) != 2 {
return
}
switch parts[0] {
case "verified":
isVerified = true
case "pending":
isVerified = false
default:
return
}
id = parts[1]
ok = true
return
}
func domainTableName(isVerified bool) string {
if isVerified {
return "_portal_domain"
}
return "_portal_pending_domain"
}
func domainVerificationDNSRecord(nonce string) string {
return fmt.Sprintf("authgear-verification=%s", nonce)
}