Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added REST API logging #476

Merged
merged 3 commits into from
Aug 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* ComiXed - A digital comic book library management application.
* Copyright (C) 2020, The ComiXed Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

package org.comixedproject.model.auditlog;

import java.util.Date;
import javax.persistence.*;
import lombok.Getter;
import lombok.Setter;

/**
* <code>RestAuditLogEntry</code> represents a single entry in the REST API audit log table.
*
* @author Darryl L. Pierce
*/
@Entity
@Table(name = "rest_audit_log")
public class RestAuditLogEntry {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter
private Long id;

@Column(name = "remote_ip", nullable = false, updatable = false)
@Getter
@Setter
private String remoteIp;

@Column(name = "url", nullable = false, updatable = false)
@Getter
@Setter
private String url;

@Column(name = "method", nullable = false, updatable = false)
@Getter
@Setter
private String method;

@Column(name = "request_content", nullable = true, updatable = false)
@Lob
@Getter
@Setter
private String requestContent;

@Column(name = "response_content", nullable = true, updatable = false)
@Lob
@Getter
@Setter
private String responseContent;

@Column(name = "email", nullable = true, updatable = false)
@Getter
@Setter
private String email;

@Column(name = "start_time", nullable = false, updatable = false)
@Getter
@Setter
private Date startTime = new Date();

@Column(name = "end_time", nullable = false, updatable = false)
@Getter
@Setter
private Date endTime = new Date();

@Column(name = "successful", nullable = false, updatable = false)
@Getter
@Setter
private Boolean successful;

@Column(name = "exception", nullable = true, updatable = false)
@Lob
@Getter
@Setter
private String exception;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="006_issue-474_add_rest_audit_log.xml"
author="mcpierce">
<createTable tableName="rest_audit_log">
<column name="id"
type="bigint">
<constraints nullable="false"
unique="true"
primaryKey="true"/>
</column>
<column name="remote_ip"
type="varchar(15)">
<constraints nullable="false"/>
</column>
<column name="url"
type="varchar(256)">
<constraints nullable="false"/>
</column>
<column name="method"
type="varchar(32)">
<constraints nullable="false"/>
</column>
<column name="email"
type="varchar(256)">
<constraints nullable="false"/>
</column>
<column name="start_time"
type="timestamp">
<constraints nullable="false"/>
</column>
<column name="end_time"
type="timestamp"
defaultValueComputed="NOW()">
<constraints nullable="false"/>
</column>
<column name="successful"
type="boolean">
<constraints nullable="false"/>
</column>
<column name="request_content"
type="clob">
<constraints nullable="true"/>
</column>
<column name="response_content"
type="clob">
<constraints nullable="true"/>
</column>
<column name="exception"
type="clob">
<constraints nullable="true"/>
</column>
</createTable>

<addAutoIncrement tableName="rest_audit_log"
columnName="id"
columnDataType="bigint"
incrementBy="1"
startWith="1"/>

<createIndex tableName="rest_audit_log"
indexName="rest_audit_log_start_time_idx">
<column name="start_time"/>
</createIndex>

<createIndex tableName="rest_audit_log"
indexName="rest_audit_log_successful_idx">
<column name="successful"/>
</createIndex>
</changeSet>
</databaseChangeLog>
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@
<include file="/db/migrations/0.7.0/003_issue-301_add_scraping_cache_table.xml"/>
<include file="/db/migrations/0.7.0/004_issue-204_add_task_audit_log.xml"/>
<include file="/db/migrations/0.7.0/005_issue-471_add_exception_field_to_task_audit_log.xml"/>
<include file="/db/migrations/0.7.0/006_issue-474_add_rest_audit_log.xml"/>

</databaseChangeLog>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* ComiXed - A digital comic book library management application.
* Copyright (C) 2020, The ComiXed Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

package org.comixedproject.repositories.auditlog;

import org.comixedproject.model.auditlog.RestAuditLogEntry;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
* <code>RestAuditLogRepository</code> manages persisted instances of {@link RestAuditLogEntry}.
*
* @author Darryl L. Pierce
*/
@Repository
public interface RestAuditLogRepository extends JpaRepository<RestAuditLogEntry, Long> {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.comixedproject.auditlog;

/**
* <code>AuditableEndpoint</code> is used to indicate that a method is to be audited whenever it's
* invoked. The method <b>must</b> return a {@link ApiResponse} object.
*
* @author Darryl L. Pierce
*/
public @interface AuditableEndpoint {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* ComiXed - A digital comic book library management application.
* Copyright (C) 2020, The ComiXed Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

package org.comixedproject.auditlog;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.comixedproject.model.auditlog.RestAuditLogEntry;
import org.comixedproject.net.ApiResponse;
import org.comixedproject.service.auditlog.RestAuditLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper;

/**
* <code>AuditableEndpointAspect</code> manages aspects relating to the REST APIs.
*
* @author Darryl L. Pierce
*/
@Aspect
@Configuration
@Log4j2
public class AuditableEndpointAspect {
@Autowired private RestAuditLogService restAuditLogService;
@Autowired private ObjectMapper objectMapper;

/**
* Wraps REST API calls and records the results.
*
* @param joinPoint the join point.
* @return the response object
*/
@Around("@annotation(org.comixedproject.auditlog.AuditableEndpoint)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Throwable error = null;
Object response = null;

final Date started = new Date();
try {
response = joinPoint.proceed();
} catch (Throwable throwable) {
error = throwable;
}
final Date ended = new Date();
if (response instanceof ApiResponse<?>) {
final ApiResponse<?> apiResponse = (ApiResponse<?>) response;
final RestAuditLogEntry entry = new RestAuditLogEntry();
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

if (request.getUserPrincipal() != null) {
entry.setEmail(request.getUserPrincipal().getName());
} else {
entry.setException("anonymous");
}
entry.setRemoteIp(request.getRemoteAddr());
entry.setUrl(request.getRequestURI());
entry.setMethod(request.getMethod());
entry.setRequestContent(
new String(((ContentCachingRequestWrapper) request).getContentAsByteArray()));
if (apiResponse.getResult() != null) {
entry.setResponseContent(this.objectMapper.writeValueAsString(apiResponse.getResult()));
}
entry.setStartTime(started);
entry.setEndTime(ended);
entry.setSuccessful(apiResponse.isSuccess());
entry.setException(apiResponse.getError());
if (apiResponse.getThrowable() != null) {
log.debug("Storing stacktrace");
final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter);
apiResponse.getThrowable().printStackTrace(printWriter);
entry.setException(stringWriter.toString());
}

this.restAuditLogService.save(entry);
}
if (error != null) throw error;
return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,19 @@
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

package org.comixedproject.web.authentication;
package org.comixedproject.authentication;

public class AuthToken {
private String token;
private String email;

public AuthToken() {}

public AuthToken(String token, String email) {
this.token = token;
this.email = email;
}

public AuthToken(String token) {
this.token = token;
}

public String getToken() {
return token;
}
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

public void setToken(String token) {
this.token = token;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
/**
* <code>AuthToken</code> represents the token used by authentication.
*
* @author Darryl L. Pierce
*/
@AllArgsConstructor
public class AuthToken {
@Getter @Setter private String token;
@Getter @Setter private String email;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

package org.comixedproject.web.authentication;
package org.comixedproject.authentication;

/**
* <code>AuthenticationConstants</code> is a placeholder for constant values used in the
Expand Down