This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
scopes.go
253 lines (221 loc) · 7.29 KB
/
scopes.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
// Copyright 2020 the Exposure Notifications Verification Server authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"fmt"
"strings"
"github.com/google/exposure-notifications-verification-server/internal/project"
"github.com/google/exposure-notifications-verification-server/pkg/rbac"
"github.com/jinzhu/gorm"
)
// Scope is a type alias to a gorm scope. It exists to reduce duplicate and
// function length. Note this is an ALIAS. It is NOT a new type.
type Scope = func(db *gorm.DB) *gorm.DB
// Unscoped returns an unscoped database (for finding soft-deleted records and
// clearing other scopes).
func Unscoped() Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Unscoped()
}
}
// OnlySystemAdmins returns a scope that restricts the query to system admins.
// It's only applicable to functions that query User.
func OnlySystemAdmins() Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where(&User{SystemAdmin: true})
}
}
// InConsumableSecretOrder is a scope that orders secrets in the order in which
// they should be consumed.
func InConsumableSecretOrder() Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Order("secrets.active DESC, secrets.created_at DESC")
}
}
// WithUserSearch returns a scope that adds querying for users by email and
// name, case-insensitive. It's only applicable to functions that query User.
func WithUserSearch(q string) Scope {
return func(db *gorm.DB) *gorm.DB {
search, err := parseUserSearch(q)
if err != nil {
_ = db.AddError(fmt.Errorf("%w: %s", ErrValidationFailed, err))
return db
}
if search.name != "" {
db = db.Where("users.name ~* ?", fmt.Sprintf("(%s)", search.name))
}
if search.email != "" {
db = db.Where("users.email ~* ?", fmt.Sprintf("(%s)", search.email))
}
// For backwards-compatibility with previous versions of search, other could
// have been a name or email.
if search.other != nil {
s := strings.Join(search.other, "|")
db = db.Where("users.name ~* ? OR users.email ~* ?", fmt.Sprintf("(%s)", s), fmt.Sprintf("(%s)", s))
}
if p := search.withPerms; p != 0 {
db = WithPermissionSearch(p)(db)
}
if p := search.withoutPerms; p != 0 {
db = WithoutPermissionSearch(p)(db)
}
return db
}
}
type userSearchQuery struct {
name string
email string
other []string
withPerms rbac.Permission
withoutPerms rbac.Permission
}
func parseUserSearch(q string) (*userSearchQuery, error) {
var resp userSearchQuery
parts := strings.Split(project.TrimSpace(q), " ")
for _, part := range parts {
part = project.TrimSpace(part)
if part == "" {
continue
}
switch {
case strings.HasPrefix(part, "name:"):
if resp.name != "" {
return nil, fmt.Errorf(`cannot specify "name:" more than once`)
}
resp.name = project.TrimSpace(part[5:])
case strings.HasPrefix(part, "email:"):
if resp.email != "" {
return nil, fmt.Errorf(`cannot specify "email:" more than once`)
}
resp.email = project.TrimSpace(part[6:])
case strings.HasPrefix(part, "can:"):
name := project.TrimSpace(part[4:])
p, ok := rbac.NamePermissionMap[name]
if !ok {
return nil, fmt.Errorf("unknown permission %q", name)
}
resp.withPerms |= p
case strings.HasPrefix(part, "cannot:"):
name := project.TrimSpace(part[7:])
p, ok := rbac.NamePermissionMap[name]
if !ok {
return nil, fmt.Errorf("unknown permission %q", name)
}
resp.withoutPerms |= p
default:
// These are "naked" fields in the query
resp.other = append(resp.other, part)
}
}
return &resp, nil
}
// WithPermissionSearch searches for memberships which have the given
// permission.
func WithPermissionSearch(p rbac.Permission) Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where(fmt.Sprintf("memberships.permissions::bit(64) & %d::bit(64) != 0::bit(64)", p))
}
}
// WithoutPermissionSearch searches for memberships which do not have the given
// permission.
func WithoutPermissionSearch(p rbac.Permission) Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where(fmt.Sprintf("memberships.permissions::bit(64) & %d::bit(64) = 0::bit(64)", p))
}
}
// WithAuditTime returns a scope that adds querying for Audit events by time.
func WithAuditTime(from, to string) Scope {
return func(db *gorm.DB) *gorm.DB {
from = project.TrimSpace(from)
if from != "" {
db = db.Where("audit_entries.created_at >= ?", from)
}
to = project.TrimSpace(to)
if to != "" {
db = db.Where("audit_entries.created_at <= ?", to)
}
return db
}
}
// WithAuditRealmID returns a scope that adds querying for Audit events by
// realm. The provided ID is expected to be stringable (int, uint, string).
func WithAuditRealmID(id uint) Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where("audit_entries.realm_id = ?", id)
}
}
// WithRealmSearch returns a scope that adds querying for realms by name. It's
// only applicable to functions that query Realm.
func WithRealmSearch(q string) Scope {
return func(db *gorm.DB) *gorm.DB {
q = project.TrimSpace(q)
if q != "" {
q = `%` + q + `%`
return db.Where("realms.name ILIKE ?", q)
}
return db
}
}
// WithRealmAutoKeyRotationEnabled filters by realms which have the auto key
// rotation enabled/disabled depending on the boolean.
func WithRealmAutoKeyRotationEnabled(b bool) Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where("auto_rotate_certificate_key = ?", b)
}
}
// WithoutAuditTest excludes audit entries related to test entries created from
// SystemTest.
func WithoutAuditTest() Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where("audit_entries.actor_id != ?", SystemTest.AuditID())
}
}
// WithAppOS returns a scope that for querying MobileApps by Operating System type.
func WithAppOS(os OSType) Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where("os = ?", os)
}
}
// WithAuthorizedAppType returns a scope that filters by the given type.
func WithAuthorizedAppType(typ APIKeyType) Scope {
return func(db *gorm.DB) *gorm.DB {
return db.Where("api_key_type = ?", typ)
}
}
// WithAuthorizedAppSearch returns a scope that adds querying for API keys by
// name and preview, case-insensitive. It's only applicable to functions that
// query AuthorizedApp.
func WithAuthorizedAppSearch(q string) Scope {
return func(db *gorm.DB) *gorm.DB {
q = project.TrimSpace(q)
if q != "" {
q = `%` + q + `%`
return db.Where("authorized_apps.name ILIKE ? OR authorized_apps.api_key_preview ILIKE ?", q, q)
}
return db
}
}
// WithMobileAppSearch returns a scope that adds querying for mobile apps by
// name, case-insensitive. It's only applicable to functions that query
// MobileApp.
func WithMobileAppSearch(q string) Scope {
return func(db *gorm.DB) *gorm.DB {
q = project.TrimSpace(q)
if q != "" {
q = `%` + q + `%`
return db.Where("mobile_apps.name ILIKE ? OR realms.name ILIKE ?", q, q)
}
return db
}
}