github.com/apptainer/singularity@v3.1.1+incompatible/internal/pkg/util/auth/token.go (about)

     1  /*
     2    Copyright (c) 2018, Sylabs, Inc. All rights reserved.
     3  
     4    This software is licensed under a 3-clause BSD license.  Please
     5    consult LICENSE.md file distributed with the sources of this project regarding
     6    your rights to use or distribute this software.
     7  */
     8  
     9  package auth
    10  
    11  import (
    12  	"io/ioutil"
    13  	"os"
    14  	"strings"
    15  )
    16  
    17  const (
    18  	// WarningTokenTooShort Warning return for token shorter than 200 b
    19  	WarningTokenTooShort = "Token is too short to be valid"
    20  	// WarningTokenToolong Warning return for token longer than 4096 b
    21  	WarningTokenToolong = "Token is too large to be valid"
    22  	// WarningEmptyToken Warning return for empty token string
    23  	WarningEmptyToken = "Token file is empty"
    24  	// WarningTokenFileNotFound token file not found
    25  	WarningTokenFileNotFound = "Authentication token file not found"
    26  	// WarningCouldntReadFile Warning return for issues when reading file
    27  	WarningCouldntReadFile = "Couldn't read your Sylabs authentication token"
    28  )
    29  
    30  // ReadToken reads a sylabs JWT auth token from a file
    31  func ReadToken(tokenPath string) (token, warning string) {
    32  	// check if token file exist
    33  	_, err := os.Stat(tokenPath)
    34  	if os.IsNotExist(err) {
    35  		return "", WarningTokenFileNotFound
    36  	}
    37  
    38  	buf, err := ioutil.ReadFile(tokenPath)
    39  	if err != nil {
    40  		return "", WarningCouldntReadFile
    41  	}
    42  
    43  	lines := strings.Split(string(buf), "\n")
    44  	if len(lines) < 1 {
    45  		return "", WarningEmptyToken
    46  	}
    47  
    48  	// A valid RSA signed token is at least 200 chars with no extra payload
    49  	token = lines[0]
    50  	if len(token) < 200 {
    51  		return "", WarningTokenTooShort
    52  	}
    53  
    54  	// A token should never be bigger than 4Kb - if it is we will have problems
    55  	// with header buffers
    56  	if len(token) > 4096 {
    57  		return "", WarningTokenToolong
    58  	}
    59  
    60  	return
    61  }