/
RestApiAccounts.scala
317 lines (287 loc) · 11.8 KB
/
RestApiAccounts.scala
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
package com.normation.rudder.rest
import com.normation.eventlog.ModificationId
import com.normation.rudder.api.*
import com.normation.rudder.api.ApiAuthorization as ApiAuthz
import com.normation.rudder.api.RoApiAccountRepository
import com.normation.rudder.api.WoApiAccountRepository
import com.normation.rudder.apidata.ApiAccountSerialisation.*
import com.normation.rudder.facts.nodes.NodeSecurityContext
import com.normation.rudder.rest.RestUtils.*
import com.normation.rudder.tenants.TenantService
import com.normation.rudder.users.UserService
import com.normation.utils.StringUuidGenerator
import com.normation.zio.*
import net.liftweb.common.*
import net.liftweb.common.Loggable
import net.liftweb.http.LiftResponse
import net.liftweb.http.rest.RestHelper
import net.liftweb.json.JArray
import net.liftweb.json.JsonDSL.*
import org.joda.time.DateTime
class RestApiAccounts(
readApi: RoApiAccountRepository,
writeApi: WoApiAccountRepository,
restExtractor: RestExtractorService,
tokenGenerator: TokenGenerator,
uuidGen: StringUuidGenerator,
userService: UserService,
apiAuthService: ApiAuthorizationLevelService,
tenantsService: TenantService
) extends RestHelper with Loggable {
// used in ApiAccounts snippet to get the context path
// of that service
val relativePath: List[String] = "secure" :: "apiaccounts" :: Nil
serve {
case Get("secure" :: "apiaccounts" :: Nil, req) =>
implicit val prettify = restExtractor
.extractBoolean("prettify")(req)(identity)
.getOrElse(Some(false))
.getOrElse(
false
)
implicit val action: String = "getAllAccounts"
// here, 'write' and not 'read' because some tokens may have admin write access,
// and we want to avoid escalation
OldInternalApiAuthz.withWriteAdmin(readApi.getAllStandardAccounts.either.runNow match {
case Right(accountSeq) =>
val filtered = accountSeq.toList
.map((a) => {
// Don't send hashes
a.copy(token = if (a.token.isHashed) {
ApiToken("")
} else {
a.token
})
})
val accounts = {
(
("aclPluginEnabled" -> apiAuthService.aclEnabled) ~
("tenantsPluginEnabled" -> tenantsService.tenantsEnabled) ~
("accounts" -> JArray(
filtered.map(_.toJson)
))
)
}
toJsonResponse(None, accounts)
case Left(err) =>
val msg = s"Could not get accounts cause : ${err.fullMsg}"
logger.error(msg)
toJsonError(None, msg)
})
case "secure" :: "apiaccounts" :: Nil JsonPut body -> req =>
implicit val prettify = restExtractor
.extractBoolean("prettify")(req)(identity)
.getOrElse(Some(false))
.getOrElse(
false
)
implicit val action: String = "updateAccount"
OldInternalApiAuthz.withWriteAdmin(req.json match {
case Full(json) =>
restExtractor.extractApiAccountFromJSON(json) match {
case Full(restApiAccount) =>
if (restApiAccount.name.isDefined) {
// generate the id for creation
val id = ApiAccountId(uuidGen.newUuid)
val now = DateTime.now
// by default, token expires after one month
val expiration = restApiAccount.expiration.getOrElse(Some(now.plusMonths(1)))
val acl = restApiAccount.authz.getOrElse(ApiAuthz.None)
val secret = ApiToken.generate_secret(tokenGenerator)
val hash = ApiToken.hash(secret)
val account = ApiAccount(
id,
ApiAccountKind.PublicApi(acl, expiration),
restApiAccount.name.get,
ApiToken(hash),
restApiAccount.description.getOrElse(""),
restApiAccount.enabled.getOrElse(true),
now,
now,
restApiAccount.tenants.getOrElse(NodeSecurityContext.All)
)
writeApi.save(account, ModificationId(uuidGen.newUuid), userService.getCurrentUser.actor).either.runNow match {
case Right(_) =>
val accounts = ("accounts" -> JArray(
List(
account
.copy(
// Send clear text secret
token = ApiToken(secret)
)
.toJson
)
))
toJsonResponse(None, accounts)
case Left(err) =>
val msg = s"Could not create account cause: ${err.fullMsg}"
logger.error(msg)
toJsonError(None, msg)
}
} else {
val msg = s"Could not create account cause: could not get account"
logger.error(msg)
toJsonError(None, msg)
}
case eb: EmptyBox =>
val msg = s"Could not create account cause: ${(eb ?~ "could not extract data from JSON").msg}"
logger.error(msg)
toJsonError(None, msg)
}
case eb: EmptyBox =>
logger.error("No Json data sent")
toJsonError(None, "No Json data sent")
})
case "secure" :: "apiaccounts" :: tokenId :: Nil JsonPost body -> req =>
val apiTokenId = ApiAccountId(tokenId)
implicit val prettify = restExtractor
.extractBoolean("prettify")(req)(identity)
.getOrElse(Some(false))
.getOrElse(
false
)
implicit val action: String = "updateAccount"
OldInternalApiAuthz.withWriteAdmin(req.json match {
case Full(json) =>
restExtractor.extractApiAccountFromJSON(json) match {
case Full(restApiAccount) =>
readApi.getById(apiTokenId).either.runNow match {
case Right(Some(account)) =>
val updateAccount = restApiAccount.update(account)
save(updateAccount)
case Right(None) =>
val msg = s"Could not update account ${tokenId} cause: could not get account"
logger.error(msg)
toJsonError(None, msg)
case Left(err) =>
val msg = s"Could not update account ${tokenId} cause: ${err.fullMsg}"
logger.error(msg)
toJsonError(None, msg)
}
case eb: EmptyBox =>
val msg = s"Could not update account ${tokenId} cause: ${(eb ?~ "could not extract data from JSON").msg}"
logger.error(msg)
toJsonError(None, msg)
}
case eb: EmptyBox =>
toJsonError(None, "No Json data sent")
})
case Delete("secure" :: "apiaccounts" :: tokenId :: Nil, req) =>
val apiTokenId = ApiAccountId(tokenId)
implicit val prettify = restExtractor
.extractBoolean("prettify")(req)(identity)
.getOrElse(Some(false))
.getOrElse(
false
)
implicit val action: String = "deleteAccount"
OldInternalApiAuthz.withWriteAdmin(readApi.getById(apiTokenId).either.runNow match {
case Right(Some(account)) =>
writeApi.delete(account.id, ModificationId(uuidGen.newUuid), userService.getCurrentUser.actor).either.runNow match {
case Right(_) =>
val filtered = account.copy(token = if (account.token.isHashed) {
ApiToken("")
} else {
account.token
})
val accounts = ("accounts" -> JArray(List(filtered.toJson)))
toJsonResponse(None, accounts)
case Left(err) =>
toJsonError(None, s"Could not delete account ${tokenId} cause: ${err.fullMsg}")
}
case Right(None) =>
toJsonError(None, s"Could not delete account ${tokenId} cause: could not get account")
case Left(err) =>
toJsonError(None, s"Could not delete account ${tokenId} cause: ${err.fullMsg}")
})
case Post("secure" :: "apiaccounts" :: tokenId :: "regenerate" :: Nil, req) =>
val apiTokenId = ApiAccountId(tokenId)
implicit val prettify = restExtractor
.extractBoolean("prettify")(req)(identity)
.getOrElse(Some(false))
.getOrElse(
false
)
implicit val action: String = "regenerateAccount"
OldInternalApiAuthz.withWriteAdmin(readApi.getById(apiTokenId).either.runNow match {
case Right(Some(account)) =>
val newSecret = ApiToken.generate_secret(tokenGenerator)
val newHash = ApiToken.hash(newSecret)
val generationDate = DateTime.now
writeApi
.save(
account.copy(token = ApiToken(newHash), tokenGenerationDate = generationDate),
ModificationId(uuidGen.newUuid),
userService.getCurrentUser.actor
)
.either
.runNow match {
case Right(account) =>
val accounts = ("accounts" -> JArray(
List(
account
.copy(
// Send clear text secret
token = ApiToken(newSecret)
)
.toJson
)
))
toJsonResponse(None, accounts)
case Left(err) =>
val msg = s"Could not regenerate account ${tokenId} cause: ${err.fullMsg}"
logger.error(msg)
toJsonError(None, s"Could not regenerate account ${tokenId} cause: ${err.fullMsg}")(
"regenerateAccount",
true
)
}
case Right(None) =>
val msg = s"Could not regenerate account ${tokenId} cause could not get account"
logger.error(msg)
toJsonError(None, msg)
case Left(err) =>
val msg = s"Could not regenerate account ${tokenId} cause: ${err.fullMsg}"
logger.error(msg)
toJsonError(None, msg)
})
}
def save(account: ApiAccount)(implicit action: String, prettify: Boolean): LiftResponse = {
writeApi.save(account, ModificationId(uuidGen.newUuid), userService.getCurrentUser.actor).either.runNow match {
case Right(res) =>
val filtered = res.copy(token = if (res.token.isHashed) {
ApiToken("")
} else {
res.token
})
val accounts = ("accounts" -> JArray(List(filtered.toJson)))
toJsonResponse(None, accounts)
case Left(err) =>
toJsonError(None, s"Could not update account '${account.name.value}' cause : ${err.fullMsg}")
}
}
}
final case class RestApiAccount(
id: Option[ApiAccountId],
name: Option[ApiAccountName],
description: Option[String],
enabled: Option[Boolean],
oldId: Option[ApiAccountId],
expiration: Option[Option[DateTime]],
authz: Option[ApiAuthz],
tenants: Option[NodeSecurityContext]
) {
// Id cannot change if already defined
def update(account: ApiAccount): ApiAccount = {
val nameUpdate = name.getOrElse(account.name)
val enableUpdate = enabled.getOrElse(account.isEnabled)
val descUpdate = description.getOrElse(account.description)
val tenantsUpdate = tenants.getOrElse(account.tenants)
val kind = account.kind match {
case ApiAccountKind.PublicApi(a, e) =>
ApiAccountKind.PublicApi(authz.getOrElse(a), expiration.getOrElse(e))
case x => x
}
account.copy(name = nameUpdate, isEnabled = enableUpdate, description = descUpdate, kind = kind, tenants = tenantsUpdate)
}
}