go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cv/internal/rpc/pagination/token.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 pagination
    16  
    17  import (
    18  	"context"
    19  	"reflect"
    20  
    21  	"google.golang.org/grpc/codes"
    22  	"google.golang.org/protobuf/proto"
    23  
    24  	"go.chromium.org/luci/common/errors"
    25  	"go.chromium.org/luci/grpc/appstatus"
    26  	"go.chromium.org/luci/server/secrets"
    27  )
    28  
    29  // InvalidToken annotates the error with InvalidArgument appstatus.
    30  func InvalidToken(err error) error {
    31  	return appstatus.Attachf(err, codes.InvalidArgument, "invalid page token")
    32  }
    33  
    34  // cryptoAdditionalData is used to verify integrity of the page tokens.
    35  var cryptoAdditionalData = []byte("cv-proto-token")
    36  
    37  // DecryptPageToken extracts page token from the request into the given proto.
    38  //
    39  // Returns appstatus-annotated InvalidArgument error if token isn't valid.
    40  func DecryptPageToken(ctx context.Context, pageToken string, dst proto.Message) error {
    41  	if pageToken == "" {
    42  		return nil
    43  	}
    44  	bytes, err := secrets.URLSafeDecrypt(ctx, pageToken, cryptoAdditionalData)
    45  	if err != nil {
    46  		return InvalidToken(err)
    47  	}
    48  	if err := proto.Unmarshal(bytes, dst); err != nil {
    49  		return InvalidToken(err)
    50  	}
    51  	return nil
    52  }
    53  
    54  // EncryptPageToken encrypts a generic page token to an opaque URL-safe string,
    55  //
    56  // Input proto can be nil, in which case resulting page token is empty.
    57  func EncryptPageToken(ctx context.Context, src proto.Message) (string, error) {
    58  	if src == nil || reflect.ValueOf(src).IsNil() {
    59  		return "", nil
    60  	}
    61  	bytes, err := proto.Marshal(src)
    62  	if err != nil {
    63  		return "", errors.Annotate(err, "failed to serialize page token").Err()
    64  	}
    65  	return secrets.URLSafeEncrypt(ctx, bytes, cryptoAdditionalData)
    66  }