Skip to content

Commit 3f7c911

Browse files
Added RailwayApp detector
1 parent 0f427b3 commit 3f7c911

File tree

5 files changed

+434
-8
lines changed

5 files changed

+434
-8
lines changed
+172
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
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+
func (s Scanner) Description() string {
54+
return "Railway is a deployment platform designed to streamline the software development life-cycle, starting with instant deployments and effortless scale, extending to CI/CD integrations and built-in observability."
55+
}
56+
57+
// FromData will find and optionally verify SaladCloud API Key secrets in a given set of bytes.
58+
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
59+
dataStr := string(data)
60+
61+
// uniqueMatches will hold unique match values and ensure we only process unique matches found in the data string
62+
var uniqueMatches = make(map[string]bool)
63+
64+
for _, match := range apiToken.FindAllStringSubmatch(dataStr, -1) {
65+
if len(match) != 2 {
66+
continue
67+
}
68+
69+
uniqueMatches[strings.TrimSpace(match[1])] = true
70+
}
71+
72+
for match := range uniqueMatches {
73+
s1 := detectors.Result{
74+
DetectorType: detectorspb.DetectorType_RailwayApp,
75+
Raw: []byte(match),
76+
ExtraData: map[string]string{
77+
"rotation_guide": "https://howtorotate.com/docs/tutorials/railwayapp/",
78+
},
79+
}
80+
81+
if verify {
82+
client := s.getClient()
83+
isVerified, verificationErr := verifyRailwayApp(ctx, client, match)
84+
s1.Verified = isVerified
85+
s1.SetVerificationError(verificationErr)
86+
}
87+
88+
results = append(results, s1)
89+
}
90+
91+
return results, nil
92+
}
93+
94+
func (s Scanner) Type() detectorspb.DetectorType {
95+
return detectorspb.DetectorType_RailwayApp
96+
}
97+
98+
/*
99+
verifyRailwayApp verifies if the passed matched api key for railwayapp is active or not.
100+
docs: https://docs.railway.app/reference/public-api
101+
*/
102+
func verifyRailwayApp(ctx context.Context, client *http.Client, match string) (bool, error) {
103+
jsonPayload, err := getJSONPayload()
104+
if err != nil {
105+
return false, err
106+
}
107+
108+
req, err := http.NewRequestWithContext(ctx, "POST", "https://backboard.railway.app/graphql/v2", bytes.NewBuffer(jsonPayload))
109+
if err != nil {
110+
return false, err
111+
}
112+
113+
// set the required headers
114+
req.Header.Set("Content-Type", "application/json")
115+
req.Header.Set("Authorization", "Bearer "+match)
116+
117+
resp, err := client.Do(req)
118+
if err != nil {
119+
return false, err
120+
}
121+
defer resp.Body.Close()
122+
123+
/*
124+
GraphQL queries return response with 200 OK status code even for errors
125+
Sources:
126+
https://www.apollographql.com/docs/react/data/error-handling/#graphql-errors
127+
https://github.com/rmosolgo/graphql-ruby/issues/1130
128+
https://inigo.io/blog/graphql_error_handling
129+
*/
130+
if resp.StatusCode != http.StatusOK {
131+
return false, fmt.Errorf("railway app verification failed with status code %d", resp.StatusCode)
132+
}
133+
134+
// if rate limit is reached, return verification as false with no error
135+
if resp.Header.Get("x-ratelimit-remaining") == "0" {
136+
return false, nil
137+
}
138+
139+
// read the response body
140+
body, err := io.ReadAll(resp.Body)
141+
if err != nil {
142+
return false, err
143+
}
144+
145+
// parse the response body into a structured format
146+
var graphqlResponse graphQLResponse
147+
if err = json.Unmarshal(body, &graphqlResponse); err != nil {
148+
return false, err
149+
}
150+
151+
// if any errors exist in response, return verification as false
152+
if len(graphqlResponse.Errors) > 0 {
153+
return false, nil
154+
}
155+
156+
return true, nil
157+
}
158+
159+
// getJSONPayload return the graphQL query as a JSON
160+
func getJSONPayload() ([]byte, error) {
161+
payload := map[string]string{
162+
"query": `query me {me {email}}`,
163+
}
164+
165+
// convert the payload to JSON
166+
jsonPayload, err := json.Marshal(payload)
167+
if err != nil {
168+
return nil, fmt.Errorf("error marshalling JSON: %w", err)
169+
}
170+
171+
return jsonPayload, nil
172+
}

0 commit comments

Comments
 (0)