github.com/google/osv-scalibr@v0.4.1/veles/secrets/github/validate/validate.go (about)

     1  // Copyright 2025 Google LLC
     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 validate contains common logic to validate github tokens
    16  package validate
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"io"
    22  	"net/http"
    23  
    24  	"github.com/google/osv-scalibr/veles"
    25  )
    26  
    27  // Validate validates a Github token given a client and a path
    28  func Validate(ctx context.Context, client *http.Client, path string, token string) (veles.ValidationStatus, error) {
    29  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com"+path, nil)
    30  	if err != nil {
    31  		return veles.ValidationFailed, fmt.Errorf("unable to create HTTP request: %w", err)
    32  	}
    33  	req.Header.Set("Authorization", "Bearer "+token)
    34  	req.Header.Set("Accept", "application/vnd.github+json")
    35  	//nolint:canonicalheader // This header is set as "X-GitHub-Api-Version" exactly as documented by GitHub.
    36  	req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
    37  
    38  	res, err := client.Do(req)
    39  	if err != nil {
    40  		return veles.ValidationFailed, fmt.Errorf("HTTP GET failed: %w", err)
    41  	}
    42  	defer res.Body.Close()
    43  	_, err = io.ReadAll(res.Body)
    44  	if err != nil {
    45  		return veles.ValidationFailed, fmt.Errorf("failed to read response body: %w", err)
    46  	}
    47  
    48  	switch res.StatusCode {
    49  	case http.StatusOK, http.StatusForbidden:
    50  		return veles.ValidationValid, nil
    51  	case http.StatusUnauthorized:
    52  		return veles.ValidationInvalid, nil
    53  	default:
    54  		return veles.ValidationFailed, nil
    55  	}
    56  }