-
Notifications
You must be signed in to change notification settings - Fork 52
/
api_notices.go
285 lines (249 loc) · 8.12 KB
/
api_notices.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
// Copyright (c) 2023-2024 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package daemon
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"regexp"
"strconv"
"github.com/canonical/x-go/strutil"
"github.com/canonical/pebble/internals/overlord/state"
)
// Ensure custom keys are in the form "domain.com/key" (but somewhat more restrictive).
var customKeyRegexp = regexp.MustCompile(
`^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+(/[a-z0-9]+(-[a-z0-9]+)*)+$`)
const (
maxNoticeKeyLength = 256
maxNoticeDataSize = 4 * 1024
)
type addedNotice struct {
ID string `json:"id"`
}
func v1GetNotices(c *Command, r *http.Request, _ *UserState) Response {
query := r.URL.Query()
requestUID, err := uidFromRequest(r)
if err != nil {
return Forbidden("cannot determine UID of request, so cannot retrieve notices")
}
daemonUID := uint32(sysGetuid())
// By default, return notices with the request UID and public notices.
userID := &requestUID
if len(query["user-id"]) > 0 {
if !isAdmin(requestUID, daemonUID) {
return Forbidden(`only admins may use the "user-id" filter`)
}
userID, err = sanitizeUserIDFilter(query["user-id"])
if err != nil {
return BadRequest(`invalid "user-id" filter: %v`, err)
}
}
if len(query["users"]) > 0 {
if !isAdmin(requestUID, daemonUID) {
return Forbidden(`only admins may use the "users" filter`)
}
if len(query["user-id"]) > 0 {
return BadRequest(`cannot use both "users" and "user-id" parameters`)
}
if query.Get("users") != "all" {
return BadRequest(`invalid "users" filter: must be "all"`)
}
// Clear the userID filter so all notices will be returned.
userID = nil
}
types, err := sanitizeTypesFilter(query["types"])
if err != nil {
// Caller did provide a types filter, but they're all invalid notice types.
// Return no notices, rather than the default of all notices.
return SyncResponse([]*state.Notice{})
}
keys := strutil.MultiCommaSeparatedList(query["keys"])
after, err := parseOptionalTime(query.Get("after"))
if err != nil {
return BadRequest(`invalid "after" timestamp: %v`, err)
}
filter := &state.NoticeFilter{
UserID: userID,
Types: types,
Keys: keys,
After: after,
}
timeout, err := parseOptionalDuration(query.Get("timeout"))
if err != nil {
return BadRequest("invalid timeout: %v", err)
}
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
var notices []*state.Notice
if timeout != 0 {
// Wait up to timeout for notices matching given filter to occur
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
// WaitNotices releases the state lock while waiting.
notices, err = st.WaitNotices(ctx, filter)
if errors.Is(err, context.Canceled) {
return BadRequest("request canceled")
}
// DeadlineExceeded will occur if timeout elapses; in that case return
// an empty list of notices, not an error.
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
return InternalError("cannot wait for notices: %s", err)
}
} else {
// No timeout given, fetch currently-available notices
notices = st.Notices(filter)
}
if notices == nil {
notices = []*state.Notice{} // avoid null result
}
return SyncResponse(notices)
}
// Get the UID of the request. If the UID is not known, return an error.
func uidFromRequest(r *http.Request) (uint32, error) {
ucred, err := ucrednetGet(r.RemoteAddr)
if err != nil {
return 0, fmt.Errorf("could not parse request UID")
}
return ucred.Uid, nil
}
// Construct the user IDs filter which will be passed to state.Notices.
// Must only be called if the query user ID argument is set.
func sanitizeUserIDFilter(queryUserID []string) (*uint32, error) {
userIDStrs := strutil.MultiCommaSeparatedList(queryUserID)
if len(userIDStrs) != 1 {
return nil, fmt.Errorf(`must only include one "user-id"`)
}
userIDInt, err := strconv.ParseInt(userIDStrs[0], 10, 64)
if err != nil {
return nil, err
}
if userIDInt < 0 || userIDInt > math.MaxUint32 {
return nil, fmt.Errorf("user ID is not a valid uint32: %d", userIDInt)
}
userID := uint32(userIDInt)
return &userID, nil
}
// Construct the types filter which will be passed to state.Notices.
func sanitizeTypesFilter(queryTypes []string) ([]state.NoticeType, error) {
typeStrs := strutil.MultiCommaSeparatedList(queryTypes)
alreadySeen := make(map[state.NoticeType]bool, len(typeStrs))
types := make([]state.NoticeType, 0, len(typeStrs))
for _, typeStr := range typeStrs {
noticeType := state.NoticeType(typeStr)
if !noticeType.Valid() {
// Ignore invalid notice types (so requests from newer clients
// with unknown types succeed).
continue
}
if alreadySeen[noticeType] {
continue
}
alreadySeen[noticeType] = true
types = append(types, noticeType)
}
if len(types) == 0 && len(typeStrs) > 0 {
return nil, errors.New("all requested notice types invalid")
}
return types, nil
}
func isAdmin(requestUID, daemonUID uint32) bool {
return requestUID == 0 || requestUID == daemonUID
}
func v1PostNotices(c *Command, r *http.Request, _ *UserState) Response {
requestUID, err := uidFromRequest(r)
if err != nil {
return Forbidden("cannot determine UID of request, so cannot create notice")
}
var payload struct {
Action string `json:"action"`
Type string `json:"type"`
Key string `json:"key"`
RepeatAfter string `json:"repeat-after"`
DataJSON json.RawMessage `json:"data"`
}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&payload); err != nil {
return BadRequest("cannot decode request body: %v", err)
}
if payload.Action != "add" {
return BadRequest("invalid action %q", payload.Action)
}
if payload.Type != "custom" {
return BadRequest(`invalid type %q (can only add "custom" notices)`, payload.Type)
}
if !customKeyRegexp.MatchString(payload.Key) {
return BadRequest(`invalid key %q (must be in "domain.com/key" format)`, payload.Key)
}
if len(payload.Key) > maxNoticeKeyLength {
return BadRequest("key must be %d bytes or less", maxNoticeKeyLength)
}
repeatAfter, err := parseOptionalDuration(payload.RepeatAfter)
if err != nil {
return BadRequest("invalid repeat-after: %v", err)
}
if len(payload.DataJSON) > maxNoticeDataSize {
return BadRequest("total size of data must be %d bytes or less", maxNoticeDataSize)
}
var data map[string]string
if len(payload.DataJSON) > 0 {
err = json.Unmarshal(payload.DataJSON, &data)
if err != nil {
return BadRequest("cannot decode notice data: %v", err)
}
}
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
noticeId, err := st.AddNotice(&requestUID, state.CustomNotice, payload.Key, &state.AddNoticeOptions{
Data: data,
RepeatAfter: repeatAfter,
})
if err != nil {
return InternalError("%v", err)
}
return SyncResponse(addedNotice{ID: noticeId})
}
func v1GetNotice(c *Command, r *http.Request, _ *UserState) Response {
requestUID, err := uidFromRequest(r)
if err != nil {
return Forbidden("cannot determine UID of request, so cannot retrieve notice")
}
daemonUID := uint32(sysGetuid())
noticeID := muxVars(r)["id"]
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
notice := st.Notice(noticeID)
if notice == nil {
return NotFound("cannot find notice with ID %q", noticeID)
}
if !noticeViewableByUser(notice, requestUID, daemonUID) {
return Forbidden("not allowed to access notice with id %q", noticeID)
}
return SyncResponse(notice)
}
func noticeViewableByUser(notice *state.Notice, requestUID, daemonUID uint32) bool {
userID, isSet := notice.UserID()
if !isSet {
return true
}
if isAdmin(requestUID, daemonUID) {
return true
}
return requestUID == userID
}