Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Audit date filter/kira pilot #4845

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

Merged
merged 11 commits into from
Nov 3, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion coderd/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ func (api *API) auditLogs(rw http.ResponseWriter, r *http.Request) {
Action: filter.Action,
Username: filter.Username,
Email: filter.Email,
DateFrom: filter.DateFrom,
DateTo: filter.DateTo,
})
if err != nil {
httpapi.InternalServerError(rw, err)
Expand Down Expand Up @@ -84,6 +86,8 @@ func (api *API) auditLogCount(rw http.ResponseWriter, r *http.Request) {
Action: filter.Action,
Username: filter.Username,
Email: filter.Email,
DateFrom: filter.DateFrom,
DateTo: filter.DateTo,
})
if err != nil {
httpapi.InternalServerError(rw, err)
Expand Down Expand Up @@ -142,10 +146,13 @@ func (api *API) generateFakeAuditLog(rw http.ResponseWriter, r *http.Request) {
if params.ResourceID == uuid.Nil {
params.ResourceID = uuid.New()
}
if params.Time.IsZero() {
params.Time = time.Now()
}

_, err = api.Database.InsertAuditLog(ctx, database.InsertAuditLogParams{
ID: uuid.New(),
Time: time.Now(),
Time: params.Time,
UserID: user.ID,
Ip: ipNet,
UserAgent: r.UserAgent(),
Expand Down Expand Up @@ -273,12 +280,33 @@ func auditSearchQuery(query string) (database.GetAuditLogsOffsetParams, []coders
// Using the query param parser here just returns consistent errors with
// other parsing.
parser := httpapi.NewQueryParamParser()
const layout = "2006-01-02"

var (
dateFromString = parser.String(searchParams, "", "date_from")
dateToString = parser.String(searchParams, "", "date_to")
parsedDateFrom, _ = time.Parse(layout, dateFromString)
parsedDateTo, _ = time.Parse(layout, dateToString)
)

if dateToString != "" {
parsedDateTo = parsedDateTo.Add(23*time.Hour + 59*time.Minute + 59*time.Second) // parsedDateTo goes to 23:59
}

if dateToString != "" && parsedDateTo.Before(parsedDateFrom) {
return database.GetAuditLogsOffsetParams{}, []codersdk.ValidationError{
{Field: "q", Detail: fmt.Sprintf("DateTo value %q cannot be before than DateFrom", parsedDateTo)},
}
}

filter := database.GetAuditLogsOffsetParams{
ResourceType: resourceTypeFromString(parser.String(searchParams, "", "resource_type")),
ResourceID: parser.UUID(searchParams, uuid.Nil, "resource_id"),
Action: actionFromString(parser.String(searchParams, "", "action")),
Username: parser.String(searchParams, "", "username"),
Email: parser.String(searchParams, "", "email"),
DateFrom: parsedDateFrom,
DateTo: parsedDateTo,
}

return filter, parser.Errors
Expand Down
19 changes: 19 additions & 0 deletions coderd/audit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package coderd_test
import (
"context"
"testing"
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -54,12 +55,14 @@ func TestAuditLogsFilter(t *testing.T) {
err := client.CreateTestAuditLog(ctx, codersdk.CreateTestAuditLogRequest{
Action: codersdk.AuditActionCreate,
ResourceType: codersdk.ResourceTypeTemplate,
Time: time.Date(2022, 8, 15, 14, 30, 45, 100, time.UTC), // 2022-8-15 14:30:45
})
require.NoError(t, err)
err = client.CreateTestAuditLog(ctx, codersdk.CreateTestAuditLogRequest{
Action: codersdk.AuditActionCreate,
ResourceType: codersdk.ResourceTypeUser,
ResourceID: userResourceID,
Time: time.Date(2022, 8, 16, 14, 30, 45, 100, time.UTC), // 2022-8-16 14:30:45
})
require.NoError(t, err)

Expand All @@ -68,6 +71,7 @@ func TestAuditLogsFilter(t *testing.T) {
Action: codersdk.AuditActionDelete,
ResourceType: codersdk.ResourceTypeUser,
ResourceID: userResourceID,
Time: time.Date(2022, 8, 15, 14, 30, 45, 100, time.UTC), // 2022-8-15 14:30:45
})
require.NoError(t, err)

Expand Down Expand Up @@ -127,6 +131,21 @@ func TestAuditLogsFilter(t *testing.T) {
SearchQuery: "action:invalid",
ExpectedResult: 3,
},
{
Name: "FilterOnCreateSingleDay",
SearchQuery: "action:create date_from:2022-08-15 date_to:2022-08-15",
ExpectedResult: 1,
},
{
Name: "FilterOnCreateDateFrom",
SearchQuery: "action:create date_from:2022-08-15",
ExpectedResult: 2,
},
{
Name: "FilterOnCreateDateTo",
SearchQuery: "action:create date_to:2022-08-15",
ExpectedResult: 1,
},
}

for _, testCase := range testCases {
Expand Down
20 changes: 20 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -2995,6 +2995,16 @@ func (q *fakeQuerier) GetAuditLogsOffset(ctx context.Context, arg database.GetAu
continue
}
}
if !arg.DateFrom.IsZero() {
if alog.Time.Before(arg.DateFrom) {
continue
}
}
if !arg.DateTo.IsZero() {
if alog.Time.After(arg.DateTo) {
continue
}
}

user, err := q.GetUserByID(ctx, alog.UserID)
userValid := err == nil
Expand Down Expand Up @@ -3057,6 +3067,16 @@ func (q *fakeQuerier) GetAuditLogCount(_ context.Context, arg database.GetAuditL
continue
}
}
if !arg.DateFrom.IsZero() {
if alog.Time.Before(arg.DateFrom) {
continue
}
}
if !arg.DateTo.IsZero() {
if alog.Time.After(arg.DateTo) {
continue
}
}

logs = append(logs, alog)
}
Expand Down
32 changes: 32 additions & 0 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions coderd/database/queries/auditlogs.sql
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ WHERE
users.email = @email
ELSE true
END
-- Filter by date_from
AND CASE
WHEN @date_from :: timestamp with time zone != '0001-01-01 00:00:00' THEN
"time" >= @date_from
ELSE true
END
-- Filter by date_to
AND CASE
WHEN @date_to :: timestamp with time zone != '0001-01-01 00:00:00' THEN
"time" <= @date_to
ELSE true
END
ORDER BY
"time" DESC
LIMIT
Expand Down Expand Up @@ -98,6 +110,18 @@ WHERE
WHEN @email :: text != '' THEN
user_id = (SELECT id from users WHERE users.email = @email )
ELSE true
END
-- Filter by date_from
AND CASE
WHEN @date_from :: timestamp with time zone != '0001-01-01 00:00:00' THEN
"time" >= @date_from
ELSE true
END
-- Filter by date_to
AND CASE
WHEN @date_to :: timestamp with time zone != '0001-01-01 00:00:00' THEN
"time" <= @date_to
ELSE true
END;

-- name: InsertAuditLog :one
Expand Down
1 change: 1 addition & 0 deletions codersdk/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ type CreateTestAuditLogRequest struct {
Action AuditAction `json:"action,omitempty"`
ResourceType ResourceType `json:"resource_type,omitempty"`
ResourceID uuid.UUID `json:"resource_id,omitempty"`
Time time.Time `json:"time,omitempty"`
}

// AuditLogs retrieves audit logs from the given page.
Expand Down
2 changes: 2 additions & 0 deletions docs/admin/audit-logs.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ The supported filters are:
- `action`- The action applied to a resource. You can [find here](https://pkg.go.dev/github.com/coder/coder@main/codersdk#AuditAction) all the actions that are supported.
- `username` - The username of the user who triggered the action.
- `email` - The email of the user who triggered the action.
- `date_from` - The inclusive start date with format `YYYY-MM-DD`.
- `date_to ` - the inclusive end date with format `YYYY-MM-DD`.

## Enabling this feature

Expand Down
5 changes: 3 additions & 2 deletions enterprise/audit/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,14 @@ var AuditableResources = auditMap(map[any]map[string]Action{
"organization_id": ActionIgnore, // Never changes.
"avatar_url": ActionTrack,
},
// We don't show any diff for the WorkspaceBuild resource
// We don't show any diff for the WorkspaceBuild resource,
// save for the template_version_id
&database.WorkspaceBuild{}: {
"id": ActionIgnore,
"created_at": ActionIgnore,
"updated_at": ActionIgnore,
"workspace_id": ActionIgnore,
"template_version_id": ActionIgnore,
"template_version_id": ActionTrack,
"build_number": ActionIgnore,
"transition": ActionIgnore,
"initiator_id": ActionIgnore,
Expand Down
1 change: 1 addition & 0 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ export interface CreateTestAuditLogRequest {
readonly action?: AuditAction
readonly resource_type?: ResourceType
readonly resource_id?: string
readonly time?: string
}

// From codersdk/apikey.go
Expand Down