go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/encryptedcookies/session/store.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 session defines API for the session storage.
    16  package session
    17  
    18  import (
    19  	"context"
    20  	"crypto/rand"
    21  	"encoding/base64"
    22  	"fmt"
    23  
    24  	"go.chromium.org/luci/server/encryptedcookies/session/sessionpb"
    25  )
    26  
    27  // ID identifies a session.
    28  type ID []byte
    29  
    30  // String is used to format the ID for logging.
    31  func (id ID) String() string {
    32  	return base64.RawStdEncoding.EncodeToString(id)
    33  }
    34  
    35  // GenerateID generates a new random session ID or panics if there's not enough
    36  // entropy.
    37  func GenerateID() ID {
    38  	id := make([]byte, 20)
    39  	if _, err := rand.Read(id); err != nil {
    40  		panic(fmt.Sprintf("failed to generate session ID: %s", err))
    41  	}
    42  	return id
    43  }
    44  
    45  // Store is a persistent transactional-capable storage of user sessions.
    46  //
    47  // Session IDs are assumed to be generated by GenerateID, i.e. be high-entropy
    48  // random blobs.
    49  type Store interface {
    50  	// FetchSession fetches an existing session with the given ID.
    51  	//
    52  	// Returns (nil, nil) if there's no such session. All errors are transient.
    53  	FetchSession(ctx context.Context, id ID) (*sessionpb.Session, error)
    54  
    55  	// UpdateSession transactionally updates or creates a session.
    56  	//
    57  	// If fetches the session, calls the callback to mutate it, and stores the
    58  	// result. If it is a new session, the callback receives an empty proto.
    59  	//
    60  	// The callback may be called multiple times in case the transaction is
    61  	// retried. Errors from callbacks are returned as is. All other errors are
    62  	// transient.
    63  	UpdateSession(ctx context.Context, id ID, cb func(*sessionpb.Session) error) error
    64  }