add config form for public keys

This commit is contained in:
Eduard Heimbuch
2020-07-24 14:59:28 +02:00
parent 13326d6253
commit 4290ca4077
29 changed files with 1416 additions and 23 deletions

View File

@@ -27,6 +27,7 @@ package sonia.scm.api.v2.resources;
import com.google.inject.AbstractModule;
import com.google.inject.servlet.ServletScopes;
import org.mapstruct.factory.Mappers;
import sonia.scm.security.gpg.PublicKeyMapper;
import sonia.scm.web.api.RepositoryToHalMapper;
public class MapperModule extends AbstractModule {
@@ -35,6 +36,7 @@ public class MapperModule extends AbstractModule {
bind(UserDtoToUserMapper.class).to(Mappers.getMapperClass(UserDtoToUserMapper.class));
bind(UserToUserDtoMapper.class).to(Mappers.getMapperClass(UserToUserDtoMapper.class));
bind(UserCollectionToDtoMapper.class);
bind(PublicKeyMapper.class).to(Mappers.getMapperClass(PublicKeyMapper.class));
bind(GroupDtoToGroupMapper.class).to(Mappers.getMapperClass(GroupDtoToGroupMapper.class));
bind(GroupToGroupDtoMapper.class).to(Mappers.getMapperClass(GroupToGroupDtoMapper.class));

View File

@@ -89,6 +89,9 @@ public class MeDtoFactory extends HalAppenderMapper {
if (UserPermissions.modify(user).isPermitted()) {
linksBuilder.single(link("update", resourceLinks.me().update(user.getName())));
}
if (UserPermissions.changePublicKeys(user).isPermitted()) {
linksBuilder.single(link("publicKeys", resourceLinks.user().publicKeys(user.getName())));
}
if (userManager.isTypeDefault(user) && UserPermissions.changePassword(user).isPermitted() && !Authentications.isSubjectAnonymous(user.getName())) {
linksBuilder.single(link("password", resourceLinks.me().passwordChange()));
}

View File

@@ -25,6 +25,7 @@
package sonia.scm.api.v2.resources;
import sonia.scm.repository.NamespaceAndName;
import sonia.scm.security.gpg.PublicKeyResource;
import javax.inject.Inject;
import java.net.URI;
@@ -99,9 +100,11 @@ class ResourceLinks {
static class UserLinks {
private final LinkBuilder userLinkBuilder;
private final LinkBuilder publicKeyLinkBuilder;
UserLinks(ScmPathInfo pathInfo) {
userLinkBuilder = new LinkBuilder(pathInfo, UserRootResource.class, UserResource.class);
publicKeyLinkBuilder = new LinkBuilder(pathInfo, PublicKeyResource.class);
}
String self(String name) {
@@ -119,6 +122,10 @@ class ResourceLinks {
public String passwordChange(String name) {
return userLinkBuilder.method("getUserResource").parameters(name).method("overwritePassword").parameters().href();
}
public String publicKeys(String name) {
return publicKeyLinkBuilder.method("findAll").parameters(name).href();
}
}
interface WithPermissionLinks {

View File

@@ -65,6 +65,7 @@ public abstract class UserToUserDtoMapper extends BaseMapper<User, UserDto> {
}
if (UserPermissions.modify(user).isPermitted()) {
linksBuilder.single(link("update", resourceLinks.user().update(user.getName())));
linksBuilder.single(link("publicKeys", resourceLinks.user().publicKeys(user.getName())));
if (userManager.isTypeDefault(user)) {
linksBuilder.single(link("password", resourceLinks.user().passwordChange(user.getName())));
}

View File

@@ -0,0 +1,86 @@
/*
* 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.gpg;
import de.otto.edison.hal.Embedded;
import de.otto.edison.hal.HalRepresentation;
import de.otto.edison.hal.Link;
import de.otto.edison.hal.Links;
import sonia.scm.api.v2.resources.LinkBuilder;
import sonia.scm.api.v2.resources.ScmPathInfoStore;
import sonia.scm.user.UserPermissions;
import javax.inject.Inject;
import javax.inject.Provider;
import java.util.List;
import java.util.stream.Collectors;
import static de.otto.edison.hal.Links.linkingTo;
public class PublicKeyCollectionMapper {
private final Provider<ScmPathInfoStore> scmPathInfoStore;
private final PublicKeyMapper mapper;
@Inject
public PublicKeyCollectionMapper(Provider<ScmPathInfoStore> scmPathInfoStore, PublicKeyMapper mapper) {
this.scmPathInfoStore = scmPathInfoStore;
this.mapper = mapper;
}
HalRepresentation map(String username, List<RawGpgKey> keys) {
List<RawGpgKeyDto> dtos = keys.stream()
.map(mapper::map)
.collect(Collectors.toList());
Links.Builder builder = linkingTo();
builder.self(selfLink(username));
if (hasCreatePermissions(username)) {
builder.single(Link.link("create", createLink(username)));
}
return new HalRepresentation(builder.build(), Embedded.embedded("keys", dtos));
}
private boolean hasCreatePermissions(String username) {
return UserPermissions.changePublicKeys(username).isPermitted();
}
private String createLink(String username) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
.method("create")
.parameters(username)
.href();
}
private String selfLink(String username) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
.method("findAll")
.parameters(username)
.href();
}
}

View File

@@ -0,0 +1,79 @@
/*
* 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.gpg;
import com.google.common.annotations.VisibleForTesting;
import de.otto.edison.hal.Link;
import de.otto.edison.hal.Links;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ObjectFactory;
import sonia.scm.api.v2.resources.LinkBuilder;
import sonia.scm.api.v2.resources.ScmPathInfoStore;
import sonia.scm.user.UserPermissions;
import javax.inject.Inject;
import javax.inject.Provider;
import static de.otto.edison.hal.Links.linkingTo;
@Mapper
public abstract class PublicKeyMapper {
@Inject
private Provider<ScmPathInfoStore> scmPathInfoStore;
@VisibleForTesting
void setScmPathInfoStore(Provider<ScmPathInfoStore> scmPathInfoStore) {
this.scmPathInfoStore = scmPathInfoStore;
}
@Mapping(target = "attributes", ignore = true)
abstract RawGpgKeyDto map(RawGpgKey rawGpgKey);
@ObjectFactory
RawGpgKeyDto createDto(RawGpgKey rawGpgKey) {
Links.Builder linksBuilder = linkingTo();
linksBuilder.self(createSelfLink(rawGpgKey));
if (UserPermissions.changePublicKeys(rawGpgKey.getOwner()).isPermitted()) {
linksBuilder.single(Link.link("delete", createDeleteLink(rawGpgKey)));
}
return new RawGpgKeyDto(linksBuilder.build());
}
private String createSelfLink(RawGpgKey rawGpgKey) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
.method("findById")
.parameters(rawGpgKey.getId())
.href();
}
private String createDeleteLink(RawGpgKey rawGpgKey) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
.method("deleteById")
.parameters(rawGpgKey.getId())
.href();
}
}

View File

@@ -0,0 +1,191 @@
/*
* 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.gpg;
import de.otto.edison.hal.HalRepresentation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.web.VndMediaType;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.util.Optional;
@Path("v2/public_keys")
public class PublicKeyResource {
private static final String MEDIA_TYPE = VndMediaType.PREFIX + "publicKey" + VndMediaType.SUFFIX;
private static final String MEDIA_TYPE_COLLECTION = VndMediaType.PREFIX + "publicKeyCollection" + VndMediaType.SUFFIX;
private final PublicKeyMapper mapper;
private final PublicKeyCollectionMapper collectionMapper;
private final PublicKeyStore store;
@Inject
public PublicKeyResource(PublicKeyMapper mapper, PublicKeyCollectionMapper collectionMapper, PublicKeyStore store) {
this.mapper = mapper;
this.collectionMapper = collectionMapper;
this.store = store;
}
@GET
@Path("{username}")
@Produces(MEDIA_TYPE_COLLECTION)
@Operation(
summary = "Get all public keys for user",
description = "Returns all keys for the given username.",
tags = "User",
operationId = "get_all_public_keys"
)
@ApiResponse(
responseCode = "200",
description = "success",
content = @Content(
mediaType = MEDIA_TYPE_COLLECTION,
schema = @Schema(implementation = HalRepresentation.class)
)
)
@ApiResponse(responseCode = "401", description = "not authenticated / invalid credentials")
@ApiResponse(responseCode = "403", description = "not authorized / the current user does not have the right privilege")
@ApiResponse(
responseCode = "500",
description = "internal server error",
content = @Content(
mediaType = VndMediaType.ERROR_TYPE,
schema = @Schema(implementation = ErrorDto.class)
)
)
public HalRepresentation findAll(@PathParam("username") String username) {
return collectionMapper.map(username, store.findByUsername(username));
}
@GET
@Path("{id}")
@Produces(MEDIA_TYPE)
@Operation(
summary = "Get single key for user",
description = "Returns a single public key for username by id.",
tags = "User",
operationId = "get_single_public_key"
)
@ApiResponse(
responseCode = "200",
description = "success",
content = @Content(
mediaType = MEDIA_TYPE,
schema = @Schema(implementation = RawGpgKeyDto.class)
)
)
@ApiResponse(responseCode = "401", description = "not authenticated / invalid credentials")
@ApiResponse(responseCode = "403", description = "not authorized / the current user does not have the right privilege")
@ApiResponse(
responseCode = "404",
description = "not found / key for given id not available",
content = @Content(
mediaType = VndMediaType.ERROR_TYPE,
schema = @Schema(implementation = ErrorDto.class)
)
)
@ApiResponse(
responseCode = "500",
description = "internal server error",
content = @Content(
mediaType = VndMediaType.ERROR_TYPE,
schema = @Schema(implementation = ErrorDto.class)
)
)
public Response findById(@PathParam("id") String id) {
Optional<RawGpgKey> byId = store.findById(id);
if (byId.isPresent()) {
return Response.ok(mapper.map(byId.get())).build();
}
return Response.status(Response.Status.NOT_FOUND).build();
}
@POST
@Path("{username}")
@Consumes(MEDIA_TYPE)
@Operation(
summary = "Create new key",
description = "Creates new key for user.",
tags = "User",
operationId = "create_public_key"
)
@ApiResponse(responseCode = "201", description = "create success")
@ApiResponse(responseCode = "401", description = "not authenticated / invalid credentials")
@ApiResponse(responseCode = "403", description = "not authorized / the current user does not have the right privilege")
@ApiResponse(
responseCode = "500",
description = "internal server error",
content = @Content(
mediaType = VndMediaType.ERROR_TYPE,
schema = @Schema(implementation = ErrorDto.class)
)
)
public Response create(@Context UriInfo uriInfo, @PathParam("username") String username, RawGpgKeyDto publicKey) {
String id = store.add(publicKey.getDisplayName(), username, publicKey.getRaw()).getId();
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(id);
return Response.created(builder.build()).build();
}
@DELETE
@Path("delete/{id}")
@Operation(
summary = "Deletes public key",
description = "Deletes public key for user.",
tags = "User",
operationId = "delete_public_key"
)
@ApiResponse(responseCode = "204", description = "delete success")
@ApiResponse(responseCode = "401", description = "not authenticated / invalid credentials")
@ApiResponse(responseCode = "403", description = "not authorized / the current user does not have the right privilege")
@ApiResponse(
responseCode = "500",
description = "internal server error",
content = @Content(
mediaType = VndMediaType.ERROR_TYPE,
schema = @Schema(implementation = ErrorDto.class)
)
)
public Response deleteById(@PathParam("id") String id) {
store.delete(id);
return Response.noContent().build();
}
}

View File

@@ -24,18 +24,20 @@
package sonia.scm.security.gpg;
import com.google.common.annotations.VisibleForTesting;
import org.apache.shiro.SecurityUtils;
import org.bouncycastle.openpgp.PGPException;
import sonia.scm.ContextEntry;
import sonia.scm.security.NotPublicKeyException;
import sonia.scm.store.DataStore;
import sonia.scm.store.DataStoreFactory;
import sonia.scm.user.UserPermissions;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@Singleton
public class PublicKeyStore {
@@ -43,26 +45,22 @@ public class PublicKeyStore {
private static final String STORE_NAME = "gpg_public_keys";
private final DataStore<RawGpgKey> store;
private final Supplier<String> currentUserSupplier;
@Inject
public PublicKeyStore(DataStoreFactory dataStoreFactory) {
this(
dataStoreFactory.withType(RawGpgKey.class).withName(STORE_NAME).build(),
() -> SecurityUtils.getSubject().getPrincipal().toString()
);
this.store = dataStoreFactory.withType(RawGpgKey.class).withName(STORE_NAME).build();
}
@VisibleForTesting
PublicKeyStore(DataStore<RawGpgKey> store, Supplier<String> currentUserSupplier) {
this.store = store;
this.currentUserSupplier = currentUserSupplier;
}
public RawGpgKey add(String displayName, String username, String rawKey) {
UserPermissions.modify(username).check();
if (!rawKey.contains("PUBLIC KEY")) {
throw new NotPublicKeyException(ContextEntry.ContextBuilder.entity(RawGpgKey.class, displayName).build(), "The provided key is not a public key");
}
public RawGpgKey add(String displayName, String rawKey) {
try {
String id = Keys.resolveIdFromKey(rawKey);
RawGpgKey key = new RawGpgKey(id, displayName, currentUserSupplier.get(), rawKey, Instant.now());
RawGpgKey key = new RawGpgKey(id, displayName, username, rawKey, Instant.now());
store.put(id, key);
@@ -72,8 +70,23 @@ public class PublicKeyStore {
}
}
public void delete(String id) {
RawGpgKey rawGpgKey = store.get(id);
if (rawGpgKey != null) {
UserPermissions.modify(rawGpgKey.getOwner()).check();
store.remove(id);
}
}
public Optional<RawGpgKey> findById(String id) {
return store.getOptional(id);
}
public List<RawGpgKey> findByUsername(String username) {
return store.getAll().values()
.stream()
.filter(rawGpgKey -> username.equalsIgnoreCase(rawGpgKey.getOwner()))
.collect(Collectors.toList());
}
}

View File

@@ -32,6 +32,7 @@ import sonia.scm.xml.XmlInstantAdapter;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.time.Instant;
import java.util.Objects;
@@ -40,6 +41,7 @@ import java.util.Objects;
@NoArgsConstructor
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class RawGpgKey {
private String id;

View File

@@ -0,0 +1,48 @@
/*
* 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.gpg;
import de.otto.edison.hal.HalRepresentation;
import de.otto.edison.hal.Links;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@NoArgsConstructor
@SuppressWarnings("squid:S2160") // we do not need equals for dto
public class RawGpgKeyDto extends HalRepresentation {
private String displayName;
private String raw;
private Instant created;
RawGpgKeyDto(Links links) {
super(links);
}
}