From 1ad43ba902669e6888b07b59cc81f03fd5210b3a Mon Sep 17 00:00:00 2001 From: barreiro Date: Mon, 26 Aug 2024 14:38:07 +0100 Subject: [PATCH 1/2] API keys feature --- .../api/internal/services/UserService.java | 55 +++++ .../tools/horreum/entity/user/UserApiKey.java | 139 +++++++++++ .../tools/horreum/entity/user/UserInfo.java | 5 + .../horreum/mapper/UserApiKeyMapper.java | 25 ++ .../horreum/notification/EmailPlugin.java | 22 ++ .../horreum/notification/Notification.java | 5 + .../server/ApiKeyAuthenticationMechanism.java | 63 +++++ .../server/ApiKeyIdentityProvider.java | 53 ++++ .../tools/horreum/server/RolesAugmentor.java | 60 +++-- .../horreum/server/SecurityBootstrap.java | 1 + .../horreum/svc/NotificationServiceImpl.java | 15 ++ .../tools/horreum/svc/TimeService.java | 5 + .../tools/horreum/svc/UserServiceImpl.java | 134 ++++++++-- .../horreum/svc/user/DatabaseUserBackend.java | 12 + .../horreum/svc/user/KeycloakUserBackend.java | 26 +- .../tools/horreum/svc/user/UserBackEnd.java | 2 + .../src/main/resources/db/changeLog.xml | 32 +++ .../templates/api_key_expiration_email.html | 12 + .../horreum/svc/UserServiceAbstractTest.java | 90 +++++++ .../io/hyperfoil/tools/HorreumClient.java | 11 +- .../auth/HorreumApiKeyAuthentication.java | 30 +++ .../tools/horreum/it/HorreumClientIT.java | 33 +++ horreum-web/src/domain/user/ApiKeys.tsx | 228 ++++++++++++++++++ horreum-web/src/domain/user/UserSettings.tsx | 15 +- 24 files changed, 1013 insertions(+), 60 deletions(-) create mode 100644 horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java create mode 100644 horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java create mode 100644 horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java create mode 100644 horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java create mode 100644 horreum-backend/src/main/resources/templates/api_key_expiration_email.html create mode 100644 horreum-client/src/main/java/io/hyperfoil/tools/auth/HorreumApiKeyAuthentication.java create mode 100644 horreum-web/src/domain/user/ApiKeys.tsx diff --git a/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java b/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java index 857a059a4..580a0895f 100644 --- a/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java +++ b/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java @@ -1,5 +1,6 @@ package io.hyperfoil.tools.horreum.api.internal.services; +import java.time.LocalDate; import java.util.List; import java.util.Map; @@ -8,6 +9,7 @@ import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; @@ -118,6 +120,28 @@ List searchUsers( @Blocking String resetPassword(@PathParam("team") String team, @RequestBody(required = true) String username); + @POST + @Path("/apikey") + @Produces("text/plain") + @Blocking + String newApiKey(@RequestBody ApiKeyRequest request); + + @GET + @Path("/apikey") + @Blocking + List apiKeys(); + + @PUT + @Path("/apikey/{id}/rename") + @Consumes("text/plain") + @Blocking + void renameApiKey(@PathParam("id") long keyId, @RequestBody String newName); + + @PUT + @Path("/apikey/{id}/revoke") + @Blocking + void revokeApiKey(@PathParam("id") long keyId); + // this is a simplified copy of org.keycloak.representations.idm.UserRepresentation class UserData { @NotNull @@ -146,4 +170,35 @@ class NewUser { public String team; public List roles; } + + /** + * Key type allows to scope what the key gives access to + */ + enum KeyType { + USER + } + + class ApiKeyRequest { + public String name; + public KeyType type; + + public ApiKeyRequest() { + } + + public ApiKeyRequest(String name, KeyType type) { + this.name = name; + this.type = type; + } + } + + class ApiKeyResponse { + public long id; + public String name; + public KeyType type; + public LocalDate creation; + public LocalDate access; + public boolean isRevoked; + public long toExpiration; + } + } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java new file mode 100644 index 000000000..d5e860099 --- /dev/null +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java @@ -0,0 +1,139 @@ +package io.hyperfoil.tools.horreum.entity.user; + +import static jakarta.persistence.GenerationType.SEQUENCE; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.Comparator; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Stream; + +import jakarta.persistence.Entity; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.NamedQueries; +import jakarta.persistence.NamedQuery; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; + +import io.hyperfoil.tools.horreum.api.internal.services.UserService; +import io.quarkus.hibernate.orm.panache.PanacheEntityBase; + +@Entity +@Table(name = "userinfo_apikey") +@NamedQueries({ + // fetch all keys that expire on a given day + @NamedQuery(name = "UserApiKey.expire", query = "from UserApiKey where not revoked AND (access is null and (creation + active day) = ?1 or (access + active day) = ?1)"), + // fetch all keys that have gone past their expiration date + @NamedQuery(name = "UserApiKey.pastExpiration", query = "from UserApiKey where not revoked AND (access is null and (creation + active day) < ?1 or (access + active day) < ?1)"), +}) +public class UserApiKey extends PanacheEntityBase implements Comparable { + + // old authentication tokens are not listed and can't be modified, but are kept around to prevent re-use + public static long ARCHIVE_AFTER_DAYS = 7; + + @Id + @SequenceGenerator(name = "apikeyIdGenerator", sequenceName = "userinfo_apikey_id_seq", allocationSize = 1) + @GeneratedValue(strategy = SEQUENCE, generator = "apikeyIdGenerator") + public long id; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "username") + public UserInfo user; + + @Transient + private final UUID randomnessSource; + + private final String hash; + + public String name; + + @Enumerated + public final UserService.KeyType type; + + public LocalDate creation, access; + + public long active; // number of days after last access that the key remains active + + public boolean revoked; + + public UserApiKey() { + randomnessSource = null; + hash = null; + name = null; + type = UserService.KeyType.USER; + } + + public UserApiKey(String name, UserService.KeyType type, LocalDate creationDate, long valid) { + randomnessSource = UUID.randomUUID(); + this.name = name; + this.type = type; + this.active = valid; + hash = computeHash(keyString()); + creation = creationDate; + revoked = false; + } + + public boolean isArchived(LocalDate givenDay) { + return givenDay.isAfter((access == null ? creation : access).plusDays(active + ARCHIVE_AFTER_DAYS)); + } + + // calculate the number of days left until expiration (if negative it's the number of days after expiration) + public long toExpiration(LocalDate givenDay) { + return active - ChronoUnit.DAYS.between(access == null ? creation : access, givenDay); + } + + public String keyString() { + String typeStr = switch (type) { + case USER -> "USR"; + }; + return "H" + typeStr + "_" + randomnessSource.toString().replace("-", "_").toUpperCase(); // keep the dashes for quick validation of key format + } + + // returns the SHA-256 hash of a given key. the hash is what gets sored in the DB, and it's what get compared for authentication + private static String computeHash(String key) { + try { + return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(key.getBytes())); + } catch (NoSuchAlgorithmException e) { + return null; // ignore: SHA-256 should exist + } + } + + public static Optional findOptional(String key) { + // validate key structure before computing hash + if (key.startsWith("H") && Stream.of(4, 13, 18, 23, 28).allMatch(i -> key.charAt(i) == '_')) { + return UserApiKey. find("hash", computeHash(key)).firstResultOptional(); + } + return Optional.empty(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } else if (o == null || getClass() != o.getClass()) { + return false; + } + return Objects.equals(this.id, ((UserApiKey) o).id) && Objects.equals(this.hash, ((UserApiKey) o).hash); + } + + @Override + public int hashCode() { + return Objects.hash(id, hash); + } + + @Override + public int compareTo(UserApiKey other) { + return Comparator. comparing(a -> a.creation).thenComparing(a -> a.id).compare(this, other); + } +} diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserInfo.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserInfo.java index 2ab4b15c7..416ed7486 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserInfo.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserInfo.java @@ -71,6 +71,10 @@ public class UserInfo extends PanacheEntityBase { @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) public Set teams; + @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user") + @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) + public Set apiKeys; + public UserInfo() { } @@ -78,6 +82,7 @@ public UserInfo(String username) { this.username = username; this.roles = new HashSet<>(); this.teams = new HashSet<>(); + this.apiKeys = new HashSet<>(); } public void setPassword(String clearPassword) { diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java new file mode 100644 index 000000000..40bbf83cf --- /dev/null +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java @@ -0,0 +1,25 @@ +package io.hyperfoil.tools.horreum.mapper; + +import java.time.LocalDate; + +import io.hyperfoil.tools.horreum.api.internal.services.UserService; +import io.hyperfoil.tools.horreum.entity.user.UserApiKey; + +public class UserApiKeyMapper { + + public static UserApiKey from(UserService.ApiKeyRequest request, LocalDate creation, long valid) { + return new UserApiKey(request.name == null ? "" : request.name, request.type, creation, valid); + } + + public static UserService.ApiKeyResponse to(UserApiKey key) { + UserService.ApiKeyResponse response = new UserService.ApiKeyResponse(); + response.id = key.id; + response.name = key.name; + response.type = key.type; + response.creation = key.creation; + response.access = key.access; + response.isRevoked = key.revoked; + response.toExpiration = key.toExpiration(LocalDate.now()); + return response; + } +} diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java index 74dc8cbae..68a273ee5 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java @@ -7,6 +7,7 @@ import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; +import java.time.LocalDate; import java.util.Date; import jakarta.enterprise.context.ApplicationScoped; @@ -46,6 +47,9 @@ public class EmailPlugin implements NotificationPlugin { @Location("expected_run_notification_email") Template expectedRunNotificationEmail; + @Location("api_key_expiration_email") + Template apiKeyExpirationEmail; + @Inject ReactiveMailer mailer; @@ -150,6 +154,24 @@ public void notifyExpectedRun(String testName, int testId, long before, String e Log.debug("Sending mail: " + content); }); } + + @Override + public void notifyApiKeyExpiration(String keyName, LocalDate creation, LocalDate lastAccess, long toExpiration, + long active) { + String subject = String.format("%s API key \"%s\" %s", subjectPrefix, keyName, + toExpiration == -1 ? "EXPIRED" : "about to expire"); + String content = apiKeyExpirationEmail + .data("baseUrl", baseUrl) + .data("username", username) + .data("keyName", keyName) + .data("creation", creation) + .data("lastAccess", lastAccess) + .data("expiration", toExpiration) + .data("active", active) + .render(); + mailer.send(Mail.withHtml(data, subject, content)).await().atMost(sendMailTimeout); + Log.debug("Sending mail: " + content); + } } private String prettyPrintTime(long duration) { diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java index 02e92abf2..5a1d03aec 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java @@ -1,6 +1,7 @@ package io.hyperfoil.tools.horreum.notification; import java.time.Instant; +import java.time.LocalDate; import io.hyperfoil.tools.horreum.events.DatasetChanges; import io.hyperfoil.tools.horreum.svc.MissingValuesEvent; @@ -22,4 +23,8 @@ public abstract void notifyMissingDataset(String testName, int testId, String ru public abstract void notifyMissingValues(String testName, String fingerprint, MissingValuesEvent missing); public abstract void notifyExpectedRun(String testName, int testId, long before, String expectedBy, String backlink); + + public abstract void notifyApiKeyExpiration(String keyName, LocalDate creation, LocalDate lastAccess, long toExpiration, + long active); + } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java new file mode 100644 index 000000000..d5628ba06 --- /dev/null +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java @@ -0,0 +1,63 @@ +package io.hyperfoil.tools.horreum.server; + +import static io.quarkus.vertx.http.runtime.security.HttpCredentialTransport.Type.OTHER_HEADER; + +import java.util.Collections; +import java.util.Set; + +import jakarta.enterprise.context.ApplicationScoped; + +import io.netty.handler.codec.http.HttpResponseStatus; +import io.quarkus.security.identity.IdentityProviderManager; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.identity.request.AuthenticationRequest; +import io.quarkus.security.identity.request.BaseAuthenticationRequest; +import io.quarkus.vertx.http.runtime.security.ChallengeData; +import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism; +import io.quarkus.vertx.http.runtime.security.HttpCredentialTransport; +import io.smallrye.mutiny.Uni; +import io.vertx.ext.web.RoutingContext; + +/** + * Look for a special HTTP header to provide authentication of HTTP requests + */ +@ApplicationScoped +public class ApiKeyAuthenticationMechanism implements HttpAuthenticationMechanism { + + public static final String HORREUM_API_KEY_HEADER = "X-Horreum-API-Key"; + + @Override + public Uni authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { + String headerValue = context.request().headers().get(HORREUM_API_KEY_HEADER); + return headerValue == null ? Uni.createFrom().nullItem() + : identityProviderManager.authenticate(new Request(headerValue)); + } + + @Override + public Uni getChallenge(RoutingContext context) { + return Uni.createFrom().item(new ChallengeData(HttpResponseStatus.UNAUTHORIZED.code(), null, null)); + } + + @Override + public Set> getCredentialTypes() { + return Collections.singleton(Request.class); + } + + @Override + public Uni getCredentialTransport(RoutingContext context) { + return Uni.createFrom().item(new HttpCredentialTransport(OTHER_HEADER, HORREUM_API_KEY_HEADER)); + } + + public static class Request extends BaseAuthenticationRequest implements AuthenticationRequest { + + private final String key; + + public Request(String key) { + this.key = key; + } + + public String getKey() { + return key; + } + } +} diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java new file mode 100644 index 000000000..0497a2884 --- /dev/null +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java @@ -0,0 +1,53 @@ +package io.hyperfoil.tools.horreum.server; + +import io.quarkus.logging.Log; +import io.quarkus.security.AuthenticationFailedException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; + +import io.hyperfoil.tools.horreum.entity.user.UserApiKey; +import io.hyperfoil.tools.horreum.svc.TimeService; +import io.quarkus.security.identity.AuthenticationRequestContext; +import io.quarkus.security.identity.IdentityProvider; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.runtime.QuarkusPrincipal; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.smallrye.mutiny.Uni; + +/** + * Retrieve and validate the key got from {@link ApiKeyAuthenticationMechanism} and create a SecurityIdentity from it. + */ +@ApplicationScoped +public class ApiKeyIdentityProvider implements IdentityProvider { + + @Inject + TimeService timeService; + + @Override + public Class getRequestType() { + return ApiKeyAuthenticationMechanism.Request.class; + } + + @Override + public Uni authenticate(ApiKeyAuthenticationMechanism.Request request, + AuthenticationRequestContext context) { + return context.runBlocking(() -> identityFromKey(request.getKey())); + } + + @Transactional + SecurityIdentity identityFromKey(String key) { + return UserApiKey.findOptional(key) + .filter(k -> !k.revoked) + .map((userKey) -> { + Log.debugv("Authentication of user {0} with key \"{1}\" {2}", userKey.user.username, userKey.name, key); + + // update last access + userKey.access = timeService.today(); + + // create identity with just the principal, roles will be populated in RolesAugmentor + return QuarkusSecurityIdentity.builder().setPrincipal(new QuarkusPrincipal(userKey.user.username)).build(); + }) + .orElse(null); + } +} diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/RolesAugmentor.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/RolesAugmentor.java index 8f5138e26..d00298252 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/RolesAugmentor.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/RolesAugmentor.java @@ -1,15 +1,13 @@ package io.hyperfoil.tools.horreum.server; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.eclipse.microprofile.config.inject.ConfigProperty; -import io.hyperfoil.tools.horreum.entity.user.TeamMembership; -import io.hyperfoil.tools.horreum.entity.user.UserInfo; -import io.hyperfoil.tools.horreum.entity.user.UserRole; import io.hyperfoil.tools.horreum.svc.ServiceException; -import io.quarkus.arc.lookup.LookupIfProperty; +import io.hyperfoil.tools.horreum.svc.user.UserBackEnd; import io.quarkus.arc.profile.UnlessBuildProfile; import io.quarkus.security.identity.AuthenticationRequestContext; import io.quarkus.security.identity.SecurityIdentity; @@ -19,7 +17,6 @@ @ApplicationScoped @UnlessBuildProfile("test") -@LookupIfProperty(name = "horreum.roles.provider", stringValue = "database") public class RolesAugmentor implements SecurityIdentityAugmentor { @Inject @@ -28,46 +25,61 @@ public class RolesAugmentor implements SecurityIdentityAugmentor { @ConfigProperty(name = "horreum.roles.database.override", defaultValue = "true") boolean override; + @ConfigProperty(name = "horreum.roles.provider") + String provider; + + @Inject + Instance backend; + @Override public Uni augment(SecurityIdentity identity, AuthenticationRequestContext context) { return identity.isAnonymous() ? Uni.createFrom().item(identity) : context.runBlocking(() -> addHorreumRoles(identity)); } private SecurityIdentity addHorreumRoles(SecurityIdentity identity) { + return switch (provider) { + case "database" -> rolesFromDB(identity); + case "keycloak" -> rolesFromKeycloak(identity); + default -> identity; + }; + } + + private SecurityIdentity rolesFromDB(SecurityIdentity identity) { String username = identity.getPrincipal().getName(); String previousRoles = roleManager.setRoles(username); try { - UserInfo user = UserInfo.findById(username); + QuarkusSecurityIdentity.Builder builder; if (override) { - if (user == null) { - throw ServiceException.serverError("Unable to fetch user entity"); - } - QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(); + builder = QuarkusSecurityIdentity.builder(); builder.setAnonymous(false); builder.setPrincipal(identity.getPrincipal()); builder.addAttributes(identity.getAttributes()); builder.addCredentials(identity.getCredentials()); builder.addPermissionChecker(identity::checkPermission); - - addRoles(builder, user); - return builder.build(); } else { - if (user == null) { - return identity; - } - QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(identity); - addRoles(builder, user); - return builder.build(); + builder = QuarkusSecurityIdentity.builder(identity); + } + backend.get().getRoles(username).forEach(builder::addRole); + return builder.build(); + } catch (Exception e) { + if (override) { + throw ServiceException.serverError("Unable to fetch user entity"); + } else { + return identity; // ignore exception when the user does not exist } } finally { roleManager.setRoles(previousRoles); } } - private void addRoles(QuarkusSecurityIdentity.Builder builder, UserInfo user) { - user.roles.stream().map(UserRole::toString).map(String::toLowerCase).forEach(builder::addRole); - user.teams.stream().map(TeamMembership::asRole).forEach(builder::addRole); - user.teams.stream().map(TeamMembership::asTeam).forEach(builder::addRole); - user.teams.stream().map(TeamMembership::asUIRole).distinct().forEach(builder::addRole); + private SecurityIdentity rolesFromKeycloak(SecurityIdentity identity) { + // no roles mean authentication from a horreum auth token. only in that case fetch roles from keycloak + if (identity.getRoles().isEmpty()) { + QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(identity); + backend.get().getRoles(identity.getPrincipal().getName()).forEach(builder::addRole); + return builder.build(); + } else { + return identity; + } } } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/SecurityBootstrap.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/SecurityBootstrap.java index eecc31858..efa2db770 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/SecurityBootstrap.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/SecurityBootstrap.java @@ -152,6 +152,7 @@ public void checkBootstrapAccount() { // create db entry, if not existent, like in UserService.createLocalUser() UserInfo userInfo = UserInfo. findByIdOptional(BOOTSTRAP_ACCOUNT).orElse(new UserInfo(BOOTSTRAP_ACCOUNT)); userInfo.defaultTeam = "dev-team"; + userInfo.persist(); Log.infov("\n>>>\n>>> Created temporary account {0} with password {1}\n>>>", BOOTSTRAP_ACCOUNT, user.password); } else if (administrators.size() > 1 && administrators.contains(BOOTSTRAP_ACCOUNT)) { diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/NotificationServiceImpl.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/NotificationServiceImpl.java index ebbdae43e..a091a5e1a 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/NotificationServiceImpl.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/NotificationServiceImpl.java @@ -28,6 +28,7 @@ import io.hyperfoil.tools.horreum.entity.alerting.NotificationSettingsDAO; import io.hyperfoil.tools.horreum.entity.data.DatasetDAO; import io.hyperfoil.tools.horreum.entity.data.TestDAO; +import io.hyperfoil.tools.horreum.entity.user.UserApiKey; import io.hyperfoil.tools.horreum.events.DatasetChanges; import io.hyperfoil.tools.horreum.mapper.NotificationSettingsMapper; import io.hyperfoil.tools.horreum.notification.Notification; @@ -190,4 +191,18 @@ public void notifyExpectedRun(int testId, long expectedBefore, String expectedBy String name = test != null ? test.name : ""; notifyAll(testId, n -> n.notifyExpectedRun(name, testId, expectedBefore, expectedBy, backlink)); } + + @WithRoles(extras = Roles.HORREUM_SYSTEM) + public void notifyApiKeyExpiration(UserApiKey key, long toExpiration) { + NotificationSettingsDAO. stream("name", key.user.username).forEach(notification -> { + NotificationPlugin plugin = plugins.get(notification.method); + if (plugin == null) { + log.errorf("Cannot notify %s of API key \"%s\" expiration: no plugin for method %s", + notification.name, key.name, notification.method); + } else { + plugin.create(notification.name, notification.data) + .notifyApiKeyExpiration(key.name, key.creation, key.access, toExpiration, key.active); + } + }); + } } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java index 215a5228c..2cb3c0038 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java @@ -1,6 +1,7 @@ package io.hyperfoil.tools.horreum.svc; import java.time.Instant; +import java.time.LocalDate; import jakarta.enterprise.context.ApplicationScoped; @@ -12,4 +13,8 @@ public class TimeService { public Instant now() { return Instant.now(); } + + public LocalDate today() { + return LocalDate.now(); + } } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java index 29aff07bb..116b3de24 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java @@ -9,6 +9,8 @@ import java.util.Map; import java.util.function.Function; +import io.hyperfoil.tools.horreum.mapper.UserApiKeyMapper; +import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.RolesAllowed; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; @@ -16,10 +18,12 @@ import jakarta.transaction.Transactional; import io.hyperfoil.tools.horreum.api.internal.services.UserService; +import io.hyperfoil.tools.horreum.entity.user.UserApiKey; import io.hyperfoil.tools.horreum.entity.user.UserInfo; import io.hyperfoil.tools.horreum.server.WithRoles; import io.hyperfoil.tools.horreum.svc.user.UserBackEnd; import io.quarkus.logging.Log; +import io.quarkus.scheduler.Scheduled; import io.quarkus.security.Authenticated; import io.quarkus.security.identity.SecurityIdentity; @@ -27,6 +31,11 @@ @ApplicationScoped public class UserServiceImpl implements UserService { + /** + * Default number of days API keys remain active after it's used to access the system + */ + public static final long DEFAULT_API_KEY_ACTIVE_DAYS = 30; + private static final int RANDOM_PASSWORD_LENGTH = 15; @Inject @@ -35,6 +44,21 @@ public class UserServiceImpl implements UserService { @Inject Instance backend; + @Inject + NotificationServiceImpl notificationServiceimpl; + + @Inject + TimeService timeService; + + private UserInfo currentUser() { + return UserInfo. findByIdOptional(getUsername()) + .orElseThrow(() -> ServiceException.notFound(format("Username {0} not found", getUsername()))); + } + + private String getUsername() { + return identity.getPrincipal().getName(); + } + @Override public List getRoles() { return identity.getRoles().stream().toList(); @@ -52,7 +76,7 @@ public List info(List usernames) { return backend.get().info(usernames); } - // ideally we want to enforce these roles in some of the endpoints, but for now this has to be done in the code + // ideally we want to enforce these roles in some endpoints, but for now this has to be done in the code // @RolesAllowed({ Roles.ADMIN, Roles.MANAGER }) @Override public void createUser(NewUser user) { @@ -61,19 +85,19 @@ public void createUser(NewUser user) { backend.get().createUser(user); createLocalUser(user.user.username, user.team, user.roles != null && user.roles.contains(Roles.MACHINE) ? user.password : null); - Log.infov("{0} created user {1} {2} with username {3} on team {4}", identity.getPrincipal().getName(), + Log.infov("{0} created user {1} {2} with username {3} on team {4}", getUsername(), user.user.firstName, user.user.lastName, user.user.username, user.team); } @RolesAllowed({ Roles.ADMIN, Roles.MANAGER }) @Override public void removeUser(String username) { - if (identity.getPrincipal().getName().equals(username)) { + if (getUsername().equals(username)) { throw ServiceException.badRequest("Cannot remove yourself"); } backend.get().removeUser(username); removeLocalUser(username); - Log.infov("{0} removed user {1}", identity.getPrincipal().getName(), username); + Log.infov("{0} removed user {1}", getUsername(), username); } @Override @@ -85,9 +109,9 @@ public List getTeams() { @WithRoles(extras = Roles.HORREUM_SYSTEM) @Override public String defaultTeam() { - UserInfo userInfo = UserInfo.findById(identity.getPrincipal().getName()); + UserInfo userInfo = currentUser(); if (userInfo == null) { - throw ServiceException.notFound(format("User with username {0} not found", identity.getPrincipal().getName())); + throw ServiceException.notFound(format("User with username {0} not found", getUsername())); } return userInfo.defaultTeam != null ? userInfo.defaultTeam : ""; } @@ -96,9 +120,9 @@ public String defaultTeam() { @WithRoles(addUsername = true) @Override public void setDefaultTeam(String unsafeTeam) { - UserInfo userInfo = UserInfo.findById(identity.getPrincipal().getName()); + UserInfo userInfo = currentUser(); if (userInfo == null) { - throw ServiceException.notFound(format("User with username {0} not found", identity.getPrincipal().getName())); + throw ServiceException.notFound(format("User with username {0} not found", getUsername())); } userInfo.defaultTeam = validateTeamName(unsafeTeam); userInfo.persistAndFlush(); @@ -140,7 +164,7 @@ public List getAllTeams() { public void addTeam(String unsafeTeam) { String team = validateTeamName(unsafeTeam); backend.get().addTeam(team); - Log.infov("{0} created team {1}", identity.getPrincipal().getName(), team); + Log.infov("{0} created team {1}", getUsername(), team); } @RolesAllowed(Roles.ADMIN) @@ -148,7 +172,7 @@ public void addTeam(String unsafeTeam) { public void deleteTeam(String unsafeTeam) { String team = validateTeamName(unsafeTeam); backend.get().deleteTeam(team); - Log.infov("{0} deleted team {1}", identity.getPrincipal().getName(), team); + Log.infov("{0} deleted team {1}", getUsername(), team); } @RolesAllowed(Roles.ADMIN) @@ -160,7 +184,7 @@ public List administrators() { @RolesAllowed(Roles.ADMIN) @Override public void updateAdministrators(List newAdmins) { - if (!newAdmins.contains(identity.getPrincipal().getName())) { + if (!newAdmins.contains(getUsername())) { throw ServiceException.badRequest("Cannot remove yourself from administrator list"); } backend.get().updateAdministrators(newAdmins); @@ -187,14 +211,12 @@ public String resetPassword(String unsafeTeam, String username) { if (backend.get().machineAccounts(team).stream().noneMatch(data -> data.username.equals(username))) { throw ServiceException.badRequest(format("User {0} is not machine account of team {1}", username, team)); } - UserInfo userInfo = UserInfo.findById(username); - if (userInfo == null) { - throw ServiceException.notFound(format("User with username {0} not found", username)); - } String newPassword = new SecureRandom().ints(RANDOM_PASSWORD_LENGTH, '0', 'z' + 1) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); - userInfo.setPassword(newPassword); - Log.infov("{0} reset password of user {1}", identity.getPrincipal().getName(), username); + UserInfo. findByIdOptional(username) + .orElseThrow(() -> ServiceException.notFound(format("Username {0} not found", username))) + .setPassword(newPassword); + Log.infov("{0} reset password of user {1}", getUsername(), username); return newPassword; } @@ -271,6 +293,84 @@ void removeLocalUser(String username) { // --- // + @Transactional + @WithRoles(addUsername = true) + @Override + public String newApiKey(ApiKeyRequest request) { + validateApiKeyName(request.name == null ? "" : request.name); + UserInfo userInfo = currentUser(); + + UserApiKey newKey = UserApiKeyMapper.from(request, timeService.today(), DEFAULT_API_KEY_ACTIVE_DAYS); + newKey.user = userInfo; + userInfo.apiKeys.add(newKey); + newKey.persist(); + userInfo.persist(); + + Log.debugv("{0} created API key \"{1}\"", getUsername(), request.name == null ? "" : request.name); + return newKey.keyString(); + } + + @Transactional + @WithRoles(extras = Roles.HORREUM_SYSTEM) + @Override + public List apiKeys() { + return currentUser().apiKeys.stream() + .filter(t -> !t.isArchived(timeService.today())) + .sorted() + .map(UserApiKeyMapper::to) + .toList(); + } + + @Transactional + @WithRoles(addUsername = true) + @Override + public void renameApiKey(long keyId, String newName) { + validateApiKeyName(newName == null ? "" : newName); + UserApiKey key = UserApiKey. findByIdOptional(keyId) + .orElseThrow(() -> ServiceException.notFound(format("Key with id {0} not found", keyId))); + if (key.revoked) { + throw ServiceException.badRequest("Can't rename revoked key"); + } + String oldName = key.name; + key.name = newName == null ? "" : newName; + Log.debugv("{0} renamed API key \"{1}\" to \"{2}\"", getUsername(), oldName, newName == null ? "" : newName); + } + + @Transactional + @WithRoles(addUsername = true) + @Override + public void revokeApiKey(long keyId) { + UserApiKey key = UserApiKey. findByIdOptional(keyId) + .orElseThrow(() -> ServiceException.notFound(format("Key with id {0} not found", keyId))); + key.revoked = true; + Log.debugv("{0} revoked API key \"{1}\"", getUsername(), key.name); + } + + @PermitAll + @Transactional + @WithRoles(extras = Roles.HORREUM_SYSTEM) + @Scheduled(every = "P1d") // daily -- it may lag up tp 24h compared to the actual date, but keys are revoked 24h after notification + public void apiKeyDailyTask() { + // notifications of keys expired and about to expire -- hardcoded to send multiple notices in the week prior to expiration + for (long toExpiration : List.of(7, 2, 1, 0, -1)) { + UserApiKey. stream("#UserApiKey.expire", timeService.today().plusDays(toExpiration)) + .forEach(key -> notificationServiceimpl.notifyApiKeyExpiration(key, toExpiration)); + } + // revoke expired keys -- could be done directly in the DB but iterate instead to be able to log + UserApiKey. stream("#UserApiKey.pastExpiration", timeService.today()).forEach(key -> { + Log.debugv("Idle API key \"{0}\" revoked", key.name); + key.revoked = true; + }); + } + + private void validateApiKeyName(String keyName) { + if (keyName.startsWith("horreum.")) { + throw ServiceException.badRequest("key names starting with 'horreum.' are reserved for internal use"); + } + } + + // --- // + public static final class FirstParameter implements Function { @Override public String[] apply(Object[] objects) { diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/DatabaseUserBackend.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/DatabaseUserBackend.java index d4fe57adc..e56bbe9c7 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/DatabaseUserBackend.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/DatabaseUserBackend.java @@ -49,6 +49,18 @@ private static String removeTeamSuffix(String team) { return team.substring(0, team.length() - 5); } + @Transactional + @Override + public List getRoles(String username) { + UserInfo user = UserInfo.findById(username); + List roles = new ArrayList<>(); + user.roles.stream().map(UserRole::toString).map(String::toLowerCase).forEach(roles::add); + user.teams.stream().map(TeamMembership::asRole).forEach(roles::add); + user.teams.stream().map(TeamMembership::asTeam).forEach(roles::add); + user.teams.stream().map(TeamMembership::asUIRole).distinct().forEach(roles::add); + return roles; + } + @Transactional @WithRoles(extras = Roles.HORREUM_SYSTEM) @Override diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/KeycloakUserBackend.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/KeycloakUserBackend.java index c11cb0f6e..057eda5b2 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/KeycloakUserBackend.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/KeycloakUserBackend.java @@ -86,6 +86,12 @@ private Set safeMachineIds() { } } + @Override + public List getRoles(String username) { + return keycloak.realm(realm).users().get(findMatchingUser(username).getId()).roles().realmLevel().listAll().stream() + .map(RoleRepresentation::getName).toList(); + } + @Override public List info(List usernames) { List users = new ArrayList<>(); @@ -125,13 +131,7 @@ public void createUser(UserService.NewUser user) { try { // assign the provided roles to the realm UsersResource usersResource = keycloak.realm(realm).users(); - List matchingUsers = usersResource.search(rep.getUsername(), true); - if (matchingUsers == null || matchingUsers.isEmpty()) { - throw ServiceException.badRequest(format("User {0} does not exist", rep.getUsername())); - } else if (matchingUsers.size() > 1) { - throw ServiceException.serverError(format("More than one user with username {0}", rep.getUsername())); - } - String userId = matchingUsers.get(0).getId(); + String userId = findMatchingUser(rep.getUsername()).getId(); if (user.team != null) { String prefix = getTeamPrefix(user.team); @@ -168,7 +168,7 @@ public void createUser(UserService.NewUser user) { @Override public void removeUser(String username) { - try (Response response = keycloak.realm(realm).users().delete(findMatchingUserId(username))) { + try (Response response = keycloak.realm(realm).users().delete(findMatchingUser(username).getId())) { if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { LOG.warnv("Got {0} response for removing user {0}", response.getStatusInfo(), username); throw ServiceException.serverError(format("Unable to remove user {0}", username)); @@ -207,7 +207,7 @@ public List getTeams() { // get the "team roles" in the realm } } - private String findMatchingUserId(String username) { // find the clientID of a single user + private UserRepresentation findMatchingUser(String username) { // find the clientID of a single user List matchingUsers = keycloak.realm(realm).users().search(username, true); if (matchingUsers == null || matchingUsers.isEmpty()) { LOG.warnv("Cannot find user with username {0}", username); @@ -217,7 +217,7 @@ private String findMatchingUserId(String username) { // find the clientID of a s matchingUsers.stream().map(UserRepresentation::getId).collect(joining(" "))); throw ServiceException.serverError(format("More than one user with username {0}", username)); } - return matchingUsers.get(0).getId(); + return matchingUsers.get(0); } @Override @@ -247,7 +247,7 @@ public void updateTeamMembers(String team, Map> roles) { // RoleMappingResource rolesMappingResource; try { // fetch the current roles for the user - String userId = findMatchingUserId(entry.getKey()); + String userId = findMatchingUser(entry.getKey()).getId(); rolesMappingResource = keycloak.realm(realm).users().get(userId).roles(); existingRoles = rolesMappingResource.getAll().getRealmMappings().stream().map(RoleRepresentation::getName) .toList(); @@ -396,7 +396,7 @@ public void updateAdministrators(List newAdmins) { // update the list of for (String username : newAdmins) { // add admin role for `newAdmins` not in `oldAdmins` if (oldAdmins.stream().noneMatch(old -> username.equals(old.getUsername()))) { try { - usersResource.get(findMatchingUserId(username)).roles().realmLevel().add(List.of(adminRole)); + usersResource.get(findMatchingUser(username).getId()).roles().realmLevel().add(List.of(adminRole)); LOG.infov("Added administrator role to user {0}", username); } catch (Throwable t) { LOG.warnv("Could not add admin role to user {0} due to {1}", username, t.getMessage()); @@ -434,7 +434,7 @@ public void setPassword(String username, String password) { credentials.setType(CredentialRepresentation.PASSWORD); credentials.setValue(password); - keycloak.realm(realm).users().get(findMatchingUserId(username)).resetPassword(credentials); + keycloak.realm(realm).users().get(findMatchingUser(username).getId()).resetPassword(credentials); } catch (Throwable t) { LOG.warnv(t, "Failed to retrieve current representation of user {0} from Keycloak", username); throw ServiceException diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/UserBackEnd.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/UserBackEnd.java index f04937238..bf55ce30e 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/UserBackEnd.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/user/UserBackEnd.java @@ -10,6 +10,8 @@ */ public interface UserBackEnd { + List getRoles(String username); + List searchUsers(String query); List info(List usernames); diff --git a/horreum-backend/src/main/resources/db/changeLog.xml b/horreum-backend/src/main/resources/db/changeLog.xml index c269d5493..1c428818d 100644 --- a/horreum-backend/src/main/resources/db/changeLog.xml +++ b/horreum-backend/src/main/resources/db/changeLog.xml @@ -4566,4 +4566,36 @@ CREATE INDEX idx_label_metrics_partial ON label (id) WHERE metrics = TRUE; + + ANY + + + + + + + + + + + + + + + + + + + + + + GRANT SELECT, INSERT, DELETE, UPDATE ON TABLE userinfo_apikey TO "${quarkus.datasource.username}"; + GRANT ALL ON SEQUENCE userinfo_apikey_id_seq TO "${quarkus.datasource.username}"; + ALTER TABLE userinfo_apikey ENABLE ROW LEVEL SECURITY; + CREATE POLICY userinfo_apikey_read ON userinfo_apikey USING (has_role('horreum.system')); + CREATE POLICY userinfo_apikey_rw ON userinfo_apikey FOR ALL USING (has_role(username)); + + diff --git a/horreum-backend/src/main/resources/templates/api_key_expiration_email.html b/horreum-backend/src/main/resources/templates/api_key_expiration_email.html new file mode 100644 index 000000000..218c535d7 --- /dev/null +++ b/horreum-backend/src/main/resources/templates/api_key_expiration_email.html @@ -0,0 +1,12 @@ +

Hello {username},

+

The API key "{keyName}" created on {creation} + {#when expiration} + {#is < 0} HAS EXPIRED. + {#is < 1} expires today. + {#is < 2} expires tomorrow. + {#else} expires in {expiration} days. + {/when} +

+

The key was {#if lastAccess == null}never used{#else}last used on {lastAccess}{/if}.

+

Remember that this key is automatically revoked if not used for {active} days.

+Horreum Alerting diff --git a/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java b/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java index 667722c21..f6b6035d5 100644 --- a/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java +++ b/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java @@ -1,5 +1,7 @@ package io.hyperfoil.tools.horreum.svc; +import static io.hyperfoil.tools.horreum.api.internal.services.UserService.KeyType.USER; +import static io.hyperfoil.tools.horreum.svc.UserServiceImpl.DEFAULT_API_KEY_ACTIVE_DAYS; import static io.restassured.RestAssured.given; import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_UNAUTHORIZED; @@ -9,6 +11,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -23,8 +26,10 @@ import org.jboss.logging.Logger; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import io.hyperfoil.tools.horreum.api.internal.services.UserService; +import io.hyperfoil.tools.horreum.entity.user.UserApiKey; import io.hyperfoil.tools.horreum.entity.user.UserInfo; import io.hyperfoil.tools.horreum.server.SecurityBootstrap; import io.hyperfoil.tools.horreum.server.WithRoles; @@ -34,6 +39,7 @@ import io.quarkus.security.identity.SecurityIdentity; import io.quarkus.security.runtime.QuarkusPrincipal; import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.quarkus.test.junit.QuarkusMock; import io.quarkus.test.security.TestIdentityAssociation; import io.quarkus.test.security.TestSecurity; @@ -56,6 +62,9 @@ public abstract class UserServiceAbstractTest { @Inject SecurityBootstrap securitiyBootstrap; + @Inject + TimeService timeService; + /** * Runs a section of a test under a different user */ @@ -554,4 +563,85 @@ void bootstrapAccount() { userService.administrators().stream().map(userData -> userData.username).anyMatch("horreum.bootstrap"::equals), "Bootstrap account missing"); } + + @TestSecurity(user = KEYCLOAK_ADMIN, roles = { Roles.ADMIN }) + @Test + void apiKeys() { + String testTeam = "apikeys-team", apiUser = "api-user"; + userService.addTeam(testTeam); + + // add a user to the team + UserService.NewUser user = new UserService.NewUser(); + user.user = new UserService.UserData("", apiUser, "API", "User", "api@horreum.io"); + user.password = "whatever"; + user.team = testTeam; + user.roles = List.of(Roles.MANAGER); + userService.createUser(user); + + overrideTestSecurity(apiUser, Set.of(Roles.MANAGER, testTeam.substring(0, testTeam.length() - 4) + Roles.MANAGER), + () -> { + // notification mock + NotificationServiceImpl notificationService = Mockito.mock(NotificationServiceImpl.class); + List notifications = Collections.synchronizedList(new ArrayList<>()); + Mockito.doAnswer(invocation -> { + notifications.add(invocation.getArgument(0)); + return null; + }).when(notificationService).notifyApiKeyExpiration(Mockito.any(), Mockito.anyLong()); + QuarkusMock.installMockForType(notificationService, NotificationServiceImpl.class); + + // empty state + assertTrue(userService.apiKeys().isEmpty()); + + // create key + String key = userService.newApiKey(new UserService.ApiKeyRequest("Test key", USER)); + assertFalse(key.length() < 32); // key should be big enough + assertTrue(UserApiKey.findOptional(key).isPresent()); // is persisted + + // one key + List keys = userService.apiKeys(); + assertEquals(1, keys.size()); + assertEquals(DEFAULT_API_KEY_ACTIVE_DAYS, keys.get(0).toExpiration); + assertFalse(keys.get(0).isRevoked); + + // rename key + assertThrows(ServiceException.class, () -> userService.renameApiKey(keys.get(0).id, "horreum.key")); + userService.renameApiKey(keys.get(0).id, "Key with new name"); + assertEquals("Key with new name", userService.apiKeys().get(0).name); + + // the system can find the key by its expiration day + assertTrue( + UserApiKey + . stream("#UserApiKey.expire", + timeService.today().plusDays(DEFAULT_API_KEY_ACTIVE_DAYS)) + .anyMatch(k -> k.id == keys.get(0).id)); + + // about to expire + assertTrue(notifications.isEmpty()); + setApiKeyCreation(keys.get(0).id, timeService.today().minusDays(DEFAULT_API_KEY_ACTIVE_DAYS)); + assertFalse(notifications.isEmpty(), "Expected a notification of key about to expire"); + assertEquals(keys.get(0).id, notifications.get(0).id, "Got notification for the wrong key"); + + // should not be revoked yet + assertFalse(userService.apiKeys().get(0).isRevoked); + assertTrue(UserApiKey. stream("#UserApiKey.expire", timeService.today()) + .anyMatch(k -> k.id == keys.get(0).id)); + + // expire it + setApiKeyCreation(keys.get(0).id, timeService.today().minusDays(DEFAULT_API_KEY_ACTIVE_DAYS + 1)); + assertEquals(2, notifications.toArray().length, "Expected a second notification after key expiration"); + + // should be revoked now + assertTrue(userService.apiKeys().get(0).isRevoked); + assertThrows(ServiceException.class, + () -> userService.renameApiKey(keys.get(0).id, "Rename revoked key should throw")); + }); + } + + @Transactional + void setApiKeyCreation(long keyId, LocalDate creation) { + UserApiKey apiKey = UserApiKey.findById(keyId); + apiKey.access = null; + apiKey.creation = creation; + userService.apiKeyDailyTask(); + } } diff --git a/horreum-client/src/main/java/io/hyperfoil/tools/HorreumClient.java b/horreum-client/src/main/java/io/hyperfoil/tools/HorreumClient.java index 1cadd66e5..8f4fc29f4 100644 --- a/horreum-client/src/main/java/io/hyperfoil/tools/HorreumClient.java +++ b/horreum-client/src/main/java/io/hyperfoil/tools/HorreumClient.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import io.hyperfoil.tools.auth.HorreumApiKeyAuthentication; import io.hyperfoil.tools.auth.KeycloakClientRequestFilter; import io.hyperfoil.tools.horreum.api.client.RunService; import io.hyperfoil.tools.horreum.api.internal.services.ActionService; @@ -96,6 +97,7 @@ public static class Builder { private String horreumUrl; private String horreumUser; private String horreumPassword; + private String horreumApiKey; private SSLContext sslContext; public Builder() { @@ -116,6 +118,11 @@ public Builder horreumPassword(String horreumPassword) { return this; } + public Builder horreumApiKey(String key) { + this.horreumApiKey = key; + return this; + } + public Builder sslContext(SSLContext sslContext) { this.sslContext = sslContext; return this; @@ -167,7 +174,9 @@ public HorreumClient build() throws IllegalStateException { clientBuilder.register(new CustomResteasyJackson2Provider(), 100); clientBuilder.sslContext(sslContext); - if (keycloakConfig.url == null || keycloakConfig.url.isEmpty()) { + if (horreumApiKey != null) { + clientBuilder.register(new HorreumApiKeyAuthentication(horreumApiKey)); + } else if (keycloakConfig.url == null || keycloakConfig.url.isEmpty()) { clientBuilder.register(new BasicAuthentication(horreumUser, horreumPassword)); } else { // register Keycloak Request Filter diff --git a/horreum-client/src/main/java/io/hyperfoil/tools/auth/HorreumApiKeyAuthentication.java b/horreum-client/src/main/java/io/hyperfoil/tools/auth/HorreumApiKeyAuthentication.java new file mode 100644 index 000000000..c308fbc47 --- /dev/null +++ b/horreum-client/src/main/java/io/hyperfoil/tools/auth/HorreumApiKeyAuthentication.java @@ -0,0 +1,30 @@ +package io.hyperfoil.tools.auth; + +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.client.ClientRequestFilter; + +import org.jboss.logging.Logger; + +public class HorreumApiKeyAuthentication implements ClientRequestFilter { + + /** sync with {@link io.hyperfoil.tools.horreum.server.ApiKeyAuthenticationMechanism} */ + public static final String HORREUM_AUTHENTICATION_HEADER = "X-Horreum-API-Key"; + + private static final Logger LOG = Logger.getLogger(HorreumApiKeyAuthentication.class); + + private final String authenticationToken; + + private boolean showAuthMethod = true; + + public HorreumApiKeyAuthentication(String token) { + authenticationToken = token; + } + + public void filter(ClientRequestContext requestContext) { + if (showAuthMethod) { + LOG.infov("Authentication with Horreum API key"); + showAuthMethod = false; + } + requestContext.getHeaders().putSingle(HORREUM_AUTHENTICATION_HEADER, authenticationToken); + } +} diff --git a/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java b/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java index 9ba81f7f6..8ffa00b35 100644 --- a/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java +++ b/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java @@ -1,6 +1,10 @@ package io.hyperfoil.tools.horreum.it; +import static io.hyperfoil.tools.horreum.api.internal.services.UserService.KeyType.USER; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -9,6 +13,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.time.Instant; +import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; @@ -18,6 +23,7 @@ import java.util.stream.Collectors; import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.NotAuthorizedException; import org.junit.jupiter.api.Assertions; @@ -63,6 +69,33 @@ public class HorreumClientIT implements QuarkusTestBeforeTestExecutionCallback, QuarkusTestBeforeClassCallback, QuarkusTestBeforeEachCallback, QuarkusTestAfterEachCallback, QuarkusTestAfterAllCallback { + @org.junit.jupiter.api.Test + public void testApiKeys() { + String keyName = "Test key"; + String theKey = horreumClient.userService.newApiKey(new UserService.ApiKeyRequest(keyName, USER)); + + try (HorreumClient apiClient = new HorreumClient.Builder() + .horreumUrl("http://localhost:".concat(System.getProperty("quarkus.http.test-port"))) + .horreumApiKey(theKey) + .build()) { + + List roles = apiClient.userService.getRoles(); + assertFalse(roles.isEmpty()); + assertTrue(roles.contains(TEST_TEAM.replace("team", Roles.TESTER))); + + UserService.ApiKeyResponse apiKey = horreumClient.userService.apiKeys().get(0); + assertFalse(apiKey.isRevoked); + assertFalse(apiKey.toExpiration < 0); + assertEquals(LocalDate.now(), apiKey.creation); + assertEquals(LocalDate.now(), apiKey.access); + assertEquals(USER, apiKey.type); + + horreumClient.userService.revokeApiKey(apiKey.id); + + assertThrows(NotAuthorizedException.class, apiClient.userService::getRoles); + } + } + @org.junit.jupiter.api.Test public void testAddRunFromData() throws JsonProcessingException { JsonNode payload = new ObjectMapper().readTree(resourceToString("data/config-quickstart.jvm.json")); diff --git a/horreum-web/src/domain/user/ApiKeys.tsx b/horreum-web/src/domain/user/ApiKeys.tsx new file mode 100644 index 000000000..18c56b9e5 --- /dev/null +++ b/horreum-web/src/domain/user/ApiKeys.tsx @@ -0,0 +1,228 @@ +import {useContext, useEffect, useState} from "react" +import { + Button, + ClipboardCopy, + Form, + FormGroup, + HelperText, + HelperTextItem, + Label, + Modal, + TextInput, + Tooltip, +} from "@patternfly/react-core" + +import {ApiKeyResponse, userApi} from "../../api"; +import {AppContext} from "../../context/appContext"; +import {AppContextType} from "../../context/@types/appContextTypes"; +import {ActionsColumn, Table, Tbody, Td, Th, Thead, Tr} from "@patternfly/react-table"; + +export default function ApiKeys() { + const {alerting} = useContext(AppContext) as AppContextType; + + const daysAfter = (other: Date) => Math.floor((Date.now() - other.getTime()) / (24 * 3600 * 1000)) + + const [apiKeys, setApiKeys] = useState([]) + const refreshApiKeys = () => userApi.apiKeys().then( + keys => setApiKeys(keys), + error => alerting.dispatchError(error, "FETCH_API_KEYS", "Failed to fetch API keys for user") + ) + useEffect(() => void refreshApiKeys(), []) + + const [createApiKey, setCreateApiKey] = useState(false) + const [newKeyName, setNewKeyName] = useState() + const [newKeyValue, setNewKeyValue] = useState() + + const [renameKeyId, setRenameKeyId] = useState() + const [renameKeyName, setRenameKeyName] = useState() + + const keyTypeTooltip = (key: ApiKeyResponse) => { + switch (key.type) { + case "USER": + return "This key provides the same set of permissions this user has"; + default: + return "Unknown" + } + } + + const keyCreationTooltip = (key: ApiKeyResponse) => { + if (!key.creation) { + return "" + } else { + const d = daysAfter(key.creation) + if (d == 0) { + return "API key was created today" + } else { + return `API key was created ${d} days ago` + } + } + } + + const keyAccessTooltip = (key: ApiKeyResponse) => { + if (!key.access) { + return "API key has never been used" + } else { + const d = daysAfter(key.access) + if (d == 0) { + return "API key was last used today" + } else if (d == 1) { + return "API key was last used yesterday" + } else { + return `API key was last used ${d} days ago` + } + } + } + + const keyStatus = (key: ApiKeyResponse) => { + const labels = []; + if (key.toExpiration != null && key.toExpiration < 0) { + labels.push() + } else if (key.isRevoked) { + labels.push() + } else { + labels.push() + } + if (key.toExpiration != null && key.toExpiration >= 0) { + if (key.toExpiration < 1) { + labels.push() + } else if (key.toExpiration < 2) { + labels.push() + } else if (key.toExpiration < 7) { + labels.push() + } + } + return labels + } + + const performCreateApiKey = () => { + userApi.newApiKey({ + name: newKeyName, + type: "USER" + }) + .then((tokenValue) => { + setNewKeyValue(tokenValue) + void alerting.dispatchInfo("API_KEY_CREATED", "API key created", "API key was successfully created", 3000) + }) + .catch(error => alerting.dispatchError(error, "API_KEY_NOT_CREATED", "Failed to create new API key")) + .finally(() => setCreateApiKey(false)) + .then(() => void refreshApiKeys()) + } + + const performRenameApiKey = () => { + if (renameKeyId) { + userApi.renameApiKey(renameKeyId, renameKeyName) + .then(() => void alerting.dispatchInfo("API_KEY_RENAMED", "API key renamed", "API key was successfully renamed", 3000)) + .catch(error => alerting.dispatchError(error, "API_KEY_NOT_RENAMED", "Failed to rename API key")) + .finally(() => setRenameKeyId(undefined)) + .then(() => void refreshApiKeys()) + } + } + + return ( + <> + + + + + + + + + + + + {apiKeys.map((key) => ( + + + + + + + + + ))} + + + + + setCreateApiKey(false)} + actions={[ + , + , + ]} + > +
+ + setNewKeyName(val)}/> + +
+
+ setNewKeyValue(undefined)}> + {newKeyValue} + + + This is the only time you'll be able to see the key + + + + setRenameKeyId(undefined)} + actions={[ + , + , + ]}> +
+ + setRenameKeyName(val)}/> + +
+
+ + ) +} diff --git a/horreum-web/src/domain/user/UserSettings.tsx b/horreum-web/src/domain/user/UserSettings.tsx index 58649ae7c..4f7932856 100644 --- a/horreum-web/src/domain/user/UserSettings.tsx +++ b/horreum-web/src/domain/user/UserSettings.tsx @@ -21,8 +21,10 @@ import { Form, FormGroup, PageSection, - Spinner, EmptyStateHeader, - } from "@patternfly/react-core" + Spinner, + EmptyStateHeader, + Tab, +} from "@patternfly/react-core" import { UserIcon } from "@patternfly/react-icons" @@ -33,7 +35,7 @@ import ManagedTeams from "./ManagedTeams" import {AppContext} from "../../context/appContext"; import {AppContextType} from "../../context/@types/appContextTypes"; import ManageMachineAccounts from "./MachineAccounts"; - +import ApiKeys from "./ApiKeys"; export const UserProfileLink = () => { const profile = useSelector(userProfileSelector) @@ -109,7 +111,7 @@ export function UserSettings() { { setModified(false) - alerting.dispatchInfo("SAVE", "Saved!", "User settings succesfully updated!", 3000) + alerting.dispatchInfo("SAVE", "Saved!", "User settings successfully updated!", 3000) }} afterReset={() => setModified(false)} > @@ -158,7 +160,7 @@ export function UserSettings() { /> { @@ -209,6 +211,9 @@ export function UserSettings() { )} + + + {managedTeams.length > 0 ? ( Date: Fri, 27 Sep 2024 14:28:54 +0100 Subject: [PATCH 2/2] Use Instant insteal of LocalDate --- .../api/internal/services/UserService.java | 6 ++-- .../tools/horreum/entity/user/UserApiKey.java | 24 +++++++++------ .../horreum/mapper/UserApiKeyMapper.java | 6 ++-- .../horreum/notification/EmailPlugin.java | 8 ++--- .../horreum/notification/Notification.java | 3 +- .../server/ApiKeyAuthenticationMechanism.java | 4 +-- .../server/ApiKeyIdentityProvider.java | 5 ++-- .../tools/horreum/svc/TimeService.java | 5 ---- .../tools/horreum/svc/UserServiceImpl.java | 11 +++---- .../src/main/resources/db/changeLog.xml | 4 +-- .../templates/api_key_expiration_email.html | 4 +-- .../horreum/svc/UserServiceAbstractTest.java | 29 +++++++++---------- .../tools/CustomResteasyJackson2Provider.java | 4 +++ .../tools/horreum/it/HorreumClientIT.java | 6 ++-- 14 files changed, 60 insertions(+), 59 deletions(-) diff --git a/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java b/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java index 580a0895f..47ac9226b 100644 --- a/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java +++ b/horreum-api/src/main/java/io/hyperfoil/tools/horreum/api/internal/services/UserService.java @@ -1,6 +1,6 @@ package io.hyperfoil.tools.horreum.api.internal.services; -import java.time.LocalDate; +import java.time.Instant; import java.util.List; import java.util.Map; @@ -195,8 +195,8 @@ class ApiKeyResponse { public long id; public String name; public KeyType type; - public LocalDate creation; - public LocalDate access; + public Instant creation; + public Instant access; public boolean isRevoked; public long toExpiration; } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java index d5e860099..3658bd451 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/entity/user/UserApiKey.java @@ -4,7 +4,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.time.LocalDate; +import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Base64; import java.util.Comparator; @@ -33,9 +33,15 @@ @Table(name = "userinfo_apikey") @NamedQueries({ // fetch all keys that expire on a given day - @NamedQuery(name = "UserApiKey.expire", query = "from UserApiKey where not revoked AND (access is null and (creation + active day) = ?1 or (access + active day) = ?1)"), + @NamedQuery(name = "UserApiKey.expire", query = """ + from UserApiKey where not revoked and (access is null and trunc(creation + (active day), day) = trunc(cast(?1 as localdatetime), day) + or trunc(access + (active day), day) = trunc(cast(?1 as localdatetime), day)) + """), // fetch all keys that have gone past their expiration date - @NamedQuery(name = "UserApiKey.pastExpiration", query = "from UserApiKey where not revoked AND (access is null and (creation + active day) < ?1 or (access + active day) < ?1)"), + @NamedQuery(name = "UserApiKey.pastExpiration", query = """ + from UserApiKey where not revoked and (access is null and trunc(creation + (active day), day) < trunc(cast(?1 as localdatetime), day) + or trunc(access + (active day), day) < trunc(cast(?1 as localdatetime), day)) + """), }) public class UserApiKey extends PanacheEntityBase implements Comparable { @@ -61,7 +67,7 @@ public class UserApiKey extends PanacheEntityBase implements Comparable comparing(a -> a.creation).thenComparing(a -> a.id).compare(this, other); + return Comparator. comparing(a -> a.creation).thenComparing(a -> a.id).compare(this, other); } } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java index 40bbf83cf..5a85f8b06 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/mapper/UserApiKeyMapper.java @@ -1,13 +1,13 @@ package io.hyperfoil.tools.horreum.mapper; -import java.time.LocalDate; +import java.time.Instant; import io.hyperfoil.tools.horreum.api.internal.services.UserService; import io.hyperfoil.tools.horreum.entity.user.UserApiKey; public class UserApiKeyMapper { - public static UserApiKey from(UserService.ApiKeyRequest request, LocalDate creation, long valid) { + public static UserApiKey from(UserService.ApiKeyRequest request, Instant creation, long valid) { return new UserApiKey(request.name == null ? "" : request.name, request.type, creation, valid); } @@ -19,7 +19,7 @@ public static UserService.ApiKeyResponse to(UserApiKey key) { response.creation = key.creation; response.access = key.access; response.isRevoked = key.revoked; - response.toExpiration = key.toExpiration(LocalDate.now()); + response.toExpiration = key.toExpiration(Instant.now()); return response; } } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java index 68a273ee5..70f672927 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/EmailPlugin.java @@ -7,7 +7,7 @@ import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; -import java.time.LocalDate; +import java.time.temporal.ChronoUnit; import java.util.Date; import jakarta.enterprise.context.ApplicationScoped; @@ -156,7 +156,7 @@ public void notifyExpectedRun(String testName, int testId, long before, String e } @Override - public void notifyApiKeyExpiration(String keyName, LocalDate creation, LocalDate lastAccess, long toExpiration, + public void notifyApiKeyExpiration(String keyName, Instant creation, Instant lastAccess, long toExpiration, long active) { String subject = String.format("%s API key \"%s\" %s", subjectPrefix, keyName, toExpiration == -1 ? "EXPIRED" : "about to expire"); @@ -164,8 +164,8 @@ public void notifyApiKeyExpiration(String keyName, LocalDate creation, LocalDate .data("baseUrl", baseUrl) .data("username", username) .data("keyName", keyName) - .data("creation", creation) - .data("lastAccess", lastAccess) + .data("creation", creation.truncatedTo(ChronoUnit.DAYS)) + .data("lastAccess", lastAccess.truncatedTo(ChronoUnit.DAYS)) .data("expiration", toExpiration) .data("active", active) .render(); diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java index 5a1d03aec..a530c2ac1 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/notification/Notification.java @@ -1,7 +1,6 @@ package io.hyperfoil.tools.horreum.notification; import java.time.Instant; -import java.time.LocalDate; import io.hyperfoil.tools.horreum.events.DatasetChanges; import io.hyperfoil.tools.horreum.svc.MissingValuesEvent; @@ -24,7 +23,7 @@ public abstract void notifyMissingDataset(String testName, int testId, String ru public abstract void notifyExpectedRun(String testName, int testId, long before, String expectedBy, String backlink); - public abstract void notifyApiKeyExpiration(String keyName, LocalDate creation, LocalDate lastAccess, long toExpiration, + public abstract void notifyApiKeyExpiration(String keyName, Instant creation, Instant lastAccess, long toExpiration, long active); } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java index d5628ba06..91f997a18 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyAuthenticationMechanism.java @@ -30,7 +30,7 @@ public class ApiKeyAuthenticationMechanism implements HttpAuthenticationMechanis public Uni authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { String headerValue = context.request().headers().get(HORREUM_API_KEY_HEADER); return headerValue == null ? Uni.createFrom().nullItem() - : identityProviderManager.authenticate(new Request(headerValue)); + : identityProviderManager.authenticate(new ApiKeyAuthenticationMechanism.Request(headerValue)); } @Override @@ -40,7 +40,7 @@ public Uni getChallenge(RoutingContext context) { @Override public Set> getCredentialTypes() { - return Collections.singleton(Request.class); + return Collections.singleton(ApiKeyAuthenticationMechanism.Request.class); } @Override diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java index 0497a2884..c6dcf5674 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/server/ApiKeyIdentityProvider.java @@ -1,13 +1,12 @@ package io.hyperfoil.tools.horreum.server; -import io.quarkus.logging.Log; -import io.quarkus.security.AuthenticationFailedException; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.transaction.Transactional; import io.hyperfoil.tools.horreum.entity.user.UserApiKey; import io.hyperfoil.tools.horreum.svc.TimeService; +import io.quarkus.logging.Log; import io.quarkus.security.identity.AuthenticationRequestContext; import io.quarkus.security.identity.IdentityProvider; import io.quarkus.security.identity.SecurityIdentity; @@ -43,7 +42,7 @@ SecurityIdentity identityFromKey(String key) { Log.debugv("Authentication of user {0} with key \"{1}\" {2}", userKey.user.username, userKey.name, key); // update last access - userKey.access = timeService.today(); + userKey.access = timeService.now(); // create identity with just the principal, roles will be populated in RolesAugmentor return QuarkusSecurityIdentity.builder().setPrincipal(new QuarkusPrincipal(userKey.user.username)).build(); diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java index 2cb3c0038..215a5228c 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/TimeService.java @@ -1,7 +1,6 @@ package io.hyperfoil.tools.horreum.svc; import java.time.Instant; -import java.time.LocalDate; import jakarta.enterprise.context.ApplicationScoped; @@ -13,8 +12,4 @@ public class TimeService { public Instant now() { return Instant.now(); } - - public LocalDate today() { - return LocalDate.now(); - } } diff --git a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java index 116b3de24..65c0c5bf3 100644 --- a/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java +++ b/horreum-backend/src/main/java/io/hyperfoil/tools/horreum/svc/UserServiceImpl.java @@ -4,12 +4,12 @@ import static java.util.Collections.emptyList; import java.security.SecureRandom; +import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; -import io.hyperfoil.tools.horreum.mapper.UserApiKeyMapper; import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.RolesAllowed; import jakarta.enterprise.context.ApplicationScoped; @@ -20,6 +20,7 @@ import io.hyperfoil.tools.horreum.api.internal.services.UserService; import io.hyperfoil.tools.horreum.entity.user.UserApiKey; import io.hyperfoil.tools.horreum.entity.user.UserInfo; +import io.hyperfoil.tools.horreum.mapper.UserApiKeyMapper; import io.hyperfoil.tools.horreum.server.WithRoles; import io.hyperfoil.tools.horreum.svc.user.UserBackEnd; import io.quarkus.logging.Log; @@ -300,7 +301,7 @@ public String newApiKey(ApiKeyRequest request) { validateApiKeyName(request.name == null ? "" : request.name); UserInfo userInfo = currentUser(); - UserApiKey newKey = UserApiKeyMapper.from(request, timeService.today(), DEFAULT_API_KEY_ACTIVE_DAYS); + UserApiKey newKey = UserApiKeyMapper.from(request, timeService.now(), DEFAULT_API_KEY_ACTIVE_DAYS); newKey.user = userInfo; userInfo.apiKeys.add(newKey); newKey.persist(); @@ -315,7 +316,7 @@ public String newApiKey(ApiKeyRequest request) { @Override public List apiKeys() { return currentUser().apiKeys.stream() - .filter(t -> !t.isArchived(timeService.today())) + .filter(t -> !t.isArchived(timeService.now())) .sorted() .map(UserApiKeyMapper::to) .toList(); @@ -353,11 +354,11 @@ public void revokeApiKey(long keyId) { public void apiKeyDailyTask() { // notifications of keys expired and about to expire -- hardcoded to send multiple notices in the week prior to expiration for (long toExpiration : List.of(7, 2, 1, 0, -1)) { - UserApiKey. stream("#UserApiKey.expire", timeService.today().plusDays(toExpiration)) + UserApiKey. stream("#UserApiKey.expire", timeService.now().plus(toExpiration, ChronoUnit.DAYS)) .forEach(key -> notificationServiceimpl.notifyApiKeyExpiration(key, toExpiration)); } // revoke expired keys -- could be done directly in the DB but iterate instead to be able to log - UserApiKey. stream("#UserApiKey.pastExpiration", timeService.today()).forEach(key -> { + UserApiKey. stream("#UserApiKey.pastExpiration", timeService.now()).forEach(key -> { Log.debugv("Idle API key \"{0}\" revoked", key.name); key.revoked = true; }); diff --git a/horreum-backend/src/main/resources/db/changeLog.xml b/horreum-backend/src/main/resources/db/changeLog.xml index 1c428818d..995d0bd1c 100644 --- a/horreum-backend/src/main/resources/db/changeLog.xml +++ b/horreum-backend/src/main/resources/db/changeLog.xml @@ -4580,8 +4580,8 @@ - - + + diff --git a/horreum-backend/src/main/resources/templates/api_key_expiration_email.html b/horreum-backend/src/main/resources/templates/api_key_expiration_email.html index 218c535d7..b3079e980 100644 --- a/horreum-backend/src/main/resources/templates/api_key_expiration_email.html +++ b/horreum-backend/src/main/resources/templates/api_key_expiration_email.html @@ -1,5 +1,5 @@

Hello {username},

-

The API key "{keyName}" created on {creation} +

The API key "{keyName}" created on {creation.format('d MMM uuuu')} {#when expiration} {#is < 0} HAS EXPIRED. {#is < 1} expires today. @@ -7,6 +7,6 @@ {#else} expires in {expiration} days. {/when}

-

The key was {#if lastAccess == null}never used{#else}last used on {lastAccess}{/if}.

+

The key was {#if lastAccess == null}never used{#else}last used on {lastAccess.format('d MMM uuuu')}{/if}.

Remember that this key is automatically revoked if not used for {active} days.

Horreum Alerting diff --git a/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java b/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java index f6b6035d5..76c079b67 100644 --- a/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java +++ b/horreum-backend/src/test/java/io/hyperfoil/tools/horreum/svc/UserServiceAbstractTest.java @@ -11,7 +11,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.time.LocalDate; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -24,7 +25,6 @@ import jakarta.transaction.Transactional; import jakarta.ws.rs.core.Response; -import org.jboss.logging.Logger; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -48,8 +48,6 @@ */ public abstract class UserServiceAbstractTest { - private static final Logger LOG = Logger.getLogger(UserServiceAbstractTest.class); - // the name of the default keycloak user with "admin" role (see io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager#createUsers) private static final String KEYCLOAK_ADMIN = "admin"; @@ -95,7 +93,6 @@ void administratorsTest() { // create the admin user and give it the admin role try { userService.createUser(adminUser); - LOG.infov("Created user {0}", adminUserName); } catch (ServiceException se) { // in the keycloak implementation this admin user already exists, and therefore the exception is expected assertEquals(se.getMessage(), "User exists with same username"); @@ -581,13 +578,12 @@ void apiKeys() { overrideTestSecurity(apiUser, Set.of(Roles.MANAGER, testTeam.substring(0, testTeam.length() - 4) + Roles.MANAGER), () -> { // notification mock - NotificationServiceImpl notificationService = Mockito.mock(NotificationServiceImpl.class); + NotificationServiceImpl notificationServiceMock = Mockito.mock(NotificationServiceImpl.class); List notifications = Collections.synchronizedList(new ArrayList<>()); - Mockito.doAnswer(invocation -> { - notifications.add(invocation.getArgument(0)); - return null; - }).when(notificationService).notifyApiKeyExpiration(Mockito.any(), Mockito.anyLong()); - QuarkusMock.installMockForType(notificationService, NotificationServiceImpl.class); + Mockito.doAnswer(invocation -> notifications.add(invocation.getArgument(0))) + .when(notificationServiceMock) + .notifyApiKeyExpiration(Mockito.any(), Mockito.anyLong()); + QuarkusMock.installMockForType(notificationServiceMock, NotificationServiceImpl.class); // empty state assertTrue(userService.apiKeys().isEmpty()); @@ -612,22 +608,23 @@ void apiKeys() { assertTrue( UserApiKey . stream("#UserApiKey.expire", - timeService.today().plusDays(DEFAULT_API_KEY_ACTIVE_DAYS)) + timeService.now().plus(DEFAULT_API_KEY_ACTIVE_DAYS, ChronoUnit.DAYS)) .anyMatch(k -> k.id == keys.get(0).id)); // about to expire assertTrue(notifications.isEmpty()); - setApiKeyCreation(keys.get(0).id, timeService.today().minusDays(DEFAULT_API_KEY_ACTIVE_DAYS)); + setApiKeyCreation(keys.get(0).id, timeService.now().minus(DEFAULT_API_KEY_ACTIVE_DAYS, ChronoUnit.DAYS)); assertFalse(notifications.isEmpty(), "Expected a notification of key about to expire"); assertEquals(keys.get(0).id, notifications.get(0).id, "Got notification for the wrong key"); // should not be revoked yet assertFalse(userService.apiKeys().get(0).isRevoked); - assertTrue(UserApiKey. stream("#UserApiKey.expire", timeService.today()) + assertTrue(UserApiKey. stream("#UserApiKey.expire", timeService.now()) .anyMatch(k -> k.id == keys.get(0).id)); // expire it - setApiKeyCreation(keys.get(0).id, timeService.today().minusDays(DEFAULT_API_KEY_ACTIVE_DAYS + 1)); + setApiKeyCreation(keys.get(0).id, + timeService.now().minus(DEFAULT_API_KEY_ACTIVE_DAYS + 1, ChronoUnit.DAYS)); assertEquals(2, notifications.toArray().length, "Expected a second notification after key expiration"); // should be revoked now @@ -638,7 +635,7 @@ void apiKeys() { } @Transactional - void setApiKeyCreation(long keyId, LocalDate creation) { + void setApiKeyCreation(long keyId, Instant creation) { UserApiKey apiKey = UserApiKey.findById(keyId); apiKey.access = null; apiKey.creation = creation; diff --git a/horreum-client/src/main/java/io/hyperfoil/tools/CustomResteasyJackson2Provider.java b/horreum-client/src/main/java/io/hyperfoil/tools/CustomResteasyJackson2Provider.java index 751ced068..3aa780bb8 100644 --- a/horreum-client/src/main/java/io/hyperfoil/tools/CustomResteasyJackson2Provider.java +++ b/horreum-client/src/main/java/io/hyperfoil/tools/CustomResteasyJackson2Provider.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class CustomResteasyJackson2Provider extends ResteasyJackson2Provider { @@ -11,7 +12,10 @@ public CustomResteasyJackson2Provider() { ObjectMapper customJsonMapper = new ObjectMapper(); // This is useful if the client is old and we have added some new properties customJsonMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + // Match io.hyperfoil.tools.horreum.converte.JavaTimeCustomizer customJsonMapper.registerModule(new JavaTimeModule()); + customJsonMapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS); + customJsonMapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS); this.setMapper(customJsonMapper); } } diff --git a/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java b/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java index 8ffa00b35..1a263625b 100644 --- a/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java +++ b/horreum-integration-tests/src/test/java/io/hyperfoil/tools/horreum/it/HorreumClientIT.java @@ -13,7 +13,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.time.Instant; -import java.time.LocalDate; +import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; @@ -86,8 +86,8 @@ public void testApiKeys() { UserService.ApiKeyResponse apiKey = horreumClient.userService.apiKeys().get(0); assertFalse(apiKey.isRevoked); assertFalse(apiKey.toExpiration < 0); - assertEquals(LocalDate.now(), apiKey.creation); - assertEquals(LocalDate.now(), apiKey.access); + assertEquals(Instant.now().truncatedTo(ChronoUnit.DAYS), apiKey.creation.truncatedTo(ChronoUnit.DAYS)); + assertEquals(Instant.now().truncatedTo(ChronoUnit.DAYS), apiKey.access.truncatedTo(ChronoUnit.DAYS)); assertEquals(USER, apiKey.type); horreumClient.userService.revokeApiKey(apiKey.id);