~sircmpwn/meta.sr.ht

ref: 0.56.17 meta.sr.ht/api/webhooks/legacy.go -rw-r--r-- 7.0 KiB
b1deacf0Nicolas Schodet Fix field name when validating the PGP key in RegisterAccount 9 months ago
                                                                                
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
package webhooks

import (
	"context"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"errors"
	"net/http"
	"strings"
	"time"

	"git.sr.ht/~sircmpwn/core-go/auth"
	"git.sr.ht/~sircmpwn/core-go/database"
	"git.sr.ht/~sircmpwn/core-go/webhooks"
	sq "github.com/Masterminds/squirrel"

	"git.sr.ht/~sircmpwn/meta.sr.ht/api/graph/model"
)

func NewLegacyQueue() *webhooks.LegacyQueue {
	return webhooks.NewLegacyQueue()
}

var legacyUserCtxKey = &contextKey{"legacyUser"}

type contextKey struct {
	name string
}

func LegacyMiddleware(
	queue *webhooks.LegacyQueue,
) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := context.WithValue(r.Context(), legacyUserCtxKey, queue)
			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)
		})
	}
}

func DeliverLegacyProfileUpdate(ctx context.Context, user *model.User) {
	// This legacy garbage is due to be removed at our earliest convenience.
	q, ok := ctx.Value(legacyUserCtxKey).(*webhooks.LegacyQueue)
	if !ok {
		panic(errors.New("No legacy user webhooks worker for this context"))
	}

	type WebhookPayload struct {
		CanonicalName string  `json:"canonical_name"`
		Name          string  `json:"name"`
		Email         string  `json:"email"`
		URL           *string `json:"url"`
		Location      *string `json:"location"`
		Bio           *string `json:"bio"`
		UsePGPKey     *string `json:"use_pgp_key"`

		UserType         string  `json:"user_type",omitempty`
		SuspensionNotice *string `json:"suspension_notice",omitempty`
	}

	// XXX: Technically we could do the PGP key lookup in a single SQL query if
	// we had a more sophisticated database system (particularly if we had lazy
	// loading queries)
	var fingerprint *[]byte
	if err := database.WithTx(ctx, &sql.TxOptions{
		Isolation: 1,
		ReadOnly: true,
	}, func(tx *sql.Tx) error {
		return sq.
			Select("p.fingerprint").
			From(`"user" u`).
			LeftJoin(`pgpkey p ON p.id = u.pgp_key_id`).
			Where("u.id = ?", user.ID).
			PlaceholderFormat(sq.Dollar).
			RunWith(tx).
			ScanContext(ctx, &fingerprint)
	}); err != nil {
		panic(err)
	}

	var fprint *string
	if fingerprint != nil {
		encoded := strings.ToUpper(hex.EncodeToString(*fingerprint))
		fprint = &encoded
	}

	payload := WebhookPayload{
		CanonicalName:    user.CanonicalName(),
		Name:             user.Username,
		Email:            user.Email,
		URL:              user.URL,
		Location:         user.Location,
		Bio:              user.Bio,
		UsePGPKey:        fprint,
		UserType:         user.UserTypeRaw,
		SuspensionNotice: user.SuspensionNotice,
	}
	encoded, err := json.Marshal(&payload)
	if err != nil {
		panic(err) // Programmer error
	}

	query := sq.
		Select().
		From("user_webhook_subscription sub").
		Where("sub.user_id = ?", user.ID)
	q.Schedule(ctx, query, "user", "profile:update", encoded)
}

func DeliverLegacyPGPKeyAdded(ctx context.Context, key *model.PGPKey) {
	q, ok := ctx.Value(legacyUserCtxKey).(*webhooks.LegacyQueue)
	if !ok {
		panic(errors.New("No legacy user webhooks worker for this context"))
	}

	type WebhookPayload struct {
		ID          int       `json:"id"`
		Key         string    `json:"key"`
		Fingerprint string    `json:"fingerprint"`
		Email       string    `json:"email"`
		Authorized  time.Time `json:"authorized"`

		Owner struct {
			CanonicalName string  `json:"canonical_name"`
			Name          string  `json:"name"`
		}`json:"owner"`
	}

	fingerprint := strings.ToUpper(hex.EncodeToString(key.RawFingerprint))
	payload := WebhookPayload{
		ID:          key.ID,
		Key:         key.Key,
		Fingerprint: fingerprint,
		Authorized:  key.Created,
	}

	// TODO: User groups
	user := auth.ForContext(ctx)
	if user.UserID != key.UserID {
		// At the time of writing, the only consumers of this function are in a
		// context where the authenticated user is the owner of this PGP key. We
		// can skip the database round-trip if we just grab their auth context.
		panic(errors.New("TODO: look up user details for this key"))
	}
	payload.Owner.CanonicalName = "~" + user.Username
	payload.Owner.Name = user.Username

	encoded, err := json.Marshal(&payload)
	if err != nil {
		panic(err) // Programmer error
	}

	query := sq.
		Select().
		From("user_webhook_subscription sub").
		Where("sub.user_id = ?", key.UserID)
	q.Schedule(ctx, query, "user", "pgp-key:add", encoded)
}

func DeliverLegacyPGPKeyRemoved(ctx context.Context, key *model.PGPKey) {
	q, ok := ctx.Value(legacyUserCtxKey).(*webhooks.LegacyQueue)
	if !ok {
		panic(errors.New("No legacy user webhooks worker for this context"))
	}

	type WebhookPayload struct {
		ID int `json:"id"`
	}
	payload := WebhookPayload{key.ID}

	encoded, err := json.Marshal(&payload)
	if err != nil {
		panic(err) // Programmer error
	}

	query := sq.
		Select().
		From("user_webhook_subscription sub").
		Where("sub.user_id = ?", key.UserID)
	q.Schedule(ctx, query, "user", "pgp-key:remove", encoded)
}

func DeliverLegacySSHKeyAdded(ctx context.Context, key *model.SSHKey) {
	q, ok := ctx.Value(legacyUserCtxKey).(*webhooks.LegacyQueue)
	if !ok {
		panic(errors.New("No legacy user webhooks worker for this context"))
	}

	type WebhookPayload struct {
		ID          int        `json:"id"`
		Authorized  time.Time  `json:"authorized"`
		Comment     *string    `json:"comment"`
		Fingerprint string     `json:"fingerprint"`
		Key         string     `json:"key"`
		LastUsed    *time.Time `json:"last_used"`

		Owner struct {
			CanonicalName string  `json:"canonical_name"`
			Name          string  `json:"name"`
		}`json:"owner"`
	}

	payload := WebhookPayload{
		ID:          key.ID,
		Authorized:  key.Created,
		Comment:     key.Comment,
		Fingerprint: key.Fingerprint,
		Key:         key.Key,
	}

	// TODO: User groups
	user := auth.ForContext(ctx)
	if user.UserID != key.UserID {
		// At the time of writing, the only consumers of this function are in a
		// context where the authenticated user is the owner of this PGP key. We
		// can skip the database round-trip if we just grab their auth context.
		panic(errors.New("TODO: look up user details for this key"))
	}
	payload.Owner.CanonicalName = "~" + user.Username
	payload.Owner.Name = user.Username

	// Note: Should only be set if the authorized user is the key owner
	payload.LastUsed = key.LastUsed

	encoded, err := json.Marshal(&payload)
	if err != nil {
		panic(err) // Programmer error
	}

	query := sq.
		Select().
		From("user_webhook_subscription sub").
		Where("sub.user_id = ?", key.UserID)
	q.Schedule(ctx, query, "user", "ssh-key:add", encoded)
}

func DeliverLegacySSHKeyRemoved(ctx context.Context, key *model.SSHKey) {
	q, ok := ctx.Value(legacyUserCtxKey).(*webhooks.LegacyQueue)
	if !ok {
		panic(errors.New("No legacy user webhooks worker for this context"))
	}

	type WebhookPayload struct {
		ID int `json:"id"`
	}
	payload := WebhookPayload{key.ID}

	encoded, err := json.Marshal(&payload)
	if err != nil {
		panic(err) // Programmer error
	}

	query := sq.
		Select().
		From("user_webhook_subscription sub").
		Where("sub.user_id = ?", key.UserID)
	q.Schedule(ctx, query, "user", "ssh-key:remove", encoded)
}