go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/auth/xsrf/interceptor.go (about)

     1  // Copyright 2021 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package xsrf
    16  
    17  import (
    18  	"context"
    19  
    20  	"google.golang.org/grpc/codes"
    21  	"google.golang.org/grpc/metadata"
    22  	"google.golang.org/grpc/status"
    23  
    24  	"go.chromium.org/luci/common/logging"
    25  	"go.chromium.org/luci/common/retry/transient"
    26  	"go.chromium.org/luci/grpc/grpcutil"
    27  
    28  	"go.chromium.org/luci/server/auth"
    29  )
    30  
    31  // XSRFTokenMetadataKey is the gRPC metadata key with the XSRF token.
    32  const XSRFTokenMetadataKey = "x-xsrf-token"
    33  
    34  // Interceptor returns a server interceptor that check the XSRF token if the
    35  // call was authenticated through the given method (usually some sort of
    36  // cookie-based authentication).
    37  //
    38  // The token should be in the incoming metadata at "x-xsrf-token" key.
    39  //
    40  // This is useful as a defense in depth against unauthorized cross-origin
    41  // requests when using pRPC APIs with cookie-based authentication. Theoretically
    42  // CORS policies and SameSite cookies can also solve this problem, but their
    43  // semantics is pretty complicated and it is easy to mess up.
    44  func Interceptor(method auth.Method) grpcutil.UnifiedServerInterceptor {
    45  	return func(ctx context.Context, _ string, handler func(ctx context.Context) error) (err error) {
    46  		if auth.GetState(ctx).Method() == method {
    47  			found := false
    48  			md, _ := metadata.FromIncomingContext(ctx)
    49  			for _, val := range md[XSRFTokenMetadataKey] {
    50  				err := Check(ctx, val)
    51  				if err == nil {
    52  					found = true
    53  					break
    54  				}
    55  				if transient.Tag.In(err) {
    56  					logging.Errorf(ctx, "Transient error when checking XSRF token: %s", err)
    57  					return status.Errorf(codes.Internal, "internal error when checking XSRF token")
    58  				}
    59  			}
    60  			if !found {
    61  				return status.Errorf(codes.Unauthenticated, "missing or invalid XSRF token in %q metadata", XSRFTokenMetadataKey)
    62  			}
    63  		}
    64  		return handler(ctx)
    65  	}
    66  }