Skip to content

feat: add audit logs for dormancy events #15298

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 14 commits into from
Oct 31, 2024
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
1 change: 1 addition & 0 deletions cli/server_createadminuser.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ func (r *RootCmd) newCreateAdminUserCommand() *serpent.Command {
UpdatedAt: dbtime.Now(),
RBACRoles: []string{rbac.RoleOwner().String()},
LoginType: database.LoginTypePassword,
Status: "",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we pass "" here? Should we just pass active?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally I would omit it but the linter doesn't like leaving it out. It doesn't really matter what this is created as, so "" just does the default behavior which is dormant.

})
if err != nil {
return xerrors.Errorf("insert user: %w", err)
Expand Down
8 changes: 8 additions & 0 deletions coderd/apidoc/docs.go

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

8 changes: 8 additions & 0 deletions coderd/apidoc/swagger.json

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

33 changes: 33 additions & 0 deletions coderd/audit/fields.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package audit

import (
"context"
"encoding/json"

"cdr.dev/slog"
)

type BackgroundSubsystem string

const (
BackgroundSubsystemDormancy BackgroundSubsystem = "dormancy"
)

func BackgroundTaskFields(subsystem BackgroundSubsystem) map[string]string {
return map[string]string{
"automatic_actor": "coder",
"automatic_subsystem": string(subsystem),
}
}

func BackgroundTaskFieldsBytes(ctx context.Context, logger slog.Logger, subsystem BackgroundSubsystem) []byte {
af := BackgroundTaskFields(subsystem)

wriBytes, err := json.Marshal(af)
if err != nil {
logger.Error(ctx, "marshal additional fields for dormancy audit", slog.Error(err))
return []byte("{}")
}

return wriBytes
}
13 changes: 7 additions & 6 deletions coderd/audit/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ type BackgroundAuditParams[T Auditable] struct {
Audit Auditor
Log slog.Logger

UserID uuid.UUID
RequestID uuid.UUID
Status int
Action database.AuditAction
OrganizationID uuid.UUID
IP string
UserID uuid.UUID
RequestID uuid.UUID
Status int
Action database.AuditAction
OrganizationID uuid.UUID
IP string
// todo: this should automatically marshal an interface{} instead of accepting a raw message.
AdditionalFields json.RawMessage

New T
Expand Down
1 change: 1 addition & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,7 @@ func New(options *Options) *API {

apiKeyMiddleware := httpmw.ExtractAPIKeyMW(httpmw.ExtractAPIKeyConfig{
DB: options.Database,
ActivateDormantUser: ActivateDormantUser(options.Logger, &api.Auditor, options.Database),
OAuth2Configs: oauthConfigs,
RedirectToLogin: false,
DisableSessionExpiryRefresh: options.DeploymentValues.Sessions.DisableExpiryRefresh.Value(),
Expand Down
3 changes: 3 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,9 @@ func createAnotherUserRetry(t testing.TB, client *codersdk.Client, organizationI
Name: RandomName(t),
Password: "SomeSecurePassword!",
OrganizationIDs: organizationIDs,
// Always create users as active in tests to ignore an extra audit log
// when logging in.
UserStatus: ptr.Ref(codersdk.UserStatusActive),
}
for _, m := range mutators {
m(&req)
Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbgen/dbgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ func User(t testing.TB, db database.Store, orig database.User) database.User {
UpdatedAt: takeFirst(orig.UpdatedAt, dbtime.Now()),
RBACRoles: takeFirstSlice(orig.RBACRoles, []string{}),
LoginType: takeFirst(orig.LoginType, database.LoginTypePassword),
Status: string(takeFirst(orig.Status, database.UserStatusDormant)),
})
require.NoError(t, err, "insert user")

Expand Down
8 changes: 7 additions & 1 deletion coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -7709,6 +7709,11 @@ func (q *FakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
}
}

status := database.UserStatusDormant
if arg.Status != "" {
status = database.UserStatus(arg.Status)
}

user := database.User{
ID: arg.ID,
Email: arg.Email,
Expand All @@ -7717,7 +7722,7 @@ func (q *FakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
UpdatedAt: arg.UpdatedAt,
Username: arg.Username,
Name: arg.Name,
Status: database.UserStatusDormant,
Status: status,
RBACRoles: arg.RBACRoles,
LoginType: arg.LoginType,
}
Expand Down Expand Up @@ -8640,6 +8645,7 @@ func (q *FakeQuerier) UpdateInactiveUsersToDormant(_ context.Context, params dat
updated = append(updated, database.UpdateInactiveUsersToDormantRow{
ID: user.ID,
Email: user.Email,
Username: user.Username,
LastSeenAt: user.LastSeenAt,
})
}
Expand Down
21 changes: 17 additions & 4 deletions coderd/database/queries.sql.go

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

11 changes: 8 additions & 3 deletions coderd/database/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,15 @@ INSERT INTO
created_at,
updated_at,
rbac_roles,
login_type
login_type,
status
)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *;
($1, $2, $3, $4, $5, $6, $7, $8, $9,
-- if the status passed in is empty, fallback to dormant, which is what
-- we were doing before.
COALESCE(NULLIF(@status::text, '')::user_status, 'dormant'::user_status)
) RETURNING *;
Comment on lines +74 to +78
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we handle this as a special case? Shouldn't we expect the status to be provided?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't really want to leak the previous default behavior out into the API code. I think it makes more sense to do the default behavior here, which is what was happening before when it wasn't being inserted.


-- name: UpdateUserProfile :one
UPDATE
Expand Down Expand Up @@ -286,7 +291,7 @@ SET
WHERE
last_seen_at < @last_seen_after :: timestamp
AND status = 'active'::user_status
RETURNING id, email, last_seen_at;
RETURNING id, email, username, last_seen_at;

-- AllUserIDs returns all UserIDs regardless of user status or deletion.
-- name: AllUserIDs :many
Expand Down
18 changes: 9 additions & 9 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const (

type ExtractAPIKeyConfig struct {
DB database.Store
ActivateDormantUser func(ctx context.Context, u database.User) (database.User, error)
OAuth2Configs *OAuth2Configs
RedirectToLogin bool
DisableSessionExpiryRefresh bool
Expand Down Expand Up @@ -414,21 +415,20 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
})
}

if userStatus == database.UserStatusDormant {
// If coder confirms that the dormant user is valid, it can switch their account to active.
// nolint:gocritic
u, err := cfg.DB.UpdateUserStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateUserStatusParams{
ID: key.UserID,
Status: database.UserStatusActive,
UpdatedAt: dbtime.Now(),
if userStatus == database.UserStatusDormant && cfg.ActivateDormantUser != nil {
id, _ := uuid.Parse(actor.ID)
user, err := cfg.ActivateDormantUser(ctx, database.User{
ID: id,
Username: actor.FriendlyName,
Status: userStatus,
})
if err != nil {
return write(http.StatusInternalServerError, codersdk.Response{
Message: internalErrorMessage,
Detail: fmt.Sprintf("can't activate a dormant user: %s", err.Error()),
Detail: fmt.Sprintf("update user status: %s", err.Error()),
})
}
userStatus = u.Status
userStatus = user.Status
}

if userStatus != database.UserStatusActive {
Expand Down
1 change: 1 addition & 0 deletions coderd/provisionerdserver/provisionerdserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,7 @@ func (s *server) FailJob(ctx context.Context, failJob *proto.FailedJob) (*proto.
wriBytes, err := json.Marshal(buildResourceInfo)
if err != nil {
s.Logger.Error(ctx, "marshal workspace resource info for failed job", slog.Error(err))
wriBytes = []byte("{}")
}

bag := audit.BaggageFromContext(ctx)
Expand Down
Loading
Loading