File size: 5,232 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package integrationkey

import (
	"context"
	"database/sql"
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
	"github.com/target/goalert/expflag"
	"github.com/target/goalert/gadb"
	"github.com/target/goalert/permission"
	"github.com/target/goalert/util/log"

	"github.com/target/goalert/validation"
	"github.com/target/goalert/validation/validate"
)

// Issuer is the JWT issuer for UIK API keys.
const Issuer = "goalert"

// Audience is the JWT audience for UIK API keys.
const Audience = "uik-key-v1"

func newClaims(keyID, tokenID uuid.UUID) jwt.Claims {
	n := time.Now()
	return jwt.RegisteredClaims{
		ID:        tokenID.String(),
		Subject:   keyID.String(),
		IssuedAt:  jwt.NewNumericDate(n),
		NotBefore: jwt.NewNumericDate(n.Add(-time.Minute)),
		Issuer:    Issuer,
		Audience:  []string{Audience},
	}
}

func (s *Store) AuthorizeUIK(ctx context.Context, tokStr string) (context.Context, error) {
	if !expflag.ContextHas(ctx, expflag.UnivKeys) {
		return ctx, permission.Unauthorized()
	}

	var claims jwt.RegisteredClaims
	_, err := s.keys.VerifyJWT(tokStr, &claims, Issuer, Audience)
	if err != nil {
		return ctx, permission.Unauthorized()
	}

	keyID, err := uuid.Parse(claims.Subject)
	if err != nil {
		log.Logf(ctx, "apikey: invalid subject: %v", err)
		return ctx, permission.Unauthorized()
	}
	tokID, err := uuid.Parse(claims.ID)
	if err != nil {
		log.Logf(ctx, "apikey: invalid token ID: %v", err)
		return ctx, permission.Unauthorized()
	}

	serviceID, err := gadb.New(s.db).IntKeyUIKValidateService(ctx, gadb.IntKeyUIKValidateServiceParams{
		KeyID:   keyID,
		TokenID: uuid.NullUUID{UUID: tokID, Valid: true},
	})
	if errors.Is(err, sql.ErrNoRows) {
		return ctx, permission.Unauthorized()
	}
	if err != nil {
		return ctx, err
	}

	ctx = permission.ServiceSourceContext(ctx, serviceID.String(), &permission.SourceInfo{
		Type: permission.SourceTypeUIK,
		ID:   keyID.String(),
	})

	return ctx, nil
}

func (s *Store) TokenHints(ctx context.Context, db gadb.DBTX, id uuid.UUID) (primary, secondary string, err error) {
	err = permission.LimitCheckAny(ctx, permission.User)
	if err != nil {
		return "", "", err
	}

	row, err := gadb.New(s.db).IntKeyTokenHints(ctx, id)
	if errors.Is(err, sql.ErrNoRows) {
		return "", "", nil
	}
	if err != nil {
		return "", "", err
	}

	return row.PrimaryTokenHint.String, row.SecondaryTokenHint.String, nil
}

func (s *Store) GenerateToken(ctx context.Context, db gadb.DBTX, id uuid.UUID) (string, error) {
	err := permission.LimitCheckAny(ctx, permission.User)
	if err != nil {
		return "", err
	}

	key, err := gadb.New(db).IntKeyFindOne(ctx, id)
	if err != nil {
		return "", err
	}
	if key.Type != gadb.EnumIntegrationKeysType(TypeUniversal) {
		return "", validation.NewFieldError("ID", "key is not a universal key")
	}

	tokID := uuid.New()
	tokStr, err := s.keys.SignJWT(newClaims(id, tokID))
	if err != nil {
		return "", err
	}

	hint := tokStr[:2] + "..." + tokStr[len(tokStr)-4:]

	err = s.setToken(ctx, db, id, tokID, hint)
	if err != nil {
		return "", err
	}

	return tokStr, nil
}

func (s *Store) setToken(ctx context.Context, db gadb.DBTX, keyID, tokenID uuid.UUID, tokenHint string) error {
	err := permission.LimitCheckAny(ctx, permission.User)
	if err != nil {
		return err
	}

	if err := validate.ASCII("Token Hint", tokenHint, 1, 32); err != nil {
		// not user specified, so return a generic error
		return errors.New("invalid token hint")
	}

	gdb := gadb.New(db)

	_, err = gdb.IntKeySetSecondaryToken(ctx, gadb.IntKeySetSecondaryTokenParams{
		ID:                 keyID,
		SecondaryToken:     uuid.NullUUID{UUID: tokenID, Valid: true},
		SecondaryTokenHint: sql.NullString{String: tokenHint, Valid: true},
	})
	if errors.Is(err, sql.ErrNoRows) {
		// it's possible there was never a primary token set
		_, err = gdb.IntKeySetPrimaryToken(ctx, gadb.IntKeySetPrimaryTokenParams{
			ID:               keyID,
			PrimaryToken:     uuid.NullUUID{UUID: tokenID, Valid: true},
			PrimaryTokenHint: sql.NullString{String: tokenHint, Valid: true},
		})
		if errors.Is(err, sql.ErrNoRows) {
			return validation.NewGenericError("key not found, or already has primary and secondary tokens")
		}

		// Note: A possible race condition here is if multiple requests are made to set the primary token at the same time. In that case, the first request will win and the others will fail with a unique constraint violation. This is acceptable because the primary token is only set once, and only rotated thereafter.
	}
	if err != nil {
		return err
	}

	return nil
}

func (s *Store) PromoteSecondaryToken(ctx context.Context, db gadb.DBTX, id uuid.UUID) error {
	err := permission.LimitCheckAny(ctx, permission.User)
	if err != nil {
		return err
	}

	hint, err := gadb.New(db).IntKeyPromoteSecondary(ctx, id)
	if err != nil {
		return err
	}

	if !hint.Valid {
		return validation.NewGenericError("no secondary token to promote")
	}

	return nil
}

func (s *Store) DeleteSecondaryToken(ctx context.Context, db gadb.DBTX, id uuid.UUID) error {
	err := permission.LimitCheckAny(ctx, permission.User)
	if err != nil {
		return err
	}

	err = gadb.New(db).IntKeyDeleteSecondaryToken(ctx, id)
	if err != nil {
		return err
	}

	return nil
}