|
| 1 | +package grpc |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/sha256" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/buildbarn/bb-storage/pkg/auth" |
| 10 | + "github.com/buildbarn/bb-storage/pkg/clock" |
| 11 | + "github.com/buildbarn/bb-storage/pkg/eviction" |
| 12 | + auth_pb "github.com/buildbarn/bb-storage/pkg/proto/auth" |
| 13 | + "github.com/buildbarn/bb-storage/pkg/util" |
| 14 | + "google.golang.org/grpc" |
| 15 | + "google.golang.org/grpc/codes" |
| 16 | + "google.golang.org/grpc/status" |
| 17 | + "google.golang.org/protobuf/proto" |
| 18 | + "google.golang.org/protobuf/types/known/structpb" |
| 19 | +) |
| 20 | + |
| 21 | +type remoteAuthenticator struct { |
| 22 | + remoteAuthClient auth_pb.AuthenticationClient |
| 23 | + scope *structpb.Value |
| 24 | + |
| 25 | + clock clock.Clock |
| 26 | + maximumCacheSize int |
| 27 | + |
| 28 | + lock sync.Mutex |
| 29 | + cachedResponses map[RemoteAuthenticatorCacheKey]*remoteAuthCacheEntry |
| 30 | + evictionSet eviction.Set[RemoteAuthenticatorCacheKey] |
| 31 | +} |
| 32 | + |
| 33 | +type RemoteAuthenticatorCacheKey [sha256.Size]byte |
| 34 | + |
| 35 | +type remoteAuthCacheEntry struct { |
| 36 | + ready <-chan struct{} |
| 37 | + response remoteAuthResponse |
| 38 | +} |
| 39 | + |
| 40 | +type remoteAuthResponse struct { |
| 41 | + expirationTime time.Time |
| 42 | + authMetadata *auth.AuthenticationMetadata |
| 43 | + err error |
| 44 | +} |
| 45 | + |
| 46 | +func (ce *remoteAuthCacheEntry) HasExpired(now time.Time) bool { |
| 47 | + select { |
| 48 | + case <-ce.ready: |
| 49 | + return ce.response.expirationTime.Before(now) |
| 50 | + default: |
| 51 | + // Ongoing remote requests have not expired by definition. |
| 52 | + return false |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// NewRemoteAuthenticator creates a new RemoteAuthenticator for incoming |
| 57 | +// requests that forwards headers to a remote service for authentication. The |
| 58 | +// result from the remote service is cached. |
| 59 | +func NewRemoteAuthenticator( |
| 60 | + client grpc.ClientConnInterface, |
| 61 | + scope *structpb.Value, |
| 62 | + clock clock.Clock, |
| 63 | + evictionSet eviction.Set[RemoteAuthenticatorCacheKey], |
| 64 | + maximumCacheSize int, |
| 65 | +) RequestHeadersAuthenticator { |
| 66 | + return &remoteAuthenticator{ |
| 67 | + remoteAuthClient: auth_pb.NewAuthenticationClient(client), |
| 68 | + scope: scope, |
| 69 | + |
| 70 | + clock: clock, |
| 71 | + maximumCacheSize: maximumCacheSize, |
| 72 | + |
| 73 | + cachedResponses: make(map[RemoteAuthenticatorCacheKey]*remoteAuthCacheEntry), |
| 74 | + evictionSet: evictionSet, |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +func (a *remoteAuthenticator) Authenticate(ctx context.Context, headers map[string][]string) (*auth.AuthenticationMetadata, error) { |
| 79 | + request := &auth_pb.AuthenticateRequest{ |
| 80 | + RequestMetadata: make(map[string]*auth_pb.AuthenticateRequest_ValueList, len(headers)), |
| 81 | + Scope: a.scope, |
| 82 | + } |
| 83 | + for headerKey, headerValues := range headers { |
| 84 | + request.RequestMetadata[headerKey] = &auth_pb.AuthenticateRequest_ValueList{ |
| 85 | + Value: headerValues, |
| 86 | + } |
| 87 | + } |
| 88 | + requestBytes, err := proto.Marshal(request) |
| 89 | + if err != nil { |
| 90 | + return nil, util.StatusWrapWithCode(err, codes.Unauthenticated, "Failed to marshal authenticate request") |
| 91 | + } |
| 92 | + // Hash the request to use as a cache key to both save memory and avoid |
| 93 | + // keeping credentials in the memory. |
| 94 | + requestKey := sha256.Sum256(requestBytes) |
| 95 | + |
| 96 | + a.lock.Lock() |
| 97 | + now := a.clock.Now() |
| 98 | + entry := a.getAndTouchCacheEntry(requestKey) |
| 99 | + if entry != nil && entry.HasExpired(now) { |
| 100 | + entry = nil |
| 101 | + } |
| 102 | + if entry == nil { |
| 103 | + // No valid cache entry available. Deduplicate requests by creating a |
| 104 | + // pending cached response. |
| 105 | + responseReady := make(chan struct{}) |
| 106 | + entry = &remoteAuthCacheEntry{ |
| 107 | + ready: responseReady, |
| 108 | + } |
| 109 | + a.cachedResponses[requestKey] = entry |
| 110 | + a.lock.Unlock() |
| 111 | + |
| 112 | + // Perform the remote authentication request. |
| 113 | + entry.response = a.authenticateRemotely(ctx, request) |
| 114 | + close(responseReady) |
| 115 | + } else { |
| 116 | + a.lock.Unlock() |
| 117 | + |
| 118 | + // Wait for the remote request to finish. |
| 119 | + select { |
| 120 | + case <-ctx.Done(): |
| 121 | + return nil, util.StatusWrapWithCode(ctx.Err(), codes.Unauthenticated, "Context cancelled") |
| 122 | + case <-entry.ready: |
| 123 | + // Noop |
| 124 | + } |
| 125 | + } |
| 126 | + return entry.response.authMetadata, entry.response.err |
| 127 | +} |
| 128 | + |
| 129 | +func (a *remoteAuthenticator) getAndTouchCacheEntry(requestKey RemoteAuthenticatorCacheKey) *remoteAuthCacheEntry { |
| 130 | + if entry, ok := a.cachedResponses[requestKey]; ok { |
| 131 | + // Cache contains a matching entry. |
| 132 | + a.evictionSet.Touch(requestKey) |
| 133 | + return entry |
| 134 | + } |
| 135 | + |
| 136 | + // Cache contains no matching entry. Free up space, so that the |
| 137 | + // caller may insert a new entry. |
| 138 | + for len(a.cachedResponses) >= a.maximumCacheSize { |
| 139 | + delete(a.cachedResponses, a.evictionSet.Peek()) |
| 140 | + a.evictionSet.Remove() |
| 141 | + } |
| 142 | + a.evictionSet.Insert(requestKey) |
| 143 | + return nil |
| 144 | +} |
| 145 | + |
| 146 | +func (a *remoteAuthenticator) authenticateRemotely(ctx context.Context, request *auth_pb.AuthenticateRequest) remoteAuthResponse { |
| 147 | + ret := remoteAuthResponse{ |
| 148 | + // The default expirationTime has already passed. |
| 149 | + expirationTime: time.Time{}, |
| 150 | + } |
| 151 | + |
| 152 | + response, err := a.remoteAuthClient.Authenticate(ctx, request) |
| 153 | + if err != nil { |
| 154 | + ret.err = util.StatusWrapWithCode(err, codes.Unauthenticated, "Remote authentication failed") |
| 155 | + return ret |
| 156 | + } |
| 157 | + |
| 158 | + // An invalid expiration time indicates that the response should not be cached. |
| 159 | + if response.GetCacheExpirationTime().IsValid() { |
| 160 | + // Note that the expiration time might still be valid for non-allow verdicts. |
| 161 | + ret.expirationTime = response.GetCacheExpirationTime().AsTime() |
| 162 | + } |
| 163 | + |
| 164 | + switch verdict := response.GetVerdict().(type) { |
| 165 | + case *auth_pb.AuthenticateResponse_Allow: |
| 166 | + ret.authMetadata, err = auth.NewAuthenticationMetadataFromProto(verdict.Allow) |
| 167 | + if err != nil { |
| 168 | + ret.err = util.StatusWrapWithCode(err, codes.Unauthenticated, "Bad authentication response") |
| 169 | + return ret |
| 170 | + } |
| 171 | + case *auth_pb.AuthenticateResponse_Deny: |
| 172 | + ret.err = status.Error(codes.Unauthenticated, verdict.Deny) |
| 173 | + return ret |
| 174 | + default: |
| 175 | + ret.err = status.Error(codes.Unauthenticated, "Invalid authentication verdict") |
| 176 | + return ret |
| 177 | + } |
| 178 | + return ret |
| 179 | +} |
0 commit comments