github.com/google/osv-scalibr@v0.4.1/veles/secrets/cratesioapitoken/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 cratesioapitoken 16 17 import ( 18 "encoding/json" 19 "net/http" 20 21 "github.com/google/osv-scalibr/veles/secrets/common/simplevalidate" 22 ) 23 24 const ( 25 randomCrateName = "osvscalibr361aa9c83e8d69e1" 26 randomUserName = "velesvalidationtestuser" 27 // We need to use a random crate name that is unlikely to exist. 28 endpointURL = "https://crates.io/api/v1/crates/" + randomCrateName + "/owners" 29 ) 30 31 // NewValidator creates a new Validator that validates the CratesIOAPIToken via 32 // the Crates.io API endpoint. 33 // 34 // It performs a PUT request to the Crates.io API endpoint to add an owner to 35 // a non-existent crate using the API key in the Authorization header. 36 // Valid tokens return 404 Not Found, while invalid tokens return 403 Forbidden. 37 func NewValidator() *simplevalidate.Validator[CratesIOAPItoken] { 38 return &simplevalidate.Validator[CratesIOAPItoken]{ 39 Endpoint: endpointURL, 40 HTTPMethod: http.MethodPut, 41 HTTPHeaders: func(key CratesIOAPItoken) map[string]string { 42 return map[string]string{ 43 "Authorization": "Bearer " + key.Token, 44 "Content-Type": "application/json", 45 } 46 }, 47 Body: buildRequestBody, 48 ValidResponseCodes: []int{http.StatusNotFound}, 49 InvalidResponseCodes: []int{http.StatusForbidden}, 50 } 51 } 52 53 func buildRequestBody(key CratesIOAPItoken) (string, error) { 54 payload := map[string][]string{ 55 "users": {randomUserName}, 56 } 57 jsonData, err := json.Marshal(payload) 58 if err != nil { 59 return "", err 60 } 61 return string(jsonData), nil 62 }