Welcome to mirror list, hosted at ThFree Co, Russian Federation.

auth.go « auth « server « gitaly « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8e34bdf78feb7a1ba1a23b022563d4f845270d07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package auth

import (
	"context"
	"time"

	grpcmwauth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	gitalyauth "gitlab.com/gitlab-org/gitaly/v14/auth"
	gitalycfgauth "gitlab.com/gitlab-org/gitaly/internal/gitaly/config/auth"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var authCount = promauto.NewCounterVec(
	prometheus.CounterOpts{
		Name: "gitaly_authentications_total",
		Help: "Counts of of Gitaly request authentication attempts",
	},
	[]string{"enforced", "status"},
)

// StreamServerInterceptor checks for Gitaly bearer tokens.
func StreamServerInterceptor(conf gitalycfgauth.Config) grpc.StreamServerInterceptor {
	return grpcmwauth.StreamServerInterceptor(checkFunc(conf))
}

// UnaryServerInterceptor checks for Gitaly bearer tokens.
func UnaryServerInterceptor(conf gitalycfgauth.Config) grpc.UnaryServerInterceptor {
	return grpcmwauth.UnaryServerInterceptor(checkFunc(conf))
}

func checkFunc(conf gitalycfgauth.Config) func(ctx context.Context) (context.Context, error) {
	return func(ctx context.Context) (context.Context, error) {
		if len(conf.Token) == 0 {
			countStatus("server disabled authentication", conf.Transitioning).Inc()
			return ctx, nil
		}

		err := gitalyauth.CheckToken(ctx, conf.Token, time.Now())
		switch status.Code(err) {
		case codes.OK:
			countStatus(okLabel(conf.Transitioning), conf.Transitioning).Inc()
		case codes.Unauthenticated:
			countStatus("unauthenticated", conf.Transitioning).Inc()
		case codes.PermissionDenied:
			countStatus("denied", conf.Transitioning).Inc()
		default:
			countStatus("invalid", conf.Transitioning).Inc()
		}

		if conf.Transitioning {
			err = nil
		}

		return ctx, err
	}
}

func okLabel(transitioning bool) string {
	if transitioning {
		// This special value is an extra warning sign to administrators that
		// authentication is currently not enforced.
		return "would be ok"
	}
	return "ok"
}

func countStatus(status string, transitioning bool) prometheus.Counter {
	enforced := "true"
	if transitioning {
		enforced = "false"
	}
	return authCount.WithLabelValues(enforced, status)
}