go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/logdog/common/types/streamsecret.go (about)

     1  // Copyright 2015 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 types
    16  
    17  import (
    18  	"crypto/rand"
    19  	"fmt"
    20  )
    21  
    22  const (
    23  	// PrefixSecretLength is the size, in bytes, of the stream secret.
    24  	//
    25  	// This value was chosen such that it is:
    26  	// - Sufficiently large to avoid collisions.
    27  	// - Can be expressed as a Base64 string without ugly padding.
    28  	PrefixSecretLength = 36
    29  
    30  	// OpNonceLength is the exact length that an OpNonce must be, if supplied.
    31  	OpNonceLength = 32
    32  )
    33  
    34  // PrefixSecret is the prefix secret value. It is used to assert ownership of
    35  // a prefix space.
    36  //
    37  // The Prefix secret is generated by the Coordinator at prefix registration,
    38  // and is included by the Butler to prove that it is the entity that registered
    39  // the stream. The secret is asserted by microservices and the Coordinator
    40  // during Butler-initiated stream operations.
    41  type PrefixSecret []byte
    42  
    43  // NewPrefixSecret generates a new, default-length secret parameter.
    44  func NewPrefixSecret() (PrefixSecret, error) {
    45  	buf := make([]byte, PrefixSecretLength)
    46  	if _, err := rand.Read(buf); err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	value := PrefixSecret(buf)
    51  	if err := value.Validate(); err != nil {
    52  		panic(err)
    53  	}
    54  	return value, nil
    55  }
    56  
    57  // Validate confirms that this prefix secret is conformant.
    58  //
    59  // Note that this does not scan the byte contents of the secret for any
    60  // security-related parameters.
    61  func (s PrefixSecret) Validate() error {
    62  	if len(s) != PrefixSecretLength {
    63  		return fmt.Errorf("invalid prefix secret length (%d != %d)", len(s), PrefixSecretLength)
    64  	}
    65  	return nil
    66  }