first functional snapshot with unit test, no frontend changes

This commit is contained in:
Konstantin Schaper
2020-08-05 17:08:15 +02:00
parent 7072761ba1
commit 0ac8b90c2f
12 changed files with 436 additions and 205 deletions

View File

@@ -25,7 +25,7 @@
package sonia.scm.api.v2.resources;
import sonia.scm.repository.NamespaceAndName;
import sonia.scm.security.gpg.PublicKeyResource;
import sonia.scm.security.gpg.UserPublicKeyResource;
import javax.inject.Inject;
import java.net.URI;
@@ -104,7 +104,7 @@ class ResourceLinks {
UserLinks(ScmPathInfo pathInfo) {
userLinkBuilder = new LinkBuilder(pathInfo, UserRootResource.class, UserResource.class);
publicKeyLinkBuilder = new LinkBuilder(pathInfo, PublicKeyResource.class);
publicKeyLinkBuilder = new LinkBuilder(pathInfo, UserPublicKeyResource.class);
}
String self(String name) {

View File

@@ -25,9 +25,9 @@
package sonia.scm.security.gpg;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import sonia.scm.security.CipherUtil;
import sonia.scm.security.PrivateKey;
import sonia.scm.store.DataStore;
import sonia.scm.store.DataStoreFactory;
import sonia.scm.xml.XmlInstantAdapter;
@@ -66,7 +66,8 @@ class PrivateKeyStore {
@XmlAccessorType(XmlAccessType.FIELD)
@AllArgsConstructor
@NoArgsConstructor
private class RawPrivateKey {
@Getter
static class RawPrivateKey {
private String key;
@XmlJavaTypeAdapter(XmlInstantAdapter.class)

View File

@@ -71,14 +71,14 @@ public class PublicKeyCollectionMapper {
}
private String createLink(String username) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
return new LinkBuilder(scmPathInfoStore.get().get(), UserPublicKeyResource.class)
.method("create")
.parameters(username)
.href();
}
private String selfLink(String username) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
return new LinkBuilder(scmPathInfoStore.get().get(), UserPublicKeyResource.class)
.method("findAll")
.parameters(username)
.href();

View File

@@ -51,7 +51,7 @@ public abstract class PublicKeyMapper {
}
@Mapping(target = "attributes", ignore = true)
@Mapping(target = "raw", ignore = true)
// @Mapping(target = "raw", ignore = true) // TODO: Why is there ?
abstract RawGpgKeyDto map(RawGpgKey rawGpgKey);
@ObjectFactory
@@ -65,16 +65,16 @@ public abstract class PublicKeyMapper {
}
private String createSelfLink(RawGpgKey rawGpgKey) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
.method("findById")
.parameters(rawGpgKey.getId())
return new LinkBuilder(scmPathInfoStore.get().get(), UserPublicKeyResource.class)
.method("findByIdJson")
.parameters(rawGpgKey.getOwner(), rawGpgKey.getId())
.href();
}
private String createDeleteLink(RawGpgKey rawGpgKey) {
return new LinkBuilder(scmPathInfoStore.get().get(), PublicKeyResource.class)
return new LinkBuilder(scmPathInfoStore.get().get(), UserPublicKeyResource.class)
.method("deleteById")
.parameters(rawGpgKey.getId())
.parameters(rawGpgKey.getOwner(), rawGpgKey.getId())
.href();
}
}

View File

@@ -24,7 +24,6 @@
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;
@@ -34,71 +33,27 @@ import sonia.scm.security.AllowAnonymousAccess;
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.HeaderParam;
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;
public PublicKeyResource(PublicKeyStore store) {
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)
@Produces("application/pgp-keys")
@AllowAnonymousAccess
@Operation(
summary = "Get single key for user",
@@ -110,7 +65,7 @@ public class PublicKeyResource {
responseCode = "200",
description = "success",
content = @Content(
mediaType = MEDIA_TYPE,
mediaType = "application/pgp-keys",
schema = @Schema(implementation = RawGpgKeyDto.class)
)
)
@@ -132,63 +87,12 @@ public class PublicKeyResource {
schema = @Schema(implementation = ErrorDto.class)
)
)
public Response findByIdJson(@PathParam("id") String id) {
public Response findByIdGpg(@PathParam("id") String id) {
Optional<RawGpgKey> byId = store.findById(id);
if (byId.isPresent()) {
return Response.ok(mapper.map(byId.get())).build();
return Response.ok(byId.get().getRaw()).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

@@ -25,6 +25,7 @@
package sonia.scm.security.gpg;
import org.bouncycastle.openpgp.PGPPublicKey;
import sonia.scm.BadRequestException;
import sonia.scm.ContextEntry;
import sonia.scm.event.ScmEventBus;
import sonia.scm.repository.Person;
@@ -39,7 +40,6 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -102,9 +102,13 @@ public class PublicKeyStore {
public void delete(String id) {
RawGpgKey rawGpgKey = store.get(id);
if (rawGpgKey != null) {
UserPermissions.changePublicKeys(rawGpgKey.getOwner()).check();
store.remove(id);
eventBus.post(new PublicKeyDeletedEvent());
if (!rawGpgKey.isReadonly()) {
UserPermissions.changePublicKeys(rawGpgKey.getOwner()).check();
store.remove(id);
eventBus.post(new PublicKeyDeletedEvent());
} else {
throw new DeletingReadonlyKeyNotAllowedException(id);
}
}
}
@@ -125,4 +129,20 @@ public class PublicKeyStore {
.collect(Collectors.toList());
}
@SuppressWarnings("squid:MaximumInheritanceDepth")
// exceptions have a deep inheritance depth themselves; therefore we accept this here
public static class DeletingReadonlyKeyNotAllowedException extends BadRequestException {
public DeletingReadonlyKeyNotAllowedException(String keyId) {
super(ContextEntry.ContextBuilder.entity(RawGpgKey.class, keyId).build(), "deleting readonly gpg keys is not allowed");
}
private static final String CODE = "3US6mweXy1";
@Override
public String getCode() {
return CODE;
}
}
}

View File

@@ -60,12 +60,17 @@ public class RawGpgKey {
RawGpgKey(String id) {
this.id = id;
}
RawGpgKey(String id, String raw) {
this.id = id;
this.raw = raw;
}
RawGpgKey(String id, String displayName, String owner, String raw, Set<Person> contacts, Instant created) {
this.id = id;
this.displayName = displayName;
this.owner = owner;
this.contacts = contacts;
this.created = created;
this.raw = raw;
}
@Override

View File

@@ -0,0 +1,190 @@
/*
* 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/users/{username}/public_keys")
public class UserPublicKeyResource {
private static final String MEDIA_TYPE_COLLECTION = VndMediaType.PREFIX + "publicKeyCollection" + VndMediaType.SUFFIX;
private static final String MEDIA_TYPE = VndMediaType.PREFIX + "publicKey" + VndMediaType.SUFFIX;
private final PublicKeyCollectionMapper collectionMapper;
private final PublicKeyStore store;
private final PublicKeyMapper mapper;
@Inject
public UserPublicKeyResource(PublicKeyCollectionMapper collectionMapper, PublicKeyMapper mapper, PublicKeyStore store) {
this.collectionMapper = collectionMapper;
this.store = store;
this.mapper = mapper;
}
@GET
@Path("")
@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 id) {
return collectionMapper.map(id, store.findByUsername(id));
}
@POST
@Path("")
@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("{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();
}
@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 findByIdJson(@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();
}
}