github.com/google/osv-scalibr@v0.4.1/veles/secrets/pypiapitoken/validator.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 pypiapitoken
    16  
    17  import (
    18  	"bytes"
    19  	"mime/multipart"
    20  	"net/http"
    21  	"time"
    22  
    23  	"github.com/google/osv-scalibr/veles/secrets/common/simplevalidate"
    24  )
    25  
    26  const (
    27  	pypiUploadURL     = "https://upload.pypi.org/legacy/"
    28  	validationTimeout = 10 * time.Second
    29  )
    30  
    31  func mustCreateBodyAndContentType() (string, string) {
    32  	var body bytes.Buffer
    33  	writer := multipart.NewWriter(&body)
    34  
    35  	if err := writer.WriteField(":action", "file_upload"); err != nil {
    36  		panic(err)
    37  	}
    38  	if err := writer.WriteField("name", "dummy-package"); err != nil {
    39  		panic(err)
    40  	}
    41  	if err := writer.WriteField("version", "0.0.1"); err != nil {
    42  		panic(err)
    43  	}
    44  	if err := writer.WriteField("content", "dummy-content"); err != nil {
    45  		panic(err)
    46  	}
    47  	if err := writer.Close(); err != nil {
    48  		panic(err)
    49  	}
    50  
    51  	return body.String(), writer.FormDataContentType()
    52  }
    53  
    54  // NewValidator creates a new Validator that validates PyPI API Tokens by
    55  // attempting to upload a dummy package to PyPI.
    56  // It performs a POST request to the PyPI legacy upload URL with multipart form data
    57  // using the API token in the Authorization header. If the request returns
    58  // HTTP 400 Bad Request, the key is considered valid.
    59  // If HTTP 403 Forbidden, the key is considered invalid.
    60  // Other errors return ValidationFailed.
    61  // We send an invalid package to not add any new package to the account.
    62  func NewValidator() *simplevalidate.Validator[PyPIAPIToken] {
    63  	body, contentType := mustCreateBodyAndContentType()
    64  	return &simplevalidate.Validator[PyPIAPIToken]{
    65  		Endpoint:   pypiUploadURL,
    66  		HTTPMethod: http.MethodPost,
    67  		HTTPHeaders: func(k PyPIAPIToken) map[string]string {
    68  			return map[string]string{
    69  				"Authorization": "token " + k.Token,
    70  				"Content-Type":  contentType,
    71  			}
    72  		},
    73  		Body: func(PyPIAPIToken) (string, error) {
    74  			return body, nil
    75  		},
    76  		ValidResponseCodes:   []int{http.StatusBadRequest},
    77  		InvalidResponseCodes: []int{http.StatusForbidden},
    78  		HTTPC: &http.Client{
    79  			Timeout: validationTimeout,
    80  		},
    81  	}
    82  }