Files
SCM-Manager/scm-webapp/src/main/java/sonia/scm/security/ApiKeyService.java

189 lines
6.5 KiB
Java
Raw Normal View History

2020-09-28 18:11:07 +02:00
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.security;
import com.google.common.util.concurrent.Striped;
import lombok.AllArgsConstructor;
import lombok.Getter;
2020-09-28 18:11:07 +02:00
import org.apache.shiro.authc.credential.PasswordService;
2020-09-29 13:54:21 +02:00
import org.apache.shiro.authz.AuthorizationException;
2020-09-28 18:11:07 +02:00
import org.apache.shiro.util.ThreadContext;
import sonia.scm.ContextEntry;
import sonia.scm.store.DataStore;
import sonia.scm.store.DataStoreFactory;
2020-09-28 18:11:07 +02:00
import javax.inject.Inject;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.function.Supplier;
import java.util.stream.Stream;
2020-09-28 18:11:07 +02:00
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.RandomStringUtils.random;
import static sonia.scm.AlreadyExistsException.alreadyExists;
2020-09-29 11:08:36 +02:00
public class ApiKeyService {
2020-09-28 18:11:07 +02:00
public static final int KEY_LENGTH = 20;
private final DataStore<ApiKeyCollection> store;
2020-09-28 18:11:07 +02:00
private final PasswordService passwordService;
2020-09-29 11:08:36 +02:00
private final KeyGenerator keyGenerator;
private final Supplier<String> passphraseGenerator;
2020-09-29 13:54:21 +02:00
private final ApiKeyTokenHandler tokenHandler;
2020-09-28 18:11:07 +02:00
private final Striped<ReadWriteLock> locks = Striped.readWriteLock(10);
@Inject
ApiKeyService(DataStoreFactory storeFactory, KeyGenerator keyGenerator, PasswordService passwordService, ApiKeyTokenHandler tokenHandler) {
2020-09-29 13:54:21 +02:00
this(storeFactory, passwordService, keyGenerator, tokenHandler, () -> random(KEY_LENGTH, 0, 0, true, true, null, new SecureRandom()));
2020-09-28 18:11:07 +02:00
}
ApiKeyService(DataStoreFactory storeFactory, PasswordService passwordService, KeyGenerator keyGenerator, ApiKeyTokenHandler tokenHandler, Supplier<String> passphraseGenerator) {
2020-09-28 18:11:07 +02:00
this.store = storeFactory.withType(ApiKeyCollection.class).withName("apiKeys").build();
this.passwordService = passwordService;
this.keyGenerator = keyGenerator;
2020-09-29 13:54:21 +02:00
this.tokenHandler = tokenHandler;
2020-09-29 11:08:36 +02:00
this.passphraseGenerator = passphraseGenerator;
2020-09-28 18:11:07 +02:00
}
2020-10-01 10:18:48 +02:00
public CreationResult createNewKey(String name, String permissionRole) {
2020-09-28 18:11:07 +02:00
String user = currentUser();
2020-09-29 11:08:36 +02:00
String passphrase = passphraseGenerator.get();
2020-09-28 18:11:07 +02:00
String hashedPassphrase = passwordService.encryptPassword(passphrase);
final String id = keyGenerator.createKey();
2020-10-01 10:18:48 +02:00
ApiKeyWithPassphrase key = new ApiKeyWithPassphrase(id, name, permissionRole, hashedPassphrase);
2020-09-28 18:11:07 +02:00
Lock lock = locks.get(user).writeLock();
lock.lock();
try {
if (containsName(user, name)) {
throw alreadyExists(ContextEntry.ContextBuilder.entity(ApiKeyWithPassphrase.class, name));
}
final ApiKeyCollection apiKeyCollection = store.getOptional(user).orElse(new ApiKeyCollection(emptyList()));
2020-09-29 13:54:21 +02:00
final ApiKeyCollection newApiKeyCollection = apiKeyCollection.add(key);
2020-09-28 18:11:07 +02:00
store.put(user, newApiKeyCollection);
} finally {
lock.unlock();
}
final String token = tokenHandler.createToken(user, new ApiKey(key), passphrase);
return new CreationResult(token, id);
2020-09-28 18:11:07 +02:00
}
2020-09-29 11:08:36 +02:00
public void remove(String id) {
2020-09-28 18:11:07 +02:00
String user = currentUser();
Lock lock = locks.get(user).writeLock();
lock.lock();
try {
2020-09-29 11:08:36 +02:00
if (!containsId(user, id)) {
2020-09-28 18:11:07 +02:00
return;
}
store.getOptional(user).ifPresent(
apiKeyCollection -> {
2020-09-29 11:08:36 +02:00
final ApiKeyCollection newApiKeyCollection = apiKeyCollection.remove(key -> id.equals(key.getId()));
2020-09-28 18:11:07 +02:00
store.put(user, newApiKeyCollection);
}
);
} finally {
lock.unlock();
}
}
2020-09-30 14:01:19 +02:00
CheckResult check(String tokenAsString) {
2020-09-29 13:54:21 +02:00
return check(tokenHandler.readToken(tokenAsString)
.orElseThrow(AuthorizationException::new));
}
2020-09-30 14:01:19 +02:00
private CheckResult check(ApiKeyTokenHandler.Token token) {
2020-09-29 13:54:21 +02:00
return check(token.getUser(), token.getApiKeyId(), token.getPassphrase());
}
2020-09-30 14:01:19 +02:00
CheckResult check(String user, String id, String passphrase) {
2020-09-28 18:11:07 +02:00
Lock lock = locks.get(user).readLock();
lock.lock();
try {
return store
.get(user)
.getKeys()
.stream()
2020-09-29 11:08:36 +02:00
.filter(key -> key.getId().equals(id))
2020-09-28 18:11:07 +02:00
.filter(key -> passwordService.passwordsMatch(passphrase, key.getPassphrase()))
2020-10-01 10:18:48 +02:00
.map(ApiKeyWithPassphrase::getPermissionRole)
2020-09-30 14:01:19 +02:00
.map(role -> new CheckResult(user, role))
.findAny()
.orElseThrow(AuthorizationException::new);
2020-09-28 18:11:07 +02:00
} finally {
lock.unlock();
}
}
2020-09-29 11:08:36 +02:00
public Collection<ApiKey> getKeys() {
return store.getOptional(currentUser())
.map(ApiKeyCollection::getKeys)
.map(Collection::stream)
.orElse(Stream.empty())
.map(ApiKey::new)
.collect(toList());
2020-09-28 18:11:07 +02:00
}
private String currentUser() {
return ThreadContext.getSubject().getPrincipals().getPrimaryPrincipal().toString();
}
2020-09-29 11:08:36 +02:00
private boolean containsId(String user, String id) {
return store
.getOptional(user)
.map(ApiKeyCollection::getKeys)
.orElse(emptyList())
.stream()
.anyMatch(key -> key.getId().equals(id));
}
2020-09-28 18:11:07 +02:00
private boolean containsName(String user, String name) {
return store
.getOptional(user)
.map(ApiKeyCollection::getKeys)
.orElse(emptyList())
.stream()
2020-09-29 11:08:36 +02:00
.anyMatch(key -> key.getDisplayName().equals(name));
2020-09-28 18:11:07 +02:00
}
@Getter
@AllArgsConstructor
public static class CreationResult {
private final String token;
private final String id;
}
2020-09-30 14:01:19 +02:00
@Getter
@AllArgsConstructor
public static class CheckResult {
private final String user;
2020-10-01 10:18:48 +02:00
private final String permissionRole;
2020-09-30 14:01:19 +02:00
}
2020-09-28 18:11:07 +02:00
}