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

SMQ-2626 - Add audit logs service for monitoring state changes in entities #2755

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions auditlogs/api/decode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package api

import (
"context"
"net/http"

api "github.com/absmach/supermq/api/http"
apiutil "github.com/absmach/supermq/api/http/util"
"github.com/absmach/supermq/auditlogs"
"github.com/go-chi/chi/v5"
)

const (
requestIDKey = "request_id"
actorIDKey = "actor_id"
entityTypeKey = "entity_type"
entityIDKey = "entity_id"
)

func decodeRetrieveAuditLogReq(_ context.Context, r *http.Request) (interface{}, error) {
req := retriveAuditLogReq{
id: chi.URLParam(r, "auditLogID"),
}

return req, nil
}

func decodeRetrieveAllAuditLogsReq(_ context.Context, r *http.Request) (interface{}, error) {
order, err := apiutil.ReadStringQuery(r, api.OrderKey, "")
if err != nil {
return retrieveAllAuditLogsReq{}, err
}

dir, err := apiutil.ReadStringQuery(r, api.DirKey, "")
if err != nil {
return retrieveAllAuditLogsReq{}, err
}

requestID, err := apiutil.ReadStringQuery(r, requestIDKey, "")
if err != nil {
return retrieveAllAuditLogsReq{}, err
}

actorID, err := apiutil.ReadStringQuery(r, actorIDKey, "")
if err != nil {
return retrieveAllAuditLogsReq{}, err
}

entityType, err := apiutil.ReadStringQuery(r, entityTypeKey, "")
if err != nil {
return retrieveAllAuditLogsReq{}, err
}

entityID, err := apiutil.ReadStringQuery(r, entityIDKey, "")
if err != nil {
return retrieveAllAuditLogsReq{}, err
}

req := retrieveAllAuditLogsReq{
Page: auditlogs.Page{
Order: order,
Dir: dir,
RequestID: requestID,
ActorID: actorID,
EntityType: entityType,
EntityID: entityID,
},
}

return req, nil

}

Check failure on line 75 in auditlogs/api/decode.go

View workflow job for this annotation

GitHub Actions / Lint and Build

unnecessary trailing newline (whitespace)
50 changes: 50 additions & 0 deletions auditlogs/api/endpoints.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package api

import (
"context"

"github.com/absmach/supermq/auditlogs"
api "github.com/absmach/supermq/api/http"
"github.com/absmach/supermq/pkg/authn"
"github.com/go-kit/kit/endpoint"
svcerr "github.com/absmach/supermq/pkg/errors/service"
)

func retrieveAuditLogEndpoint(svc auditlogs.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(retriveAuditLogReq)

session, ok := ctx.Value(api.SessionKey).(authn.Session)
if !ok {
return nil, svcerr.ErrAuthentication
}

log, err := svc.RetrieveByID(ctx, session, req.id)
if err != nil {
return nil, err
}

return retrieveAuditLogRes{log}, nil
}
}

func retrieveAllAuditLogsEndpoint(svc auditlogs.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(retrieveAllAuditLogsReq)

session, ok := ctx.Value(api.SessionKey).(authn.Session)
if !ok {
return nil, svcerr.ErrAuthentication
}

page, err := svc.RetrieveAll(ctx, session, req.Page)
if err != nil {
return nil, err
}

return retrieveAllAuditLogsRes{page}, nil
}
}
14 changes: 14 additions & 0 deletions auditlogs/api/requests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package api

import "github.com/absmach/supermq/auditlogs"

type retriveAuditLogReq struct {
id string
}

type retrieveAllAuditLogsReq struct {
auditlogs.Page
}
42 changes: 42 additions & 0 deletions auditlogs/api/responses.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package api

import (
"net/http"

"github.com/absmach/supermq/auditlogs"
)

type retrieveAuditLogRes struct {
auditlogs.AuditLog
}

func (res retrieveAuditLogRes) Code() int {
return http.StatusOK
}

func (res retrieveAuditLogRes) Headers() map[string]string {
return map[string]string{}
}

func (res retrieveAuditLogRes) Empty() bool {
return false
}

type retrieveAllAuditLogsRes struct {
auditlogs.AuditLogPage
}

func (res retrieveAllAuditLogsRes) Code() int {
return http.StatusOK
}

func (res retrieveAllAuditLogsRes) Headers() map[string]string {
return map[string]string{}
}

func (res retrieveAllAuditLogsRes) Empty() bool {
return false
}
49 changes: 49 additions & 0 deletions auditlogs/api/transport.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package api

import (
"log/slog"

"github.com/absmach/supermq"
"github.com/absmach/supermq/auditlogs"
api "github.com/absmach/supermq/api/http"
apiutil "github.com/absmach/supermq/api/http/util"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
smqauthn "github.com/absmach/supermq/pkg/authn"
kithttp "github.com/go-kit/kit/transport/http"
)

// MakeHandler returns a HTTP handler for Channels API endpoints.
func MakeHandler(svc auditlogs.Service, authn smqauthn.Authentication, mux *chi.Mux, logger *slog.Logger, instanceID string, idp supermq.IDProvider) *chi.Mux {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, api.EncodeError)),
}

mux.Route("/auditlogs", func(r chi.Router) {
r.Use(api.AuthenticateMiddleware(authn, false))
r.Use(api.RequestIDMiddleware(idp))

r.Get("/{id}", otelhttp.NewHandler(kithttp.NewServer(
retrieveAuditLogEndpoint(svc),
decodeRetrieveAuditLogReq,
api.EncodeResponse,
opts...,
), "retrieve_audit_log").ServeHTTP)

r.Get("/", otelhttp.NewHandler(kithttp.NewServer(
retrieveAllAuditLogsEndpoint(svc),
decodeRetrieveAllAuditLogsReq,
api.EncodeResponse,
opts...,
), "retrieve_all_audit_logs").ServeHTTP)
})

mux.Get("health", supermq.Health("auditlogs", instanceID))
mux.Handle("/metrics", promhttp.Handler())

return mux
}
71 changes: 71 additions & 0 deletions auditlogs/auditlogs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package auditlogs

import (
"context"
"time"

"github.com/absmach/supermq/pkg/authn"
)

type AuditLog struct {
ID string `json:"id"`
RequestID string `json:"request_id"`
DomainID string `json:"domain_id"`
OccurredAt time.Time `json:"occured_at"`

Check failure on line 17 in auditlogs/auditlogs.go

View workflow job for this annotation

GitHub Actions / Lint and Build

`occured` is a misspelling of `occurred` (misspell)
ActorID string `json:"actor_id"`
CurrentState EntityState `json:"current_state"`
PreviousState EntityState `json:"previous_state"`
StateAttributes Metadata `json:"state_attributes"`
EntityID string `json:"entity_id"`
EntityType EntityType `json:"entity_type"`
Metadata Metadata `json:"metadata"`
}

type AuditLogPage struct {
Page
Logs []AuditLog `json:"logs"`
}

type Page struct {
Total uint64 `json:"total"`
Offset uint64 `json:"offset"`
Limit uint64 `json:"limit"`
Order string `json:"order,omitempty"`
Dir string `json:"dir,omitempty"`
ID string `json:"id,omitempty"`
RequestID string `json:"request_id,omitempty"`
OccuredAt string `json:"occured_at,omitempty"`

Check failure on line 40 in auditlogs/auditlogs.go

View workflow job for this annotation

GitHub Actions / Lint and Build

`occured` is a misspelling of `occurred` (misspell)
ActorID string `json:"actor_id,omitempty"`
EntityType string `json:"entity_type,omitempty"`
EntityID string `json:"entity_id,omitempty"`
}

type Metadata map[string]any


//go:generate mockery --name Repository --output=./mocks --filename repository.go --quiet --note "Copyright (c) Abstract Machines"
type Repository interface {
// Save saves audit log.
Save(ctx context.Context, log AuditLog) error

// RetrieveByID retrieves audit log by its unique ID.
RetrieveByID(ctx context.Context, id string) (AuditLog, error)

// RetrieveAll retrieves all audit logs.
RetrieveAll(ctx context.Context, pm Page) (AuditLogPage, error)
}

//go:generate mockery --name Service --output=./mocks --filename service.go --quiet --note "Copyright (c) Abstract Machines"
type Service interface {
// Save saves audit log.
Save(ctx context.Context, log AuditLog) error

// RetrieveByID retrieves audit log by its unique ID.
RetrieveByID(ctx context.Context, session authn.Session, id string) (AuditLog, error)

// RetrieveAll retrieves all audit logs.
RetrieveAll(ctx context.Context, session authn.Session, pm Page) (AuditLogPage, error)
}
Loading
Loading