Skip to content

Commit

Permalink
Convert lib/auth/join* to use slog
Browse files Browse the repository at this point in the history
  • Loading branch information
rosstimothy committed Dec 20, 2024
1 parent 6061a88 commit 2d658c6
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 78 deletions.
94 changes: 59 additions & 35 deletions lib/auth/join.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"log/slog"
"net"
"slices"
"strings"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/peer"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
Expand Down Expand Up @@ -60,7 +59,11 @@ func (a *Server) checkTokenJoinRequestCommon(ctx context.Context, req *types.Reg
// make sure the token is valid
provisionToken, err := a.ValidateToken(ctx, req.Token)
if err != nil {
log.Warningf("%q can not join the cluster with role %s, token error: %v", req.NodeName, req.Role, err)
a.logger.WarnContext(ctx, "cannot join the cluster with invalid token",
"node_name", req.NodeName,
"role", req.Role,
"error", err,
)
msg := "the token is not valid" // default to most generic message
if strings.Contains(err.Error(), TokenExpiredOrNotFound) {
// propagate ExpiredOrNotFound message so that clients can attempt
Expand All @@ -80,17 +83,22 @@ func (a *Server) checkTokenJoinRequestCommon(ctx context.Context, req *types.Reg
}
}
if !hasLocalServiceRole {
msg := fmt.Sprintf("%q [%v] cannot requisition instance certs (token contains no local service roles)", req.NodeName, req.HostID)
log.Warn(msg)
return nil, trace.AccessDenied(msg)
a.logger.WarnContext(ctx, "cannot requisition instance certs (token contains no local service roles)",
"node_name", req.NodeName,
"host_id", req.HostID,
)
return nil, trace.AccessDenied("%s [%v] cannot requisition instance certs (token contains no local service roles)", req.NodeName, req.HostID)
}
}

// make sure the caller is requesting a role allowed by the token
if !provisionToken.GetRoles().Include(req.Role) && req.Role != types.RoleInstance {
msg := fmt.Sprintf("node %q [%v] can not join the cluster, the token does not allow %q role", req.NodeName, req.HostID, req.Role)
log.Warn(msg)
return nil, trace.BadParameter(msg)
a.logger.WarnContext(ctx, "token does not allow role to join the cluster",
"node_name", req.NodeName,
"host_id", req.HostID,
"role", req.Role,
)
return nil, trace.BadParameter("node %q [%v] can not join the cluster, the token does not allow %q role", req.NodeName, req.HostID, req.Role)
}

return provisionToken, nil
Expand Down Expand Up @@ -121,17 +129,20 @@ func setRemoteAddrFromContext(ctx context.Context, req *types.RegisterUsingToken
// handleJoinFailure logs and audits the failure of a join. It is intentionally
// designed to handle potential nullness of the input parameters.
func (a *Server) handleJoinFailure(
ctx context.Context,
origErr error,
pt types.ProvisionToken,
attributeSource joinAttributeSourcer,
req *types.RegisterUsingTokenRequest,
) {
fields := logrus.Fields{}
attrs := []slog.Attr{slog.Any("error", origErr)}
if req != nil {
fields["role"] = req.Role
fields["host_id"] = req.HostID
fields["node_name"] = req.NodeName
fields["remote_addr"] = req.RemoteAddr
attrs = append(attrs, []slog.Attr{
slog.String("role", string(req.Role)),
slog.String("host_id", req.HostID),
slog.String("node_name", req.NodeName),
slog.String("remote_addr", req.RemoteAddr),
}...)
}

// Fetch and encode attributes if they are available.
Expand All @@ -140,21 +151,21 @@ func (a *Server) handleJoinFailure(
var err error
attributes, err := attributeSource.JoinAuditAttributes()
if err != nil {
log.WithError(err).Warn("Unable to fetch join attributes from join method")
a.logger.WarnContext(ctx, "Unable to fetch join attributes from join method", "error", err)
}
fields["attributes"] = attributes
attrs = append(attrs, slog.Any("attributes", attributes))
attributesProto, err = apievents.EncodeMap(attributes)
if err != nil {
log.WithError(err).Warn("Unable to encode join attributes for audit event")
a.logger.WarnContext(ctx, "Unable to encode join attributes for audit event", "error", err)
}
}

// Add log fields from token if available.
if pt != nil {
fields["join_method"] = string(pt.GetJoinMethod())
fields["token_name"] = pt.GetSafeName()
attrs = append(attrs, slog.String("join_method", string(pt.GetJoinMethod())))
attrs = append(attrs, slog.String("token_name", pt.GetSafeName()))
}
log.WithError(origErr).WithFields(fields).Warn("Failure to join cluster occurred")
a.logger.LogAttrs(ctx, slog.LevelWarn, "Failure to join cluster occurred", attrs...)

var evt apievents.AuditEvent
status := apievents.Status{
Expand Down Expand Up @@ -201,7 +212,7 @@ func (a *Server) handleJoinFailure(
evt = instanceJoinEvent
}
if err := a.emitter.EmitAuditEvent(a.closeCtx, evt); err != nil {
log.WithError(err).Warn("Failed to emit failed join event")
a.logger.WarnContext(ctx, "Failed to emit failed join event", "error", err)
}
}

Expand All @@ -222,7 +233,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
defer func() {
// Emit a log message and audit event on join failure.
if err != nil {
a.handleJoinFailure(err, provisionToken, joinAttributeSrc, req)
a.handleJoinFailure(ctx, err, provisionToken, joinAttributeSrc, req)
}
}()

Expand Down Expand Up @@ -398,16 +409,16 @@ func (a *Server) generateCertsBot(
if joinAttributeSrc != nil {
attributes, err := joinAttributeSrc.JoinAuditAttributes()
if err != nil {
log.WithError(err).Warn("Unable to fetch join attributes from join method.")
a.logger.WarnContext(ctx, "Unable to fetch join attributes from join method", "error", err)
}
joinEvent.Attributes, err = apievents.EncodeMap(attributes)
if err != nil {
log.WithError(err).Warn("Unable to encode join attributes for audit event.")
a.logger.WarnContext(ctx, "Unable to encode join attributes for audit event", "error", err)
}

auth.Metadata, err = structpb.NewStruct(attributes)
if err != nil {
log.WithError(err).Warn("Unable to encode struct value for join metadata.")
a.logger.WarnContext(ctx, "Unable to encode struct value for join metadata", "error", err)
}
}

Expand All @@ -432,16 +443,20 @@ func (a *Server) generateCertsBot(
if shouldDeleteToken {
// delete ephemeral bot join tokens so they can't be re-used
if err := a.DeleteToken(ctx, provisionToken.GetName()); err != nil {
log.WithError(err).Warnf("Could not delete bot provision token %q after generating certs",
provisionToken.GetSafeName(),
a.logger.WarnContext(ctx, "Could not delete bot provision token after generating certs",
"provision_token", provisionToken.GetSafeName(),
"error", err,
)
}
}

// Emit audit event for bot join.
log.Infof("Bot %q (instance: %s) has joined the cluster.", botName, botInstanceID)
a.logger.InfoContext(ctx, "Bot has joined the cluster",
"bot_name", botName,
"bot_instance", botInstanceID,
)
if err := a.emitter.EmitAuditEvent(ctx, joinEvent); err != nil {
log.WithError(err).Warn("Failed to emit bot join event.")
a.logger.WarnContext(ctx, "Failed to emit bot join event", "error", err)
}
return certs, nil
}
Expand All @@ -464,7 +479,7 @@ func (a *Server) generateCerts(
if r.IsLocalService() {
systemRoles = append(systemRoles, r)
} else {
log.Warnf("Omitting non-service system role from instance cert: %q", r)
a.logger.WarnContext(ctx, "Omitting non-service system role from instance cert", "system_role", string(r))
}
}
}
Expand All @@ -488,9 +503,18 @@ func (a *Server) generateCerts(

// Emit audit event
if req.Role == types.RoleInstance {
log.Infof("Instance %q [%v] has joined the cluster. role=%s, systemRoles=%+v", req.NodeName, req.HostID, req.Role, systemRoles)
a.logger.InfoContext(ctx, "Instance has joined the cluster",
"node_name", req.NodeName,
"host_id", req.HostID,
"role", req.Role,
"system_roles", systemRoles,
)
} else {
log.Infof("Instance %q [%v] has joined the cluster. role=%s", req.NodeName, req.HostID, req.Role)
a.logger.InfoContext(ctx, "Instance has joined the cluster",
"node_name", req.NodeName,
"host_id", req.HostID,
"role", req.Role,
)
}
joinEvent := &apievents.InstanceJoin{
Metadata: apievents.Metadata{
Expand All @@ -513,15 +537,15 @@ func (a *Server) generateCerts(
if joinAttributeSrc != nil {
attributes, err := joinAttributeSrc.JoinAuditAttributes()
if err != nil {
log.WithError(err).Warn("Unable to fetch join attributes from join method.")
a.logger.WarnContext(ctx, "Unable to fetch join attributes from join method", "error", err)
}
joinEvent.Attributes, err = apievents.EncodeMap(attributes)
if err != nil {
log.WithError(err).Warn("Unable to encode join attributes for audit event.")
a.logger.WarnContext(ctx, "Unable to encode join attributes for audit event", "error", err)
}
}
if err := a.emitter.EmitAuditEvent(ctx, joinEvent); err != nil {
log.WithError(err).Warn("Failed to emit instance join event.")
a.logger.WarnContext(ctx, "Failed to emit instance join event", "error", err)
}
return certs, nil
}
Expand Down
4 changes: 1 addition & 3 deletions lib/auth/join_azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,9 +366,7 @@ func (a *Server) RegisterUsingAzureMethodWithOpts(
defer func() {
// Emit a log message and audit event on join failure.
if err != nil {
a.handleJoinFailure(
err, provisionToken, nil, joinRequest,
)
a.handleJoinFailure(ctx, err, provisionToken, nil, joinRequest)
}
}()

Expand Down
18 changes: 9 additions & 9 deletions lib/auth/join_gcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"strings"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/gcp"
Expand All @@ -50,17 +49,18 @@ func (a *Server) checkGCPJoinRequest(ctx context.Context, req *types.RegisterUsi

claims, err := a.gcpIDTokenValidator.Validate(ctx, req.IDToken)
if err != nil {
log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).WithError(err).Warn("Unable to validate GCP IDToken")
a.logger.WarnContext(ctx, "Unable to validate GCP IDToken",
"error", err,
"claims", claims,
"token", pt.GetName(),
)
return nil, trace.Wrap(err)
}

log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).Info("GCP VM trying to join cluster")
a.logger.InfoContext(ctx, "GCP VM trying to join cluster",
"claims", claims,
"token", pt.GetName(),
)

if err := checkGCPAllowRules(token, claims); err != nil {
return nil, trace.Wrap(err)
Expand Down
9 changes: 4 additions & 5 deletions lib/auth/join_github.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"time"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/githubactions"
Expand Down Expand Up @@ -87,10 +86,10 @@ func (a *Server) checkGitHubJoinRequest(ctx context.Context, req *types.Register
}
}

log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).Info("Github actions run trying to join cluster")
a.logger.InfoContext(ctx, "Github actions run trying to join cluster",
"claims", claims,
"token", pt.GetName(),
)

return claims, trace.Wrap(checkGithubAllowRules(token, claims))
}
Expand Down
9 changes: 4 additions & 5 deletions lib/auth/join_gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"strings"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/gitlab"
Expand Down Expand Up @@ -57,10 +56,10 @@ func (a *Server) checkGitLabJoinRequest(ctx context.Context, req *types.Register
return nil, trace.Wrap(err)
}

log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).Info("GitLab CI run trying to join cluster")
a.logger.InfoContext(ctx, "GitLab CI run trying to join cluster",
"claims", claims,
"token", pt.GetName(),
)

return claims, trace.Wrap(checkGitLabAllowRules(token, claims))
}
Expand Down
4 changes: 1 addition & 3 deletions lib/auth/join_iam.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,7 @@ func (a *Server) RegisterUsingIAMMethodWithOpts(
defer func() {
// Emit a log message and audit event on join failure.
if err != nil {
a.handleJoinFailure(
err, provisionToken, nil, joinRequest,
)
a.handleJoinFailure(ctx, err, provisionToken, nil, joinRequest)
}
}()

Expand Down
9 changes: 4 additions & 5 deletions lib/auth/join_kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"time"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

"github.com/gravitational/teleport/api/types"
kubetoken "github.com/gravitational/teleport/lib/kube/token"
Expand Down Expand Up @@ -82,10 +81,10 @@ func (a *Server) checkKubernetesJoinRequest(ctx context.Context, req *types.Regi
)
}

log.WithFields(logrus.Fields{
"validated_identity": result,
"token": token.GetName(),
}).Info("Kubernetes workload trying to join cluster")
a.logger.InfoContext(ctx, "Kubernetes workload trying to join cluster",
"validated_identity", result,
"token", token.GetName(),
)

return result, trace.Wrap(checkKubernetesAllowRules(token, result))
}
Expand Down
9 changes: 4 additions & 5 deletions lib/auth/join_spacelift.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"fmt"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/modules"
Expand Down Expand Up @@ -64,10 +63,10 @@ func (a *Server) checkSpaceliftJoinRequest(ctx context.Context, req *types.Regis
return nil, trace.Wrap(err)
}

log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).Info("Spacelift run trying to join cluster")
a.logger.InfoContext(ctx, "Spacelift run trying to join cluster",
"claims", claims,
"token", pt.GetName(),
)

return claims, trace.Wrap(checkSpaceliftAllowRules(token, claims))
}
Expand Down
9 changes: 4 additions & 5 deletions lib/auth/join_terraformcloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"fmt"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/modules"
Expand Down Expand Up @@ -75,10 +74,10 @@ func (a *Server) checkTerraformCloudJoinRequest(ctx context.Context, req *types.
return nil, trace.Wrap(err)
}

log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).Info("Terraform Cloud run trying to join cluster")
a.logger.InfoContext(ctx, "Terraform Cloud run trying to join cluster",
"claims", claims,
"token", pt.GetName(),
)

return claims, trace.Wrap(checkTerraformCloudAllowRules(token, claims))
}
Expand Down
Loading

0 comments on commit 2d658c6

Please sign in to comment.