-
Notifications
You must be signed in to change notification settings - Fork 364
/
WebAppUserParser.java
578 lines (548 loc) · 16.3 KB
/
WebAppUserParser.java
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/********************************************************************************
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
********************************************************************************/
package org.eclipse.californium.cloud.s3.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.security.auth.DestroyFailedException;
import org.eclipse.californium.cloud.util.ResourceParser;
import org.eclipse.californium.elements.util.StandardCharsets;
import org.eclipse.californium.elements.util.StringUtil;
import org.eclipse.californium.scandium.util.SecretUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Web application user parser.
*
* Format:
*
* <pre>
* {@code # <comment>}
*
* {@code <user-name>[.pw]=<password>}
* {@code [[<user-name>].s3=<s3AccessKeyId>,<s3AccessKeySecret>]}
* {@code [[<user-name>].config=<config>]}
* {@code [[<user-name>].groups=<group1>,<group2>,..]}
*
* {@code [*.s3=<s3AccessKeyId>,<s3AccessKeySecret>]}
* </pre>
*
* The {@code password}, the {@code s3AccessKeyId}, and the
* {@code s3AccessKeySecret} may be provided in base 64 or included as plain
* text in single- ({@code '}) or double-quotes ({@code "}). {@code config} may
* be provided plain or included in single- ({@code '}) or double-quotes
* ({@code "}). The {@code groups} is a {@code ','} separated list of group
* names, each either in plain or included in single- ({@code '}) or
* double-quotes ({@code "}). An entry with {@code *.s3} is used to setup the
* default S3 credentials for user definitions without explicit {@code .s3}
* definition.
*
* Example:
*
* <pre>
* {@code # default S3 credentials}
* {@code *.s3='<S3-access-key-id-default>','<S3-access-key-secret-default>'}
*
* {@code # User with default S3 credentials}
* {@code User1='secret'}
* {@code .config=user}
*
* {@code # User, base 64 password and S3 credentials}
* {@code User2=bW9yZSBzZWNyZXQ=}
* {@code .config=admin}
* {@code .s3='<S3-access-key-id-user2>','<S3-access-key-secret-user2>'}
* {@code .groups=Demo,Environment-Sensor}
*
* </pre>
*
* @since 3.12
*/
public class WebAppUserParser implements ResourceParser<WebAppUserParser> {
private static final Logger LOGGER = LoggerFactory.getLogger(WebAppUserParser.class);
/**
* Postfix in header for password.
*/
public static final String PW_POSTFIX = ".pw";
/**
* Postfix in header for S3 credentials.
*/
public static final String S3_POSTFIX = ".s3";
/**
* Postfix in header for groups.
*/
public static final String GROUPS_POSTFIX = ".groups";
/**
* Postfix in header for "Single Page Application" configuration store.
*/
public static final String CONFIG_POSTFIX = ".config";
/**
* Map of user names and credentials.
*/
private final Map<String, WebAppUser> map = new ConcurrentHashMap<>();
/**
* Default S3 credentials.
*/
private WebAppUser s3Default;
/**
* {@code true} to use case sensitive names, {@code false}, otherwise.
*/
private final boolean caseSensitiveNames;
/**
* {@code true} if credentials are destroyed.
*/
private volatile boolean destroyed;
/**
* Create credentials map.
*
* @param caseSensitiveNames {@code true} to use case sensitive names,
* {@code false}, otherwise.
*/
public WebAppUserParser(boolean caseSensitiveNames) {
this.caseSensitiveNames = caseSensitiveNames;
}
/**
* Get key from name.
*
* @param name name of entry
* @return key from name
* @see #caseSensitiveNames
*/
private String getKey(String name) {
String key = name == null ? "" : name;
if (!caseSensitiveNames && key != null) {
key = key.toLowerCase();
}
return key;
}
/**
* Match names considering {@link #caseSensitiveNames}.
*
* @param name1 first name to match
* @param name2 second name to match
* @return {@code true}, if names are matching, {@code false}, otherwise.
*/
private boolean match(String name1, String name2) {
if (caseSensitiveNames) {
return name1.equals(name2);
} else {
return name1.equalsIgnoreCase(name2);
}
}
/**
* Get prefix from id.
*
* @param id id
* @param postfix postfix to be removed from id
* @return either the unchanged id, or the id with the postfix tail removed.
* @see StringUtil#truncateTail(boolean, String, String)
*/
private String prefix(String id, String postfix) {
return StringUtil.truncateTail(caseSensitiveNames, id, postfix);
}
/**
* Checks, if id is a name.
*
* The id is a name, if it ends with {@link #PW_POSTFIX}, or if it doesn't
* end with {@link #S3_POSTFIX}, {@link #GROUPS_POSTFIX} nor
* {@link #CONFIG_POSTFIX}.
*
* @param id id to check
* @return {@code true}, if id complies with a name, {@code false},
* otherwise.
*/
private boolean isName(String id) {
String name = prefix(id, PW_POSTFIX);
if (name != id) {
return true;
}
name = prefix(id, S3_POSTFIX);
if (name != id) {
return !map.containsKey(getKey(name));
}
name = prefix(id, GROUPS_POSTFIX);
if (name != id) {
return !map.containsKey(getKey(name));
}
name = prefix(id, CONFIG_POSTFIX);
if (name != id) {
return !map.containsKey(getKey(name));
}
return true;
}
/**
* Match the web application user builder with the provided name
*
* A web application user builder without a name doesn't match at all. A
* empty name matches any non empty builder name. Or the name must match the
* builder's name according {@link #match(String, String)}.
*
* @param builder web application user builder
* @param name name
* @return {@code true}, if the builder and name matches, {@code false},
* otherwise.
*/
private boolean match(WebAppUser.Builder builder, String name) {
if (builder.name == null) {
return false;
}
if (name.isEmpty()) {
return !builder.name.isEmpty();
} else {
return match(builder.name, name);
}
}
/**
* Add web application user.
*
* If no S3 credentials are provided, the default S3 credentials are used,
* if available.
*
* @param builder web application user builder
* @return {@code true}, if web application user have been added,
* {@code false}, if web application user have been updated
*/
public boolean add(WebAppUser.Builder builder) {
if (s3Default != null) {
if (builder.accessKeyId == null && builder.accessKeySecret == null) {
builder.accessKeyId = s3Default.accessKeyId;
builder.accessKeySecret = s3Default.accessKeySecret;
}
}
WebAppUser credentials = builder.build();
return map.put(getKey(credentials.name), credentials) == null;
}
/**
* Add credentials.
*
* @param credentials user credentials
* @return {@code true}, if user credentials have been added, {@code false},
* if user credentials have been updated
*/
public boolean add(WebAppUser credentials) {
if (s3Default != null) {
if (credentials.accessKeyId == null && credentials.accessKeySecret == null) {
WebAppUser.Builder builder = WebAppUser.builder();
builder.name = credentials.name;
builder.password = credentials.password;
builder.accessKeyId = s3Default.accessKeyId;
builder.accessKeySecret = s3Default.accessKeySecret;
builder.webAppConfig = credentials.webAppConfig;
builder.groups = credentials.groups;
credentials = builder.build();
}
}
return map.put(getKey(credentials.name), credentials) == null;
}
/**
* Get web application user.
*
* @param name name of web application user
* @return web application user, {@code null}, if not available.
*/
public WebAppUser get(String name) {
return map.get(getKey(name));
}
/**
* Remove web application user.
*
* @param name name of web application user
* @return {@code true}, if web application user have been removed,
* {@code false} otherwise.
*/
public boolean remove(String name) {
return map.remove(getKey(name)) != null;
}
/**
* Number of entries.
*
* @return number of entries
*/
public int size() {
return map.size();
}
@Override
public void save(Writer writer) throws IOException {
if (s3Default != null) {
writer.write(S3_POSTFIX + "=");
writer.write(encode64(s3Default.accessKeyId));
writer.write(',');
writer.write(encode64(s3Default.accessKeySecret));
writer.write(StringUtil.lineSeparator());
}
List<String> names = new ArrayList<>(map.keySet());
names.sort(null);
for (String name : names) {
WebAppUser credentials = map.get(name);
if (credentials != null) {
writer.write(credentials.name);
writer.write('=');
writer.write(encode64(credentials.password));
writer.write(StringUtil.lineSeparator());
if (credentials.webAppConfig != null) {
writer.write(credentials.name + CONFIG_POSTFIX);
writer.write('=');
writer.write(credentials.webAppConfig);
writer.write(StringUtil.lineSeparator());
}
if (s3Default == null || !s3Default.accessKeyId.equals(credentials.accessKeyId)) {
writer.write(credentials.name + S3_POSTFIX);
writer.write('=');
writer.write(encode64(credentials.accessKeyId));
writer.write(',');
writer.write(encode64(credentials.accessKeySecret));
writer.write(StringUtil.lineSeparator());
}
if (credentials.groups != null && !credentials.groups.isEmpty()) {
writer.write(credentials.name + GROUPS_POSTFIX);
boolean first = true;
for (String group : credentials.groups) {
if (first) {
writer.write('=');
first = false;
} else {
writer.write(',');
}
writer.write(group);
}
}
}
}
}
@Override
public void load(Reader reader) throws IOException {
BufferedReader lineReader = new BufferedReader(reader);
try {
int lineNumber = 0;
int errors = 0;
int comments = 0;
WebAppUser.Builder builder = WebAppUser.builder();
String line;
// readLine() reads the secret into a String,
// what may be considered to be a weak practice.
while ((line = lineReader.readLine()) != null) {
++lineNumber;
try {
if (!line.isEmpty() && !line.startsWith("#")) {
String[] entry = line.split("=", 2);
if (entry.length == 2) {
String name = entry[0];
String[] values = entry[1].split(",");
if (name.equals("*" + S3_POSTFIX)) {
WebAppUser.Builder def = WebAppUser.builder();
def.name = "*";
if (parseS3(def, "*", values)) {
s3Default = def.build();
} else {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line);
}
continue;
}
String prefix = prefix(name, CONFIG_POSTFIX);
if (prefix != name) {
if (values.length != 1 || !match(builder, prefix)) {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line);
} else {
builder.webAppConfig = decodeText(values[0]);
}
continue;
}
prefix = prefix(name, S3_POSTFIX);
if (prefix != name) {
if (!parseS3(builder, prefix, values)) {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line);
}
continue;
}
prefix = prefix(name, GROUPS_POSTFIX);
if (prefix != name) {
if (!parseGroups(builder, prefix, values)) {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line);
}
continue;
}
prefix = prefix(name, PW_POSTFIX);
if (prefix != name || isName(name)) {
if (builder.name != null) {
add(builder);
builder = WebAppUser.builder();
}
if (values.length != 1) {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line);
} else {
if (prefix == null) {
builder.name = name;
} else {
builder.name = prefix;
}
builder.password = decodeTextOr64(values[0]);
}
}
} else {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line);
}
} else {
++comments;
}
} catch (IllegalArgumentException ex) {
++errors;
LOGGER.warn("{}: '{}' invalid line!", lineNumber, line, ex);
}
}
if (builder.name != null) {
add(builder);
}
if (size() == 0 && errors > 0 && lineNumber == comments + errors) {
LOGGER.warn("read store, only errors, wrong password?");
SecretUtil.destroy(this);
}
} catch (RuntimeException e) {
LOGGER.warn("read store, unexpected error occurred!", e);
} catch (IOException e) {
if (e.getCause() instanceof GeneralSecurityException) {
LOGGER.warn("read store, wrong password?", e);
SecretUtil.destroy(this);
} else {
throw e;
}
} finally {
try {
lineReader.close();
} catch (IOException e) {
}
}
LOGGER.info("read {} user credentials.", size());
}
/**
* Parse S3 credentials.
*
* The values must contain the S3 access key id in the first and the S3
* access key secret in the second value.
*
* @param builder builder with web application user data
* @param name name part of line
* @param values split values of line
* @return {@code true} if the S3 credentials are valid, {@code false},
* otherwise.
*/
private boolean parseS3(WebAppUser.Builder builder, String name, String[] values) {
if (values.length != 2 || !match(builder, name)) {
return false;
}
builder.accessKeyId = decodeTextOr64(values[0]);
builder.accessKeySecret = decodeTextOr64(values[1]);
return !builder.accessKeyId.isEmpty() && !builder.accessKeySecret.isEmpty();
}
/**
* Parse groups.
*
* @param builder builder with web application user data
* @param name name part of line
* @param values split values of line
* @return {@code true} if the groups are valid, {@code false}, otherwise.
*/
private boolean parseGroups(WebAppUser.Builder builder, String name, String[] values) {
if (!match(builder, name)) {
return false;
}
for (int index = 0; index < values.length; ++index) {
values[index] = decodeText(values[index]);
}
builder.groups = Arrays.asList(values);
return true;
}
@Override
public void destroy() throws DestroyFailedException {
map.clear();
destroyed = true;
}
@Override
public boolean isDestroyed() {
return destroyed;
}
/**
* Encode UTF-8 text in base 64.
*
* @param value UTF-8 text
* @return base 64
*/
private static String encode64(String value) {
byte[] data = value.getBytes(StandardCharsets.UTF_8);
return StringUtil.byteArrayToBase64(data);
}
/**
* Decode value to text.
*
* A plain text value must be in single- ({@code '}) or double-quotes
* ({@code "}). Other values are considered to be base 64 encoded.
*
* @param value value to be decoded
* @return text
*/
private static String decodeTextOr64(String value) {
if (value.isEmpty()) {
return value;
}
char c = value.charAt(0);
if (value.length() > 2 && (c == '\'' || c == '"')) {
int end = value.length() - 1;
char e = value.charAt(end);
if (e == c) {
value = value.substring(1, end);
return value;
}
}
byte[] data = StringUtil.base64ToByteArray(value);
return new String(data, StandardCharsets.UTF_8);
}
/**
* Decode text value.
*
* If the value is in single- ({@code '}) or double-quotes ({@code "}),
* these are removed.
*
* @param value value to be decoded
* @return text value
*/
private static String decodeText(String value) {
if (!value.isEmpty()) {
char c = value.charAt(0);
if (value.length() > 2 && (c == '\'' || c == '"')) {
int end = value.length() - 1;
char e = value.charAt(end);
if (e == c) {
value = value.substring(1, end);
}
}
}
return value;
}
@Override
public WebAppUserParser create() {
return new WebAppUserParser(caseSensitiveNames);
}
}