Skip to content

Commit 10f5d79

Browse files
Added new detector for railwayApp
1 parent 0f427b3 commit 10f5d79

File tree

5 files changed

+420
-8
lines changed

5 files changed

+420
-8
lines changed
+168
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
package railwayapp
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"io"
9+
"net/http"
10+
"strings"
11+
12+
regexp "github.com/wasilibs/go-re2"
13+
14+
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
15+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
16+
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
17+
)
18+
19+
type Scanner struct {
20+
client *http.Client
21+
}
22+
23+
// graphQLResponse will handle the response from railway API
24+
type graphQLResponse struct {
25+
Data interface{} `json:"data"`
26+
Errors []interface{} `json:"errors"`
27+
}
28+
29+
// Ensure the Scanner satisfies the interface at compile time.
30+
var _ detectors.Detector = (*Scanner)(nil)
31+
32+
var (
33+
defaultClient = common.SaneHttpClient()
34+
35+
apiToken = regexp.MustCompile(detectors.PrefixRegex([]string{"railwayapp", "railway"}) +
36+
`\b([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})\b`)
37+
)
38+
39+
func (s Scanner) getClient() *http.Client {
40+
if s.client != nil {
41+
return s.client
42+
}
43+
44+
return defaultClient
45+
}
46+
47+
// Keywords are used for efficiently pre-filtering chunks.
48+
// Use identifiers in the secret preferably, or the provider name.
49+
func (s Scanner) Keywords() []string {
50+
return []string{"railwayapp", "railway"}
51+
}
52+
53+
// FromData will find and optionally verify SaladCloud API Key secrets in a given set of bytes.
54+
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
55+
dataStr := string(data)
56+
57+
// uniqueMatches will hold unique match values and ensure we only process unique matches found in the data string
58+
var uniqueMatches = make(map[string]bool)
59+
60+
for _, match := range apiToken.FindAllStringSubmatch(dataStr, -1) {
61+
if len(match) != 2 {
62+
continue
63+
}
64+
65+
uniqueMatches[strings.TrimSpace(match[1])] = true
66+
}
67+
68+
for match := range uniqueMatches {
69+
s1 := detectors.Result{
70+
DetectorType: detectorspb.DetectorType_RailwayApp,
71+
Raw: []byte(match),
72+
ExtraData: map[string]string{
73+
"rotation_guide": "https://howtorotate.com/docs/tutorials/railwayapp/",
74+
},
75+
}
76+
77+
if verify {
78+
client := s.getClient()
79+
isVerified, verificationErr := verifyRailwayApp(ctx, client, match)
80+
s1.Verified = isVerified
81+
s1.SetVerificationError(verificationErr)
82+
}
83+
84+
results = append(results, s1)
85+
}
86+
87+
return results, nil
88+
}
89+
90+
func (s Scanner) Type() detectorspb.DetectorType {
91+
return detectorspb.DetectorType_RailwayApp
92+
}
93+
94+
/*
95+
verifyRailwayApp verifies if the passed matched api key for railwayapp is active or not.
96+
docs: https://docs.railway.app/reference/public-api
97+
*/
98+
func verifyRailwayApp(ctx context.Context, client *http.Client, match string) (bool, error) {
99+
jsonPayload, err := getJSONPayload()
100+
if err != nil {
101+
return false, err
102+
}
103+
104+
req, err := http.NewRequestWithContext(ctx, "POST", "https://backboard.railway.app/graphql/v2", bytes.NewBuffer(jsonPayload))
105+
if err != nil {
106+
return false, err
107+
}
108+
109+
// set the required headers
110+
req.Header.Set("Content-Type", "application/json")
111+
req.Header.Set("Authorization", "Bearer "+match)
112+
113+
resp, err := client.Do(req)
114+
if err != nil {
115+
return false, err
116+
}
117+
defer resp.Body.Close()
118+
119+
/*
120+
GraphQL queries return response with 200 OK status code even for errors
121+
Sources:
122+
https://www.apollographql.com/docs/react/data/error-handling/#graphql-errors
123+
https://github.com/rmosolgo/graphql-ruby/issues/1130
124+
https://inigo.io/blog/graphql_error_handling
125+
*/
126+
if resp.StatusCode != http.StatusOK {
127+
return false, fmt.Errorf("railway app verification failed with status code %d", resp.StatusCode)
128+
}
129+
130+
// if rate limit is reached, return verification as false with no error
131+
if resp.Header.Get("x-ratelimit-remaining") == "0" {
132+
return false, nil
133+
}
134+
135+
// read the response body
136+
body, err := io.ReadAll(resp.Body)
137+
if err != nil {
138+
return false, err
139+
}
140+
141+
// parse the response body into a structured format
142+
var graphqlResponse graphQLResponse
143+
if err = json.Unmarshal(body, &graphqlResponse); err != nil {
144+
return false, err
145+
}
146+
147+
// if any errors exist in response, return verification as false
148+
if len(graphqlResponse.Errors) > 0 {
149+
return false, nil
150+
}
151+
152+
return true, nil
153+
}
154+
155+
// getJSONPayload return the graphQL query as a JSON
156+
func getJSONPayload() ([]byte, error) {
157+
payload := map[string]string{
158+
"query": `query me {me {email}}`,
159+
}
160+
161+
// convert the payload to JSON
162+
jsonPayload, err := json.Marshal(payload)
163+
if err != nil {
164+
return nil, fmt.Errorf("error marshalling JSON: %w", err)
165+
}
166+
167+
return jsonPayload, nil
168+
}

0 commit comments

Comments
 (0)