code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
func (ns *nodeServer) prepareSessMgr(workDir string) error {
sessMgrLabelKey := common.SessMgrNodeSelectorKey
var labelsToModify common.LabelsToModify
labelsToModify.Add(sessMgrLabelKey, "true")
node, err := ns.getNode()
if err != nil {
return errors.Wrapf(err, "can't get node %s", ns.nodeId)
}
_, err = utils.ChangeNodeLabelWithPatchMode(ns.client, node, labelsToModify)
if err != nil {
return errors.Wrapf(err, "error when patching labels on node %s", ns.nodeId)
}
// check sessmgrd.sock file existence
sessMgrSockFilePath := filepath.Join(workDir, common.SessMgrSockFile)
glog.Infof("Checking existence of file %s", sessMgrSockFilePath)
retryLimit := 30
var i int
for i = 0; i < retryLimit; i++ {
if _, err := os.Stat(sessMgrSockFilePath); err == nil {
break
}
// err != nil
if !os.IsNotExist(err) {
glog.Errorf("fail to os.Stat sessmgr socket file %s", sessMgrSockFilePath)
}
time.Sleep(1 * time.Second)
}
if i >= retryLimit {
return errors.New("timeout waiting for SessMgr Pod to be ready")
}
return nil
} | 0 | Go | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func (ns *nodeServer) getNode() (node *v1.Node, err error) {
// Default to allow patch stale node info
if envVar, found := os.LookupEnv(AllowPatchStaleNodeEnv); !found || envVar == "true" {
if ns.node != nil {
glog.V(3).Infof("Found cached node %s", ns.node.Name)
return ns.node, nil
}
}
if node, err = kubeclient.GetNode(ns.apiReader, ns.nodeId); err != nil {
return nil, err
}
glog.V(1).Infof("Got node %s from api server", node.Name)
ns.node = node
return ns.node, nil
} | 0 | Go | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func Register(mgr manager.Manager, cfg config.Config) error {
csiDriver := NewDriver(cfg.NodeId, cfg.Endpoint, mgr.GetClient(), mgr.GetAPIReader())
if err := mgr.Add(csiDriver); err != nil {
return err
}
return nil
} | 0 | Go | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func AccountPostLogin(w http.ResponseWriter, r *http.Request) {
account, err := (&models.Account{Context: ctx.Context}).FromBody(r)
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
var a1 = &models.Account{Context: ctx.Context}
a1.FromData(account)
a1, err = a1.Get()
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
account, err = a1.ValidatePassword(account.Password, "Password")
if err != nil {
ctx.HandleStatus(w, r, "Invalid username or password!", http.StatusForbidden)
return
}
session, err := (&models.Session{Context: ctx.Context, Unique: account.Unique}).Post()
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
expiry := time.Now().Add(time.Hour * 15) // TODO: Change this once we've implemented refreshing
SetAuthCookie(w, types.CookieSessionID, session.Key.ID.String(), expiry)
SetAuthCookie(w, types.CookieRefreshToken, session.Refresh, expiry)
ctx.HandleJson(w, r, account.CopyPublic(), http.StatusOK)
} | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
func authenticateDNSToken(tokenString string) bool {
tokens := strings.Split(tokenString, " ")
if len(tokens) < 2 {
return false
}
return tokens[1] == servercfg.GetDNSKey()
} | 0 | Go | CWE-798 | Use of Hard-coded Credentials | The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data. | https://cwe.mitre.org/data/definitions/798.html | vulnerable |
func GetDNSKey() string {
key := "secretkey"
if os.Getenv("DNS_KEY") != "" {
key = os.Getenv("DNS_KEY")
} else if config.Config.Server.DNSKey != "" {
key = config.Config.Server.DNSKey
}
return key
} | 0 | Go | CWE-798 | Use of Hard-coded Credentials | The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data. | https://cwe.mitre.org/data/definitions/798.html | vulnerable |
eg.Go(func() error {
var err error
policyOutput, err = policyEvaluator.Evaluate(ectx, &PolicyRequest{
HTTP: req.HTTP,
Session: req.Session,
IsValidClientCertificate: isValidClientCertificate,
})
return err
}) | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func NewHeadersRequestFromPolicy(policy *config.Policy, hostname string) *HeadersRequest {
input := new(HeadersRequest)
input.EnableGoogleCloudServerlessAuthentication = policy.EnableGoogleCloudServerlessAuthentication
input.EnableRoutingKey = policy.EnvoyOpts.GetLbPolicy() == envoy_config_cluster_v3.Cluster_RING_HASH ||
policy.EnvoyOpts.GetLbPolicy() == envoy_config_cluster_v3.Cluster_MAGLEV
input.Issuer = hostname
input.KubernetesServiceAccountToken = policy.KubernetesServiceAccountToken
for _, wu := range policy.To {
input.ToAudience = "https://" + wu.URL.Hostname()
}
input.PassAccessToken = policy.GetSetAuthorizationHeader() == configpb.Route_ACCESS_TOKEN
input.PassIDToken = policy.GetSetAuthorizationHeader() == configpb.Route_ID_TOKEN
return input
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (a *Authorize) getMatchingPolicy(requestURL url.URL) *config.Policy {
options := a.currentOptions.Load()
for _, p := range options.GetAllPolicies() {
if p.Matches(requestURL) {
return &p
}
}
return nil
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (a *Authorize) getEvaluatorRequestFromCheckRequest(
in *envoy_service_auth_v3.CheckRequest,
sessionState *sessions.State,
) (*evaluator.Request, error) {
requestURL := getCheckRequestURL(in)
req := &evaluator.Request{
HTTP: evaluator.NewRequestHTTP(
in.GetAttributes().GetRequest().GetHttp().GetMethod(),
requestURL,
getCheckRequestHeaders(in),
getPeerCertificate(in),
in.GetAttributes().GetSource().GetAddress().GetSocketAddress().GetAddress(),
),
}
if sessionState != nil {
req.Session = evaluator.RequestSession{
ID: sessionState.ID,
}
}
req.Policy = a.getMatchingPolicy(requestURL)
return req, nil
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func init() {
disableExtAuthz = marshalAny(&envoy_extensions_filters_http_ext_authz_v3.ExtAuthzPerRoute{
Override: &envoy_extensions_filters_http_ext_authz_v3.ExtAuthzPerRoute_Disabled{
Disabled: true,
},
})
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (b *Builder) buildControlPlanePrefixRoute(
options *config.Options,
prefix string,
protected bool,
requireStrictTransportSecurity bool,
) *envoy_config_route_v3.Route {
r := &envoy_config_route_v3.Route{
Name: "pomerium-prefix-" + prefix,
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: prefix},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: httpCluster,
},
},
},
ResponseHeadersToAdd: toEnvoyHeaders(options.GetSetResponseHeaders(requireStrictTransportSecurity)),
}
if !protected {
r.TypedPerFilterConfig = map[string]*any.Any{
"envoy.filters.http.ext_authz": disableExtAuthz,
}
}
return r
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (b *Builder) buildControlPlanePathRoute(
options *config.Options,
path string,
protected bool,
requireStrictTransportSecurity bool,
) *envoy_config_route_v3.Route {
r := &envoy_config_route_v3.Route{
Name: "pomerium-path-" + path,
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: httpCluster,
},
},
},
ResponseHeadersToAdd: toEnvoyHeaders(options.GetSetResponseHeaders(requireStrictTransportSecurity)),
}
if !protected {
r.TypedPerFilterConfig = map[string]*any.Any{
"envoy.filters.http.ext_authz": disableExtAuthz,
}
}
return r
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (b *Builder) buildPomeriumAuthenticateHTTPRoutes(
options *config.Options,
host string,
requireStrictTransportSecurity bool,
) ([]*envoy_config_route_v3.Route, error) {
if !config.IsAuthenticate(options.Services) {
return nil, nil
}
for _, fn := range []func() (*url.URL, error){
options.GetAuthenticateURL,
options.GetInternalAuthenticateURL,
} {
u, err := fn()
if err != nil {
return nil, err
}
if urlMatchesHost(u, host) {
return []*envoy_config_route_v3.Route{
b.buildControlPlanePathRoute(options, options.AuthenticateCallbackPath, false, requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/", false, requireStrictTransportSecurity),
}, nil
}
}
return nil, nil
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (b *Builder) buildPomeriumHTTPRoutes(
options *config.Options,
host string,
requireStrictTransportSecurity bool,
) ([]*envoy_config_route_v3.Route, error) {
var routes []*envoy_config_route_v3.Route
// if this is the pomerium proxy in front of the the authenticate service, don't add
// these routes since they will be handled by authenticate
isFrontingAuthenticate, err := isProxyFrontingAuthenticate(options, host)
if err != nil {
return nil, err
}
if !isFrontingAuthenticate {
routes = append(routes,
// enable ext_authz
b.buildControlPlanePathRoute(options, "/.pomerium/jwt", true, requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, urlutil.WebAuthnURLPath, true, requireStrictTransportSecurity),
// disable ext_authz and passthrough to proxy handlers
b.buildControlPlanePathRoute(options, "/ping", false, requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/healthz", false, requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/.pomerium", false, requireStrictTransportSecurity),
b.buildControlPlanePrefixRoute(options, "/.pomerium/", false, requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/.well-known/pomerium", false, requireStrictTransportSecurity),
b.buildControlPlanePrefixRoute(options, "/.well-known/pomerium/", false, requireStrictTransportSecurity),
)
// per #837, only add robots.txt if there are no unauthenticated routes
if !hasPublicPolicyMatchingURL(options, url.URL{Scheme: "https", Host: host, Path: "/robots.txt"}) {
routes = append(routes, b.buildControlPlanePathRoute(options, "/robots.txt", false, requireStrictTransportSecurity))
}
}
authRoutes, err := b.buildPomeriumAuthenticateHTTPRoutes(options, host, requireStrictTransportSecurity)
if err != nil {
return nil, err
}
routes = append(routes, authRoutes...)
return routes, nil
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (b *Builder) buildGRPCRoutes() ([]*envoy_config_route_v3.Route, error) {
action := &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: "pomerium-control-plane-grpc",
},
},
}
return []*envoy_config_route_v3.Route{{
Name: "pomerium-grpc",
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{
Prefix: "/",
},
Grpc: &envoy_config_route_v3.RouteMatch_GrpcRouteMatchOptions{},
},
Action: action,
TypedPerFilterConfig: map[string]*any.Any{
"envoy.filters.http.ext_authz": disableExtAuthz,
},
}}, nil
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func Test_buildControlPlanePathRoute(t *testing.T) {
options := config.NewDefaultOptions()
b := &Builder{filemgr: filemgr.NewManager()}
route := b.buildControlPlanePathRoute(options, "/hello/world", false, false)
testutil.AssertProtoJSONEqual(t, `
{
"name": "pomerium-path-/hello/world",
"match": {
"path": "/hello/world"
},
"responseHeadersToAdd": [
{
"appendAction": "OVERWRITE_IF_EXISTS_OR_ADD",
"header": {
"key": "X-Frame-Options",
"value": "SAMEORIGIN"
}
},
{
"appendAction": "OVERWRITE_IF_EXISTS_OR_ADD",
"header": {
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
}
],
"route": {
"cluster": "pomerium-control-plane-http"
},
"typedPerFilterConfig": {
"envoy.filters.http.ext_authz": {
"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
"disabled": true
}
}
}
`, route)
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func Test_buildControlPlanePrefixRoute(t *testing.T) {
options := config.NewDefaultOptions()
b := &Builder{filemgr: filemgr.NewManager()}
route := b.buildControlPlanePrefixRoute(options, "/hello/world/", false, false)
testutil.AssertProtoJSONEqual(t, `
{
"name": "pomerium-prefix-/hello/world/",
"match": {
"prefix": "/hello/world/"
},
"responseHeadersToAdd": [
{
"appendAction": "OVERWRITE_IF_EXISTS_OR_ADD",
"header": {
"key": "X-Frame-Options",
"value": "SAMEORIGIN"
}
},
{
"appendAction": "OVERWRITE_IF_EXISTS_OR_ADD",
"header": {
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
}
],
"route": {
"cluster": "pomerium-control-plane-http"
},
"typedPerFilterConfig": {
"envoy.filters.http.ext_authz": {
"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
"disabled": true
}
}
}
`, route)
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
func (p *Policy) ToPPL() *parser.Policy {
ppl := &parser.Policy{}
allowRule := parser.Rule{Action: parser.ActionAllow}
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "pomerium_routes",
})
if p.AllowPublicUnauthenticatedAccess {
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "accept",
Data: parser.Boolean(true),
})
}
if p.CORSAllowPreflight {
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "cors_preflight",
Data: parser.Boolean(true),
})
}
if p.AllowAnyAuthenticatedUser {
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "authenticated_user",
Data: parser.Boolean(true),
})
}
for _, ad := range p.AllAllowedDomains() {
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "domain",
Data: parser.Object{
"is": parser.String(ad),
},
})
}
for _, aic := range p.AllAllowedIDPClaims() {
var ks []string
for k := range aic {
ks = append(ks, k)
}
sort.Strings(ks)
for _, k := range ks {
for _, v := range aic[k] {
bs, _ := json.Marshal(v)
data, _ := parser.ParseValue(bytes.NewReader(bs))
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "claim",
SubPath: k,
Data: data,
})
}
}
}
for _, au := range p.AllAllowedUsers() {
allowRule.Or = append(allowRule.Or,
parser.Criterion{
Name: "user",
Data: parser.Object{
"is": parser.String(au),
},
},
parser.Criterion{
Name: "email",
Data: parser.Object{
"is": parser.String(au),
},
})
}
ppl.Rules = append(ppl.Rules, allowRule)
denyRule := parser.Rule{Action: parser.ActionDeny}
denyRule.Or = append(denyRule.Or,
parser.Criterion{
Name: "invalid_client_certificate",
})
ppl.Rules = append(ppl.Rules, denyRule)
// append embedded PPL policy rules
if p.Policy != nil && p.Policy.Policy != nil {
ppl.Rules = append(ppl.Rules, p.Policy.Policy.Rules...)
}
return ppl
} | 0 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
err = sigRepo.ListSignatures(ctx, manifestDesc, func(signatureManifests []ocispec.Descriptor) error {
for _, sigManifestDesc := range signatureManifests {
sigBlob, sigDesc, err := sigRepo.FetchSignatureBlob(ctx, sigManifestDesc)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: unable to fetch signature %s due to error: %v\n", sigManifestDesc.Digest.String(), err)
skippedSignatures = true
continue
}
sigEnvelope, err := signature.ParseEnvelope(sigDesc.MediaType, sigBlob)
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
continue
}
envelopeContent, err := sigEnvelope.Content()
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
continue
}
signedArtifactDesc, err := envelope.DescriptorFromSignaturePayload(&envelopeContent.Payload)
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
continue
}
signatureAlgorithm, err := proto.EncodeSigningAlgorithm(envelopeContent.SignerInfo.SignatureAlgorithm)
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
continue
}
sig := signatureOutput{
MediaType: sigDesc.MediaType,
Digest: sigManifestDesc.Digest.String(),
SignatureAlgorithm: string(signatureAlgorithm),
SignedAttributes: getSignedAttributes(opts.outputFormat, envelopeContent),
UserDefinedAttributes: signedArtifactDesc.Annotations,
UnsignedAttributes: getUnsignedAttributes(envelopeContent),
Certificates: getCertificates(opts.outputFormat, envelopeContent),
SignedArtifact: *signedArtifactDesc,
}
// clearing annotations from the SignedArtifact field since they're already
// displayed as UserDefinedAttributes
sig.SignedArtifact.Annotations = nil
output.Signatures = append(output.Signatures, sig)
}
return nil
}) | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func TestInspectCommand_SecretsFromArgs(t *testing.T) {
opts := &inspectOpts{}
command := inspectCommand(opts)
expected := &inspectOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Password: "password",
InsecureRegistry: true,
Username: "user",
},
outputFormat: cmd.OutputPlaintext,
}
if err := command.ParseFlags([]string{
"--password", expected.Password,
expected.reference,
"-u", expected.Username,
"--insecure-registry",
"--output", "text"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse Args failed: %v", err)
}
if *opts != *expected {
t.Fatalf("Expect inspect opts: %v, got: %v", expected, opts)
}
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func TestInspectCommand_SecretsFromEnv(t *testing.T) {
t.Setenv(defaultUsernameEnv, "user")
t.Setenv(defaultPasswordEnv, "password")
opts := &inspectOpts{}
expected := &inspectOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Password: "password",
Username: "user",
},
outputFormat: cmd.OutputJSON,
}
command := inspectCommand(opts)
if err := command.ParseFlags([]string{
expected.reference,
"--output", "json"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse Args failed: %v", err)
}
if *opts != *expected {
t.Fatalf("Expect inspect opts: %v, got: %v", expected, opts)
}
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func runList(ctx context.Context, opts *listOpts) error {
// set log level
ctx = opts.LoggingFlagOpts.SetLoggerLevel(ctx)
// initialize
reference := opts.reference
sigRepo, err := getRepository(ctx, opts.inputType, reference, &opts.SecureFlagOpts, opts.allowReferrersAPI)
if err != nil {
return err
}
targetDesc, resolvedRef, err := resolveReferenceWithWarning(ctx, opts.inputType, reference, sigRepo, "list")
if err != nil {
return err
}
// print all signature manifest digests
return printSignatureManifestDigests(ctx, targetDesc, sigRepo, resolvedRef)
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
err := sigRepo.ListSignatures(ctx, targetDesc, func(signatureManifests []ocispec.Descriptor) error {
for _, sigManifestDesc := range signatureManifests {
if prevDigest != "" {
// check and print title
printTitle()
// print each signature digest
fmt.Printf(" ├── %s\n", prevDigest)
}
prevDigest = sigManifestDesc.Digest
}
return nil
}) | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func runVerify(command *cobra.Command, opts *verifyOpts) error {
// set log level
ctx := opts.LoggingFlagOpts.SetLoggerLevel(command.Context())
// initialize
sigVerifier, err := verifier.NewFromConfig()
if err != nil {
return err
}
// set up verification plugin config.
configs, err := cmd.ParseFlagMap(opts.pluginConfig, cmd.PflagPluginConfig.Name)
if err != nil {
return err
}
// set up user metadata
userMetadata, err := cmd.ParseFlagMap(opts.userMetadata, cmd.PflagUserMetadata.Name)
if err != nil {
return err
}
// core verify process
reference := opts.reference
sigRepo, err := getRepository(ctx, opts.inputType, reference, &opts.SecureFlagOpts, opts.allowReferrersAPI)
if err != nil {
return err
}
// resolve the given reference and set the digest
_, resolvedRef, err := resolveReferenceWithWarning(ctx, opts.inputType, reference, sigRepo, "verify")
if err != nil {
return err
}
intendedRef := resolveArtifactDigestReference(resolvedRef, opts.trustPolicyScope)
verifyOpts := notation.VerifyOptions{
ArtifactReference: intendedRef,
PluginConfig: configs,
// TODO: need to change MaxSignatureAttempts as a user input flag or
// a field in config.json
MaxSignatureAttempts: maxSignatureAttempts,
UserMetadata: userMetadata,
}
_, outcomes, err := notation.Verify(ctx, sigVerifier, sigRepo, verifyOpts)
err = checkVerificationFailure(outcomes, resolvedRef, err)
if err != nil {
return err
}
reportVerificationSuccess(outcomes, resolvedRef)
return nil
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func TestVerifyCommand_BasicArgs(t *testing.T) {
opts := &verifyOpts{}
command := verifyCommand(opts)
expected := &verifyOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Username: "user",
Password: "password",
},
pluginConfig: []string{"key1=val1"},
}
if err := command.ParseFlags([]string{
expected.reference,
"--username", expected.Username,
"--password", expected.Password,
"--plugin-config", "key1=val1"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse args failed: %v", err)
}
if !reflect.DeepEqual(*expected, *opts) {
t.Fatalf("Expect verify opts: %v, got: %v", expected, opts)
}
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func TestVerifyCommand_MoreArgs(t *testing.T) {
opts := &verifyOpts{}
command := verifyCommand(opts)
expected := &verifyOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
InsecureRegistry: true,
},
pluginConfig: []string{"key1=val1", "key2=val2"},
}
if err := command.ParseFlags([]string{
expected.reference,
"--insecure-registry",
"--plugin-config", "key1=val1",
"--plugin-config", "key2=val2"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse args failed: %v", err)
}
if !reflect.DeepEqual(*expected, *opts) {
t.Fatalf("Expect verify opts: %v, got: %v", expected, opts)
}
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func NewQUICServer(addr, password, domain string, tcpTimeout, udpTimeout int, blockDomainList, blockCIDR4List, blockCIDR6List string, updateListInterval int64, blockGeoIP []string, withoutbrook bool) (*QUICServer, error) {
if err := limits.Raise(); err != nil {
Log(&Error{"when": "try to raise system limits", "warning": err.Error()})
}
if runtime.GOOS == "linux" {
c := exec.Command("sysctl", "-w", "net.core.rmem_max=2500000")
b, err := c.CombinedOutput()
if err != nil {
Log(&Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
if runtime.GOOS == "darwin" {
c := exec.Command("sysctl", "-w", "kern.ipc.maxsockbuf=3014656")
b, err := c.CombinedOutput()
if err != nil {
Log(&Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
var p []byte
var f UDPServerConnFactory
if !withoutbrook {
p = []byte(password)
f = NewPacketServerConnFactory()
}
if withoutbrook {
var err error
p, err = crypto1.SHA256Bytes([]byte(password))
if err != nil {
return nil, err
}
f = NewSimplePacketServerConnFactory()
}
s := &QUICServer{
Password: p,
Domain: domain,
Addr: addr,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
UDPServerConnFactory: f,
RunnerGroup: runnergroup.New(),
WithoutBrook: withoutbrook,
}
return s, nil
} | 0 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
func (c *StreamClient) Exchange(local net.Conn) error {
go func() {
for {
if c.Timeout != 0 {
if err := c.Server.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return
}
}
l, err := c.ReadL()
if err != nil {
return
}
if _, err := local.Write(c.RB[2+16 : 2+16+l]); err != nil {
return
}
}
}()
for {
if c.Timeout != 0 {
if err := local.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := local.Read(c.WB[2+16 : len(c.WB)-16])
if err != nil {
return nil
}
if err := c.WriteL(l); err != nil {
return nil
}
}
return nil
} | 0 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
func (c *StreamClient) ReadL() (int, error) {
if _, err := io.ReadFull(c.Server, c.RB[:2+16]); err != nil {
return 0, err
}
if _, err := c.sa.Open(c.RB[:0], c.sn, c.RB[:2+16], nil); err != nil {
return 0, err
}
l := int(binary.BigEndian.Uint16(c.RB[:2]))
if _, err := io.ReadFull(c.Server, c.RB[2+16:2+16+l+16]); err != nil {
return 0, err
}
NextNonce(c.sn)
if _, err := c.sa.Open(c.RB[:2+16], c.sn, c.RB[2+16:2+16+l+16], nil); err != nil {
return 0, err
}
NextNonce(c.sn)
return l, nil
} | 0 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
func (c *StreamClient) WriteL(l int) error {
binary.BigEndian.PutUint16(c.WB[:2], uint16(l))
c.ca.Seal(c.WB[:0], c.cn, c.WB[:2], nil)
NextNonce(c.cn)
c.ca.Seal(c.WB[:2+16], c.cn, c.WB[2+16:2+16+l], nil)
if _, err := c.Server.Write(c.WB[:2+16+l+16]); err != nil {
return err
}
NextNonce(c.cn)
return nil
} | 0 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
func (r *MySQL) Probe() (bool, string) {
if r.tls != nil {
mysql.RegisterTLSConfig(global.DefaultProg, r.tls)
}
db, err := sql.Open("mysql", r.ConnStr)
if err != nil {
return false, err.Error()
}
defer db.Close()
// Check if we need to query specific data
if len(r.Data) > 0 {
for k, v := range r.Data {
log.Debugf("[%s / %s / %s] - Verifying Data - [%s] : [%s]", r.ProbeKind, r.ProbeName, r.ProbeTag, k, v)
sql, err := r.getSQL(k)
if err != nil {
return false, err.Error()
}
log.Debugf("[%s / %s / %s] - SQL - [%s]", r.ProbeKind, r.ProbeName, r.ProbeTag, sql)
rows, err := db.Query(sql)
if err != nil {
return false, err.Error()
}
if !rows.Next() {
rows.Close()
return false, fmt.Sprintf("No data found for [%s]", k)
}
//check the value is equal to the value in data
var value string
if err := rows.Scan(&value); err != nil {
rows.Close()
return false, err.Error()
}
if value != v {
rows.Close()
return false, fmt.Sprintf("Value not match for [%s] expected [%s] got [%s] ", k, v, value)
}
rows.Close()
log.Debugf("[%s / %s / %s] - Data Verified Successfully! - [%s] : [%s]", r.ProbeKind, r.ProbeName, r.ProbeTag, k, v)
}
} else {
err = db.Ping()
if err != nil {
return false, err.Error()
}
row, err := db.Query("show status like \"uptime\"") // run a SQL to test
if err != nil {
return false, err.Error()
}
defer row.Close()
}
return true, "Check MySQL Server Successfully!"
} | 0 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
func (r *MySQL) getSQL(str string) (string, error) {
if len(strings.TrimSpace(str)) == 0 {
return "", fmt.Errorf("Empty SQL data")
}
fields := strings.Split(str, ":")
if len(fields) != 5 {
return "", fmt.Errorf("Invalid SQL data - [%s]. (syntax: database:table:field:key:value)", str)
}
db := fields[0]
table := fields[1]
field := fields[2]
key := fields[3]
value := fields[4]
//check value is int or not
if _, err := strconv.Atoi(value); err != nil {
return "", fmt.Errorf("Invalid SQL data - [%s], the value must be int", str)
}
sql := fmt.Sprintf("SELECT %s FROM %s.%s WHERE %s = %s", field, db, table, key, value)
return sql, nil
} | 0 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
func (r *PostgreSQL) getSQL(str string) (string, string, error) {
if len(strings.TrimSpace(str)) == 0 {
return "", "", fmt.Errorf("Empty SQL data")
}
fields := strings.Split(str, ":")
if len(fields) != 5 {
return "", "", fmt.Errorf("Invalid SQL data - [%s]. (syntax: database:table:field:key:value)", str)
}
db := fields[0]
table := fields[1]
field := fields[2]
key := fields[3]
value := fields[4]
//check value is int or not
if _, err := strconv.Atoi(value); err != nil {
return "", "", fmt.Errorf("Invalid SQL data - [%s], the value must be int", str)
}
sql := fmt.Sprintf("SELECT %s FROM %s WHERE %s = %s", field, table, key, value)
return db, sql, nil
} | 0 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
func (v *SnapshotJob) do(ffmpegPath, inputUrl string) (err error) {
outputPicDir := path.Join(StaticDir, v.App)
if err = os.MkdirAll(outputPicDir, 0777); err != nil {
log.Println(fmt.Sprintf("create snapshot image dir:%v failed, err is %v", outputPicDir, err))
return
}
normalPicPath := path.Join(outputPicDir, fmt.Sprintf("%v", v.Stream)+"-%03d.png")
bestPng := path.Join(outputPicDir, fmt.Sprintf("%v-best.png", v.Stream))
param := fmt.Sprintf("%v -i %v -vf fps=1 -vcodec png -f image2 -an -y -vframes %v -y %v", ffmpegPath, inputUrl, v.vframes, normalPicPath)
log.Println(fmt.Sprintf("start snapshot, cmd param=%v", param))
timeoutCtx, _ := context.WithTimeout(v.cancelCtx, v.timeout)
cmd := exec.CommandContext(timeoutCtx, "/bin/bash", "-c", param)
if err = cmd.Run(); err != nil {
log.Println(fmt.Sprintf("run snapshot %v cmd failed, err is %v", v.Tag(), err))
return
}
bestFileSize := int64(0)
for i := 1; i <= v.vframes; i++ {
pic := path.Join(outputPicDir, fmt.Sprintf("%v-%03d.png", v.Stream, i))
fi, err := os.Stat(pic)
if err != nil {
log.Println(fmt.Sprintf("stat pic:%v failed, err is %v", pic, err))
continue
}
if bestFileSize == 0 {
bestFileSize = fi.Size()
} else if fi.Size() > bestFileSize {
os.Remove(bestPng)
os.Symlink(pic, bestPng)
bestFileSize = fi.Size()
}
}
log.Println(fmt.Sprintf("%v the best thumbnail is %v", v.Tag(), bestPng))
return
} | 0 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
func (r *TerraformRunnerServer) NewTerraform(ctx context.Context, req *NewTerraformRequest) (*NewTerraformReply, error) {
r.InstanceID = req.GetInstanceID()
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating new terraform", "workingDir", req.WorkingDir, "execPath", req.ExecPath)
tf, err := tfexec.NewTerraform(req.WorkingDir, req.ExecPath)
if err != nil {
log.Error(err, "unable to create new terraform", "workingDir", req.WorkingDir, "execPath", req.ExecPath)
return nil, err
}
// hold only 1 instance
r.tf = tf
var terraform infrav1.Terraform
if err := terraform.FromBytes(req.Terraform, r.Scheme); err != nil {
log.Error(err, "there was a problem getting the terraform resource")
return nil, err
}
// cache the Terraform resource when initializing
r.terraform = &terraform
disableTestLogging := os.Getenv("DISABLE_TF_LOGS") == "1"
if !disableTestLogging {
r.tf.SetStdout(os.Stdout)
r.tf.SetStderr(os.Stderr)
if os.Getenv("ENABLE_SENSITIVE_TF_LOGS") == "1" {
r.tf.SetLogger(&LocalPrintfer{logger: log})
}
}
return &NewTerraformReply{Id: r.InstanceID}, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (r *TerraformRunnerServer) Plan(ctx context.Context, req *PlanRequest) (*PlanReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating a plan")
ctx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-r.Done:
cancel()
case <-ctx.Done():
}
}()
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
var planOpt []tfexec.PlanOption
if req.Out != "" {
planOpt = append(planOpt, tfexec.Out(req.Out))
} else {
// if backend is disabled completely, there will be no plan output file (req.Out = "")
log.Info("backend seems to be disabled completely, so there will be no plan output file")
}
if req.Refresh == false {
planOpt = append(planOpt, tfexec.Refresh(req.Refresh))
}
if req.Destroy {
planOpt = append(planOpt, tfexec.Destroy(req.Destroy))
}
for _, target := range req.Targets {
planOpt = append(planOpt, tfexec.Target(target))
}
drifted, err := r.tf.Plan(ctx, planOpt...)
if err != nil {
st := status.New(codes.Internal, err.Error())
var stateErr *tfexec.ErrStateLocked
if errors.As(err, &stateErr) {
st, err = st.WithDetails(&PlanReply{Message: "not ok", StateLockIdentifier: stateErr.ID})
if err != nil {
return nil, err
}
}
log.Error(err, "error creating the plan")
return nil, st.Err()
}
planCreated := false
if req.Out != "" {
planCreated = true
plan, err := r.tf.ShowPlanFile(ctx, req.Out)
if err != nil {
return nil, err
}
// This is the case when the plan is empty.
if plan.PlannedValues.Outputs == nil &&
plan.PlannedValues.RootModule.Resources == nil &&
plan.ResourceChanges == nil &&
plan.PriorState == nil &&
plan.OutputChanges == nil {
planCreated = false
}
}
return &PlanReply{Message: "ok", Drifted: drifted, PlanCreated: planCreated}, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (r *TerraformRunnerServer) SaveTFPlan(ctx context.Context, req *SaveTFPlanRequest) (*SaveTFPlanReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("save the plan")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
var tfplan []byte
if req.BackendCompletelyDisable {
tfplan = []byte("dummy plan")
} else {
var err error
tfplan, err = ioutil.ReadFile(filepath.Join(r.tf.WorkingDir(), TFPlanName))
if err != nil {
err = fmt.Errorf("error reading plan file: %s", err)
log.Error(err, "unable to complete SaveTFPlan function")
return nil, err
}
}
planRev := strings.Replace(req.Revision, "/", "-", 1)
planName := "plan-" + planRev
if err := r.writePlanAsSecret(ctx, req.Name, req.Namespace, log, planName, tfplan, "", req.Uuid); err != nil {
return nil, err
}
if r.terraform.Spec.StoreReadablePlan == "json" {
planObj, err := r.tf.ShowPlanFile(ctx, TFPlanName)
if err != nil {
log.Error(err, "unable to get the plan output for json")
return nil, err
}
jsonBytes, err := json.Marshal(planObj)
if err != nil {
log.Error(err, "unable to marshal the plan to json")
return nil, err
}
if err := r.writePlanAsSecret(ctx, req.Name, req.Namespace, log, planName, jsonBytes, ".json", req.Uuid); err != nil {
return nil, err
}
} else if r.terraform.Spec.StoreReadablePlan == "human" {
rawOutput, err := r.tf.ShowPlanFileRaw(ctx, TFPlanName)
if err != nil {
log.Error(err, "unable to get the plan output for human")
return nil, err
}
if err := r.writePlanAsConfigMap(ctx, req.Name, req.Namespace, log, planName, rawOutput, "", req.Uuid); err != nil {
return nil, err
}
}
return &SaveTFPlanReply{Message: "ok"}, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (r *TerraformRunnerServer) ShowPlanFileRaw(ctx context.Context, req *ShowPlanFileRawRequest) (*ShowPlanFileRawReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("show the raw plan file")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
rawOutput, err := r.tf.ShowPlanFileRaw(ctx, req.Filename)
if err != nil {
log.Error(err, "unable to get the raw plan output")
return nil, err
}
return &ShowPlanFileRawReply{RawOutput: rawOutput}, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (r *TerraformRunnerServer) ShowPlanFile(ctx context.Context, req *ShowPlanFileRequest) (*ShowPlanFileReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("show the raw plan file")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
plan, err := r.tf.ShowPlanFile(ctx, req.Filename)
if err != nil {
log.Error(err, "unable to get the json plan output")
return nil, err
}
jsonBytes, err := json.Marshal(plan)
if err != nil {
log.Error(err, "unable to marshal the plan to json")
return nil, err
}
return &ShowPlanFileReply{JsonOutput: jsonBytes}, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (r *TerraformRunnerServer) Output(ctx context.Context, req *OutputRequest) (*OutputReply, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating outputs")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
outputs, err := r.tf.Output(ctx)
if err != nil {
log.Error(err, "unable to get outputs")
return nil, err
}
outputReply := &OutputReply{Outputs: map[string]*OutputMeta{}}
for k, v := range outputs {
outputReply.Outputs[k] = &OutputMeta{
Sensitive: v.Sensitive,
Type: v.Type,
Value: v.Value,
}
}
return outputReply, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (ctx *Context) RedirectToFirst(location ...string) {
for _, loc := range location {
if len(loc) == 0 {
continue
}
// Unfortunately browsers consider a redirect Location with preceding "//" and "/\" as meaning redirect to "http(s)://REST_OF_PATH"
// Therefore we should ignore these redirect locations to prevent open redirects
if len(loc) > 1 && loc[0] == '/' && (loc[1] == '/' || loc[1] == '\\') {
continue
}
u, err := url.Parse(loc)
if err != nil || ((u.Scheme != "" || u.Host != "") && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {
continue
}
ctx.Redirect(loc)
return
}
ctx.Redirect(setting.AppSubURL + "/")
} | 0 | Go | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
func (t *assetAction) checkERC20Deposit() error {
asset, _ := t.asset.ERC20()
return t.bridgeView.FindDeposit(
t.erc20D, t.blockHeight, t.logIndex, asset.Address(),
)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (t *assetAction) checkERC20BridgeResumed() error {
return t.bridgeView.FindBridgeResumed(
t.erc20BridgeResumed, t.blockHeight, t.logIndex)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (t *assetAction) checkERC20AssetList() error {
return t.bridgeView.FindAssetList(t.erc20AL, t.blockHeight, t.logIndex)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (t *assetAction) checkERC20BridgeStopped() error {
return t.bridgeView.FindBridgeStopped(
t.erc20BridgeStopped, t.blockHeight, t.logIndex)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (t *assetAction) checkERC20AssetLimitsUpdated() error {
asset, _ := t.asset.ERC20()
return t.bridgeView.FindAssetLimitsUpdated(
t.erc20AssetLimitsUpdated, t.blockHeight, t.logIndex, asset.Address(),
)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (m *MockERC20BridgeView) FindBridgeResumed(arg0 *types.ERC20EventBridgeResumed, arg1, arg2 uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindBridgeResumed", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (m *MockERC20BridgeView) FindDeposit(arg0 *types.ERC20Deposit, arg1, arg2 uint64, arg3 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindDeposit", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (mr *MockERC20BridgeViewMockRecorder) FindAssetList(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAssetList", reflect.TypeOf((*MockERC20BridgeView)(nil).FindAssetList), arg0, arg1, arg2)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (m *MockERC20BridgeView) FindBridgeStopped(arg0 *types.ERC20EventBridgeStopped, arg1, arg2 uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindBridgeStopped", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (mr *MockERC20BridgeViewMockRecorder) FindDeposit(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeposit", reflect.TypeOf((*MockERC20BridgeView)(nil).FindDeposit), arg0, arg1, arg2, arg3)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (m *MockERC20BridgeView) FindAssetList(arg0 *types.ERC20AssetList, arg1, arg2 uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindAssetList", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (mr *MockERC20BridgeViewMockRecorder) FindBridgeResumed(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindBridgeResumed", reflect.TypeOf((*MockERC20BridgeView)(nil).FindBridgeResumed), arg0, arg1, arg2)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (mr *MockERC20BridgeViewMockRecorder) FindAssetLimitsUpdated(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAssetLimitsUpdated", reflect.TypeOf((*MockERC20BridgeView)(nil).FindAssetLimitsUpdated), arg0, arg1, arg2, arg3)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (m *MockERC20BridgeView) FindAssetLimitsUpdated(arg0 *types.ERC20AssetLimitsUpdated, arg1, arg2 uint64, arg3 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindAssetLimitsUpdated", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (mr *MockERC20BridgeViewMockRecorder) FindBridgeStopped(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindBridgeStopped", reflect.TypeOf((*MockERC20BridgeView)(nil).FindBridgeStopped), arg0, arg1, arg2)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (e *ERC20LogicView) FindBridgeStopped(
al *types.ERC20EventBridgeStopped,
blockNumber,
logIndex uint64,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_bridge_stopped", resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterBridgeStopped(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedBridgeStopped
for iter.Next() {
if iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20BridgeStopped
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (e *ERC20LogicView) FindAssetList(
al *types.ERC20AssetList,
blockNumber,
logIndex uint64,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_asset_list", al.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetListed(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
[]ethcommon.Address{ethcommon.HexToAddress(al.AssetSource)},
[][32]byte{},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetListed
assetID := strings.TrimPrefix(al.VegaAssetID, "0x")
for iter.Next() {
if hex.EncodeToString(iter.Event.VegaAssetId[:]) == assetID &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20AssetList
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (e *ERC20LogicView) FindAssetLimitsUpdated(
update *types.ERC20AssetLimitsUpdated,
blockNumber uint64, logIndex uint64,
ethAssetAddress string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_asset_limits_updated", update.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetLimitsUpdated(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
[]ethcommon.Address{ethcommon.HexToAddress(ethAssetAddress)},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetLimitsUpdated
for iter.Next() {
eventLifetimeLimit, _ := num.UintFromBig(iter.Event.LifetimeLimit)
eventWithdrawThreshold, _ := num.UintFromBig(iter.Event.WithdrawThreshold)
if update.LifetimeLimits.EQ(eventLifetimeLimit) &&
update.WithdrawThreshold.EQ(eventWithdrawThreshold) &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20AssetLimitsUpdated
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (e *ERC20LogicView) FindWithdrawal(
w *types.ERC20Withdrawal,
blockNumber, logIndex uint64,
ethAssetAddress string,
) (*big.Int, string, uint, error) {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return nil, "", 0, err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_withdrawal", w.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetWithdrawn(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
// user_address
[]ethcommon.Address{ethcommon.HexToAddress(w.TargetEthereumAddress)},
// asset_source
[]ethcommon.Address{ethcommon.HexToAddress(ethAssetAddress)})
if err != nil {
resp = getMaybeHTTPStatus(err)
return nil, "", 0, err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetWithdrawn
nonce := &big.Int{}
_, ok := nonce.SetString(w.ReferenceNonce, 10)
if !ok {
return nil, "", 0, fmt.Errorf("could not use reference nonce, expected base 10 integer: %v", w.ReferenceNonce)
}
for iter.Next() {
if nonce.Cmp(iter.Event.Nonce) == 0 &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex {
event = iter.Event
break
}
}
if event == nil {
return nil, "", 0, ErrUnableToFindERC20Withdrawal
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return nil, "", 0, err
}
return nonce, event.Raw.TxHash.Hex(), event.Raw.Index, nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (e *ERC20LogicView) FindBridgeResumed(
al *types.ERC20EventBridgeResumed,
blockNumber,
logIndex uint64,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_bridge_stopped", resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterBridgeResumed(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedBridgeResumed
for iter.Next() {
if iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20BridgeStopped
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (e *ERC20LogicView) FindDeposit(
d *types.ERC20Deposit,
blockNumber, logIndex uint64,
ethAssetAddress string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_deposit", d.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetDeposited(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
// user_address
[]ethcommon.Address{ethcommon.HexToAddress(d.SourceEthereumAddress)},
// asset_source
[]ethcommon.Address{ethcommon.HexToAddress(ethAssetAddress)})
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
depamount := d.Amount.BigInt()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetDeposited
targetPartyID := strings.TrimPrefix(d.TargetPartyID, "0x")
for iter.Next() {
if hex.EncodeToString(iter.Event.VegaPublicKey[:]) == targetPartyID &&
iter.Event.Amount.Cmp(depamount) == 0 &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20Deposit
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (*BridgeViewStub) FindDeposit(d *types.ERC20Deposit, blockNumber, logIndex uint64, ethAssetAddress string) error {
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (*BridgeViewStub) FindBridgeResumed(al *types.ERC20EventBridgeResumed, blockNumber, logIndex uint64) error {
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (*BridgeViewStub) FindBridgeStopped(al *types.ERC20EventBridgeStopped, blockNumber, logIndex uint64) error {
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (*BridgeViewStub) FindAssetLimitsUpdated(w *types.ERC20AssetLimitsUpdated, blockNumber, logIndex uint64, ethAssetAddress string) error {
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (*BridgeViewStub) FindAssetList(al *types.ERC20AssetList, blockNumber, logIndex uint64) error {
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (o *OnChainVerifier) filterSignerAdded(
ctx context.Context,
filterer *multisig.MultisigControlFilterer,
event *types.SignerEvent,
) error {
iter, err := filterer.FilterSignerAdded(
&bind.FilterOpts{
Start: event.BlockNumber,
End: &event.BlockNumber,
Context: ctx,
},
)
if err != nil {
o.log.Error("Couldn't start filtering on signer added event",
logging.Error(err))
return err
}
defer iter.Close()
for iter.Next() {
if o.log.GetLevel() <= logging.DebugLevel {
o.log.Debug("found signer added event on chain",
logging.String("new-signer", iter.Event.NewSigner.Hex()),
)
}
nonce, _ := big.NewInt(0).SetString(event.Nonce, 10)
if iter.Event.Raw.BlockNumber == event.BlockNumber &&
uint64(iter.Event.Raw.Index) == event.LogIndex &&
iter.Event.NewSigner.Hex() == event.Address &&
nonce.Cmp(iter.Event.Nonce) == 0 {
// now we know the event is OK,
// just need to check for confirmations
return o.ethConfirmations.Check(event.BlockNumber)
}
}
return ErrNoSignerEventFound
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (o *OnChainVerifier) CheckThresholdSetEvent(
event *types.SignerThresholdSetEvent,
) error {
o.mu.RLock()
defer o.mu.RUnlock()
if o.log.GetLevel() <= logging.DebugLevel {
o.log.Debug("checking threshold set event on chain",
logging.String("contract-address", o.multiSigAddress.Hex()),
logging.String("event", event.String()),
)
}
filterer, err := multisig.NewMultisigControlFilterer(
o.multiSigAddress,
o.ethClient,
)
if err != nil {
o.log.Error("could not instantiate multisig control filterer",
logging.Error(err))
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := filterer.FilterThresholdSet(
&bind.FilterOpts{
Start: event.BlockNumber,
End: &event.BlockNumber,
Context: ctx,
},
)
if err != nil {
o.log.Error("Couldn't start filtering on signer added event",
logging.Error(err))
return err
}
defer iter.Close()
for iter.Next() {
if o.log.GetLevel() <= logging.DebugLevel {
o.log.Debug("found threshold set event on chain",
logging.Uint16("new-threshold", iter.Event.NewThreshold),
)
}
nonce, _ := big.NewInt(0).SetString(event.Nonce, 10)
if iter.Event.Raw.BlockNumber == event.BlockNumber &&
uint64(iter.Event.Raw.Index) == event.LogIndex &&
iter.Event.NewThreshold == uint16(event.Threshold) &&
nonce.Cmp(iter.Event.Nonce) == 0 {
// now we know the event is OK,
// just need to check for confirmations
return o.ethConfirmations.Check(event.BlockNumber)
}
}
return ErrNoThresholdSetEventFound
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func (o *OnChainVerifier) filterSignerRemoved(
ctx context.Context,
filterer *multisig.MultisigControlFilterer,
event *types.SignerEvent,
) error {
iter, err := filterer.FilterSignerRemoved(
&bind.FilterOpts{
Start: event.BlockNumber,
End: &event.BlockNumber,
Context: ctx,
},
)
if err != nil {
o.log.Error("Couldn't start filtering on signer removed event",
logging.Error(err))
return err
}
defer iter.Close()
for iter.Next() {
if o.log.GetLevel() <= logging.DebugLevel {
o.log.Debug("found signer removed event on chain",
logging.String("old-signer", iter.Event.OldSigner.Hex()),
)
}
nonce, _ := big.NewInt(0).SetString(event.Nonce, 10)
if iter.Event.Raw.BlockNumber == event.BlockNumber &&
uint64(iter.Event.Raw.Index) == event.LogIndex &&
iter.Event.OldSigner.Hex() == event.Address &&
nonce.Cmp(iter.Event.Nonce) == 0 {
// now we know the event is OK,
// just need to check for confirmations
return o.ethConfirmations.Check(event.BlockNumber)
}
}
return ErrNoSignerEventFound
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func ValidateAllAuthorizationModels(ctx context.Context, db storage.OpenFGADatastore) ([]validationResult, error) {
validationResults := make([]validationResult, 0)
continuationTokenStores := ""
for {
// fetch a page of stores
stores, tokenStores, err := db.ListStores(ctx, storage.PaginationOptions{
PageSize: 100,
From: continuationTokenStores,
})
if err != nil {
return nil, fmt.Errorf("error reading stores: %w", err)
}
// validate each store
for _, store := range stores {
latestModelID, err := db.FindLatestAuthorizationModelID(ctx, store.Id)
if err != nil {
fmt.Printf("no models in store %s \n", store.Id)
}
continuationTokenModels := ""
for {
// fetch a page of models for that store
models, tokenModels, err := db.ReadAuthorizationModels(ctx, store.Id, storage.PaginationOptions{
PageSize: 100,
From: continuationTokenModels,
})
if err != nil {
return nil, fmt.Errorf("error reading authorization models: %w", err)
}
// validate each model
for _, model := range models {
_, err := typesystem.NewAndValidate(model)
validationResult := validationResult{
StoreID: store.Id,
ModelID: model.Id,
IsLatestModel: model.Id == latestModelID,
}
if err != nil {
validationResult.Error = err.Error()
}
validationResults = append(validationResults, validationResult)
}
continuationTokenModels = string(tokenModels)
if continuationTokenModels == "" {
break
}
}
}
// next page of stores
continuationTokenStores = string(tokenStores)
if continuationTokenStores == "" {
break
}
}
return validationResults, nil
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func (q *ExpandQuery) Execute(ctx context.Context, req *openfgapb.ExpandRequest) (*openfgapb.ExpandResponse, error) {
store := req.GetStoreId()
modelID := req.GetAuthorizationModelId()
tupleKey := req.GetTupleKey()
object := tupleKey.GetObject()
relation := tupleKey.GetRelation()
if object == "" || relation == "" {
return nil, serverErrors.InvalidExpandInput
}
tk := tupleUtils.NewTupleKey(object, relation, "")
model, err := q.datastore.ReadAuthorizationModel(ctx, store, modelID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, serverErrors.AuthorizationModelNotFound(modelID)
}
return nil, serverErrors.HandleError("", err)
}
if !typesystem.IsSchemaVersionSupported(model.GetSchemaVersion()) {
return nil, serverErrors.ValidationError(typesystem.ErrInvalidSchemaVersion)
}
typesys := typesystem.New(model)
if err = validation.ValidateObject(typesys, tk); err != nil {
return nil, serverErrors.ValidationError(err)
}
err = validation.ValidateRelation(typesys, tk)
if err != nil {
return nil, serverErrors.ValidationError(err)
}
objectType := tupleUtils.GetType(object)
rel, err := typesys.GetRelation(objectType, relation)
if err != nil {
if errors.Is(err, typesystem.ErrObjectTypeUndefined) {
return nil, serverErrors.TypeNotFound(objectType)
}
if errors.Is(err, typesystem.ErrRelationUndefined) {
return nil, serverErrors.RelationNotFound(relation, objectType, tk)
}
return nil, serverErrors.HandleError("", err)
}
userset := rel.GetRewrite()
root, err := q.resolveUserset(ctx, store, userset, tk, typesys)
if err != nil {
return nil, err
}
return &openfgapb.ExpandResponse{
Tree: &openfgapb.UsersetTree{
Root: root,
},
}, nil
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func (w *WriteAuthorizationModelCommand) Execute(ctx context.Context, req *openfgapb.WriteAuthorizationModelRequest) (*openfgapb.WriteAuthorizationModelResponse, error) {
// Until this is solved: https://github.com/envoyproxy/protoc-gen-validate/issues/74
if len(req.GetTypeDefinitions()) > w.backend.MaxTypesPerAuthorizationModel() {
return nil, serverErrors.ExceededEntityLimit("type definitions in an authorization model", w.backend.MaxTypesPerAuthorizationModel())
}
// Fill in the schema version for old requests, which don't contain it, while we migrate to the new schema version.
if req.SchemaVersion == "" {
req.SchemaVersion = typesystem.SchemaVersion1_1
}
model := &openfgapb.AuthorizationModel{
Id: ulid.Make().String(),
SchemaVersion: req.GetSchemaVersion(),
TypeDefinitions: req.GetTypeDefinitions(),
}
_, err := typesystem.NewAndValidate(model)
if err != nil {
return nil, serverErrors.InvalidAuthorizationModelInput(err)
}
err = w.backend.WriteAuthorizationModel(ctx, req.GetStoreId(), model)
if err != nil {
return nil, serverErrors.NewInternalError("Error writing authorization model configuration", err)
}
return &openfgapb.WriteAuthorizationModelResponse{
AuthorizationModelId: model.Id,
}, nil
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func (s *Server) StreamedListObjects(req *openfgapb.StreamedListObjectsRequest, srv openfgapb.OpenFGAService_StreamedListObjectsServer) error {
ctx := srv.Context()
ctx, span := tracer.Start(ctx, "StreamedListObjects", trace.WithAttributes(
attribute.String("object_type", req.GetType()),
attribute.String("relation", req.GetRelation()),
attribute.String("user", req.GetUser()),
))
defer span.End()
storeID := req.GetStoreId()
modelID, err := s.resolveAuthorizationModelID(ctx, storeID, req.GetAuthorizationModelId())
if err != nil {
return err
}
model, err := s.datastore.ReadAuthorizationModel(ctx, storeID, modelID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return serverErrors.AuthorizationModelNotFound(req.GetAuthorizationModelId())
}
return serverErrors.HandleError("", err)
}
typesys := typesystem.New(model)
ctx = typesystem.ContextWithTypesystem(ctx, typesys)
q := &commands.ListObjectsQuery{
Datastore: s.datastore,
Logger: s.logger,
ListObjectsDeadline: s.config.ListObjectsDeadline,
ListObjectsMaxResults: s.config.ListObjectsMaxResults,
ResolveNodeLimit: s.config.ResolveNodeLimit,
}
req.AuthorizationModelId = modelID
return q.ExecuteStreamed(ctx, req, srv)
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func (s *Server) ListObjects(ctx context.Context, req *openfgapb.ListObjectsRequest) (*openfgapb.ListObjectsResponse, error) {
storeID := req.GetStoreId()
targetObjectType := req.GetType()
ctx, span := tracer.Start(ctx, "ListObjects", trace.WithAttributes(
attribute.String("object_type", targetObjectType),
attribute.String("relation", req.GetRelation()),
attribute.String("user", req.GetUser()),
))
defer span.End()
modelID := req.GetAuthorizationModelId()
modelID, err := s.resolveAuthorizationModelID(ctx, storeID, modelID)
if err != nil {
return nil, err
}
model, err := s.datastore.ReadAuthorizationModel(ctx, storeID, modelID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, serverErrors.AuthorizationModelNotFound(modelID)
}
return nil, err
}
typesys := typesystem.New(model)
ctx = typesystem.ContextWithTypesystem(ctx, typesys)
q := &commands.ListObjectsQuery{
Datastore: s.datastore,
Logger: s.logger,
ListObjectsDeadline: s.config.ListObjectsDeadline,
ListObjectsMaxResults: s.config.ListObjectsMaxResults,
ResolveNodeLimit: s.config.ResolveNodeLimit,
}
return q.Execute(ctx, &openfgapb.ListObjectsRequest{
StoreId: storeID,
ContextualTuples: req.GetContextualTuples(),
AuthorizationModelId: modelID,
Type: targetObjectType,
Relation: req.Relation,
User: req.User,
})
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func TestCheckDoesNotThrowBecauseDirectTupleWasFound(t *testing.T) {
ctx := context.Background()
storeID := ulid.Make().String()
modelID := ulid.Make().String()
typedefs := parser.MustParse(`
type user
type repo
relations
define reader: [user] as self
`)
tk := tuple.NewTupleKey("repo:openfga", "reader", "user:anne")
tuple := &openfgapb.Tuple{Key: tk}
mockController := gomock.NewController(t)
defer mockController.Finish()
mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController)
mockDatastore.EXPECT().
ReadAuthorizationModel(gomock.Any(), storeID, modelID).
AnyTimes().
Return(&openfgapb.AuthorizationModel{
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: typedefs,
}, nil)
// it could happen that one of the following two mocks won't be necessary because the goroutine will be short-circuited
mockDatastore.EXPECT().
ReadUserTuple(gomock.Any(), storeID, gomock.Any()).
AnyTimes().
Return(tuple, nil)
mockDatastore.EXPECT().
ReadUsersetTuples(gomock.Any(), storeID, gomock.Any()).
AnyTimes().
DoAndReturn(
func(_ context.Context, _ string, _ storage.ReadUsersetTuplesFilter) (storage.TupleIterator, error) {
time.Sleep(50 * time.Millisecond)
return nil, errors.New("some error")
})
s := New(&Dependencies{
Datastore: mockDatastore,
Logger: logger.NewNoopLogger(),
Transport: gateway.NewNoopTransport(),
}, &Config{
ResolveNodeLimit: 25,
})
checkResponse, err := s.Check(ctx, &openfgapb.CheckRequest{
StoreId: storeID,
TupleKey: tk,
AuthorizationModelId: modelID,
})
require.NoError(t, err)
require.Equal(t, true, checkResponse.Allowed)
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func BenchmarkListObjectsNoRaceCondition(b *testing.B) {
ctx := context.Background()
logger := logger.NewNoopLogger()
transport := gateway.NewNoopTransport()
store := ulid.Make().String()
modelID := ulid.Make().String()
mockController := gomock.NewController(b)
defer mockController.Finish()
typedefs := parser.MustParse(`
type user
type repo
relations
define allowed: [user] as self
define viewer: [user] as self and allowed
`)
mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController)
mockDatastore.EXPECT().ReadAuthorizationModel(gomock.Any(), store, modelID).AnyTimes().Return(&openfgapb.AuthorizationModel{
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: typedefs,
}, nil)
mockDatastore.EXPECT().ListObjectsByType(gomock.Any(), store, "repo").AnyTimes().Return(nil, errors.New("error reading from storage"))
s := New(&Dependencies{
Datastore: mockDatastore,
Transport: transport,
Logger: logger,
}, &Config{
ResolveNodeLimit: 25,
ListObjectsDeadline: 5 * time.Second,
ListObjectsMaxResults: 1000,
})
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := s.ListObjects(ctx, &openfgapb.ListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
})
require.ErrorIs(b, err, serverErrors.NewInternalError("", errors.New("error reading from storage")))
err = s.StreamedListObjects(&openfgapb.StreamedListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
}, NewMockStreamServer())
require.ErrorIs(b, err, serverErrors.NewInternalError("", errors.New("error reading from storage")))
}
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func TestListObjects_Unoptimized_UnhappyPaths(t *testing.T) {
ctx := context.Background()
logger := logger.NewNoopLogger()
transport := gateway.NewNoopTransport()
store := ulid.Make().String()
modelID := ulid.Make().String()
mockController := gomock.NewController(t)
defer mockController.Finish()
mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController)
mockDatastore.EXPECT().ReadAuthorizationModel(gomock.Any(), store, modelID).AnyTimes().Return(&openfgapb.AuthorizationModel{
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: parser.MustParse(`
type user
type repo
relations
define allowed: [user] as self
define viewer: [user] as self and allowed
`),
}, nil)
mockDatastore.EXPECT().ListObjectsByType(gomock.Any(), store, "repo").AnyTimes().Return(nil, errors.New("error reading from storage"))
s := New(&Dependencies{
Datastore: mockDatastore,
Transport: transport,
Logger: logger,
}, &Config{
ResolveNodeLimit: 25,
ListObjectsDeadline: 5 * time.Second,
ListObjectsMaxResults: 1000,
})
t.Run("error_listing_objects_from_storage_in_non-streaming_version", func(t *testing.T) {
res, err := s.ListObjects(ctx, &openfgapb.ListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
})
require.Nil(t, res)
require.ErrorIs(t, err, serverErrors.NewInternalError("", errors.New("error reading from storage")))
})
t.Run("error_listing_objects_from_storage_in_streaming_version", func(t *testing.T) {
err := s.StreamedListObjects(&openfgapb.StreamedListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
}, NewMockStreamServer())
require.ErrorIs(t, err, serverErrors.NewInternalError("", errors.New("error reading from storage")))
})
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func BenchmarkListObjectsWithConcurrentChecks(b *testing.B, ds storage.OpenFGADatastore) {
ctx := context.Background()
store := ulid.Make().String()
typedefs := parser.MustParse(`
type user
type document
relations
define allowed: [user] as self
define viewer: [user] as self and allowed
`)
model := &openfgapb.AuthorizationModel{
Id: ulid.Make().String(),
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: typedefs,
}
err := ds.WriteAuthorizationModel(ctx, store, model)
require.NoError(b, err)
n := 0
for i := 0; i < 100; i++ {
var tuples []*openfgapb.TupleKey
for j := 0; j < ds.MaxTuplesPerWrite()/2; j++ {
obj := fmt.Sprintf("document:%s", strconv.Itoa(n))
user := fmt.Sprintf("user:%s", strconv.Itoa(n))
tuples = append(
tuples,
tuple.NewTupleKey(obj, "viewer", user),
tuple.NewTupleKey(obj, "allowed", user),
)
n += 1
}
err = ds.Write(ctx, store, nil, tuples)
require.NoError(b, err)
}
listObjectsQuery := commands.ListObjectsQuery{
Datastore: ds,
Logger: logger.NewNoopLogger(),
ResolveNodeLimit: defaultResolveNodeLimit,
}
var r *openfgapb.ListObjectsResponse
ctx = typesystem.ContextWithTypesystem(ctx, typesystem.New(model))
b.ResetTimer()
for i := 0; i < b.N; i++ {
r, _ = listObjectsQuery.Execute(ctx, &openfgapb.ListObjectsRequest{
StoreId: store,
AuthorizationModelId: model.Id,
Type: "document",
Relation: "viewer",
User: "user:999",
})
}
listObjectsResponse = r
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func BenchmarkListObjectsWithReverseExpand(b *testing.B, ds storage.OpenFGADatastore) {
ctx := context.Background()
store := ulid.Make().String()
model := &openfgapb.AuthorizationModel{
Id: ulid.Make().String(),
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: []*openfgapb.TypeDefinition{
{
Type: "user",
},
{
Type: "document",
Relations: map[string]*openfgapb.Userset{
"viewer": typesystem.This(),
},
Metadata: &openfgapb.Metadata{
Relations: map[string]*openfgapb.RelationMetadata{
"viewer": {
DirectlyRelatedUserTypes: []*openfgapb.RelationReference{
typesystem.DirectRelationReference("user", ""),
},
},
},
},
},
},
}
err := ds.WriteAuthorizationModel(ctx, store, model)
require.NoError(b, err)
n := 0
for i := 0; i < 100; i++ {
var tuples []*openfgapb.TupleKey
for j := 0; j < ds.MaxTuplesPerWrite(); j++ {
obj := fmt.Sprintf("document:%s", strconv.Itoa(n))
user := fmt.Sprintf("user:%s", strconv.Itoa(n))
tuples = append(tuples, tuple.NewTupleKey(obj, "viewer", user))
n += 1
}
err = ds.Write(ctx, store, nil, tuples)
require.NoError(b, err)
}
listObjectsQuery := commands.ListObjectsQuery{
Datastore: ds,
Logger: logger.NewNoopLogger(),
ResolveNodeLimit: defaultResolveNodeLimit,
}
var r *openfgapb.ListObjectsResponse
ctx = typesystem.ContextWithTypesystem(ctx, typesystem.New(model))
b.ResetTimer()
for i := 0; i < b.N; i++ {
r, _ = listObjectsQuery.Execute(ctx, &openfgapb.ListObjectsRequest{
StoreId: store,
AuthorizationModelId: model.Id,
Type: "document",
Relation: "viewer",
User: "user:999",
})
}
listObjectsResponse = r
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func RunQueryTests(t *testing.T, ds storage.OpenFGADatastore) {
t.Run("TestReadAuthorizationModelQueryErrors", func(t *testing.T) { TestReadAuthorizationModelQueryErrors(t, ds) })
t.Run("TestSuccessfulReadAuthorizationModelQuery", func(t *testing.T) { TestSuccessfulReadAuthorizationModelQuery(t, ds) })
t.Run("TestReadAuthorizationModel", func(t *testing.T) { ReadAuthorizationModelTest(t, ds) })
t.Run("TestExpandQuery", func(t *testing.T) { TestExpandQuery(t, ds) })
t.Run("TestExpandQueryErrors", func(t *testing.T) { TestExpandQueryErrors(t, ds) })
t.Run("TestGetStoreQuery", func(t *testing.T) { TestGetStoreQuery(t, ds) })
t.Run("TestGetStoreSucceeds", func(t *testing.T) { TestGetStoreSucceeds(t, ds) })
t.Run("TestListStores", func(t *testing.T) { TestListStores(t, ds) })
t.Run("TestReadAssertionQuery", func(t *testing.T) { TestReadAssertionQuery(t, ds) })
t.Run("TestReadQuerySuccess", func(t *testing.T) { ReadQuerySuccessTest(t, ds) })
t.Run("TestReadQueryError", func(t *testing.T) { ReadQueryErrorTest(t, ds) })
t.Run("TestReadAllTuples", func(t *testing.T) { ReadAllTuplesTest(t, ds) })
t.Run("TestReadAllTuplesInvalidContinuationToken", func(t *testing.T) { ReadAllTuplesInvalidContinuationTokenTest(t, ds) })
t.Run("TestReadAuthorizationModelsWithoutPaging",
func(t *testing.T) { TestReadAuthorizationModelsWithoutPaging(t, ds) },
)
t.Run("TestReadAuthorizationModelsWithPaging",
func(t *testing.T) { TestReadAuthorizationModelsWithPaging(t, ds) },
)
t.Run("TestReadAuthorizationModelsInvalidContinuationToken",
func(t *testing.T) { TestReadAuthorizationModelsInvalidContinuationToken(t, ds) },
)
t.Run("TestReadChanges", func(t *testing.T) { TestReadChanges(t, ds) })
t.Run("TestReadChangesReturnsSameContTokenWhenNoChanges",
func(t *testing.T) { TestReadChangesReturnsSameContTokenWhenNoChanges(t, ds) },
)
t.Run("TestListObjectsRespectsMaxResults", func(t *testing.T) { TestListObjectsRespectsMaxResults(t, ds) })
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func New(model *openfgapb.AuthorizationModel) *TypeSystem {
tds := make(map[string]*openfgapb.TypeDefinition, len(model.GetTypeDefinitions()))
relations := make(map[string]map[string]*openfgapb.Relation, len(model.GetTypeDefinitions()))
for _, td := range model.GetTypeDefinitions() {
tds[td.GetType()] = td
tdRelations := make(map[string]*openfgapb.Relation, len(td.GetRelations()))
for relation, rewrite := range td.GetRelations() {
r := &openfgapb.Relation{
Name: relation,
Rewrite: rewrite,
TypeInfo: &openfgapb.RelationTypeInfo{},
}
if metadata, ok := td.GetMetadata().GetRelations()[relation]; ok {
r.TypeInfo.DirectlyRelatedUserTypes = metadata.GetDirectlyRelatedUserTypes()
}
tdRelations[relation] = r
}
relations[td.GetType()] = tdRelations
}
return &TypeSystem{
modelID: model.GetId(),
schemaVersion: model.GetSchemaVersion(),
typeDefinitions: tds,
relations: relations,
}
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func TestSuccessfulRewriteValidations(t *testing.T) {
var tests = []struct {
name string
model *openfgapb.AuthorizationModel
}{
{
name: "empty_relations",
model: &openfgapb.AuthorizationModel{
SchemaVersion: SchemaVersion1_1,
TypeDefinitions: []*openfgapb.TypeDefinition{
{
Type: "repo",
},
},
},
},
{
name: "zero_length_relations_is_valid",
model: &openfgapb.AuthorizationModel{
SchemaVersion: SchemaVersion1_1,
TypeDefinitions: []*openfgapb.TypeDefinition{
{
Type: "repo",
Relations: map[string]*openfgapb.Userset{},
},
},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := NewAndValidate(test.model)
require.NoError(t, err)
})
}
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func (c *LocalChecker) checkComputedUserset(parentctx context.Context, req *ResolveCheckRequest, rewrite *openfgav1.Userset_ComputedUserset) CheckHandlerFunc {
return func(ctx context.Context) (*ResolveCheckResponse, error) {
ctx, span := tracer.Start(ctx, "checkComputedUserset")
defer span.End()
return c.dispatch(
ctx,
&ResolveCheckRequest{
StoreID: req.GetStoreID(),
AuthorizationModelID: req.GetAuthorizationModelID(),
TupleKey: tuple.NewTupleKey(
req.TupleKey.GetObject(),
rewrite.ComputedUserset.GetRelation(),
req.TupleKey.GetUser(),
),
ResolutionMetadata: &ResolutionMetadata{
Depth: req.GetResolutionMetadata().Depth - 1,
DatastoreQueryCount: req.GetResolutionMetadata().DatastoreQueryCount,
},
})(ctx)
}
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func TestListObjects_Unoptimized_UnhappyPaths_Known_Error(t *testing.T) {
ctx := context.Background()
store := ulid.Make().String()
modelID := ulid.Make().String()
mockController := gomock.NewController(t)
defer mockController.Finish()
mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController)
mockDatastore.EXPECT().ReadAuthorizationModel(gomock.Any(), store, modelID).AnyTimes().Return(&openfgav1.AuthorizationModel{
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: parser.MustParse(`
type user
type repo
relations
define allowed: [user] as self
define viewer: [user] as self and allowed
`),
}, nil)
mockDatastore.EXPECT().ReadStartingWithUser(gomock.Any(), store, gomock.Any()).AnyTimes().Return(nil, serverErrors.AuthorizationModelResolutionTooComplex)
s := MustNewServerWithOpts(
WithDatastore(mockDatastore),
)
t.Run("error_listing_objects_from_storage_in_non-streaming_version", func(t *testing.T) {
res, err := s.ListObjects(ctx, &openfgav1.ListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
})
require.Nil(t, res)
require.ErrorIs(t, err, serverErrors.AuthorizationModelResolutionTooComplex)
})
t.Run("error_listing_objects_from_storage_in_streaming_version", func(t *testing.T) {
err := s.StreamedListObjects(&openfgav1.StreamedListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
}, NewMockStreamServer())
require.ErrorIs(t, err, serverErrors.AuthorizationModelResolutionTooComplex)
})
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func TestListObjects_Unoptimized_UnhappyPaths(t *testing.T) {
ctx := context.Background()
store := ulid.Make().String()
modelID := ulid.Make().String()
mockController := gomock.NewController(t)
defer mockController.Finish()
mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController)
mockDatastore.EXPECT().ReadAuthorizationModel(gomock.Any(), store, modelID).AnyTimes().Return(&openfgav1.AuthorizationModel{
SchemaVersion: typesystem.SchemaVersion1_1,
TypeDefinitions: parser.MustParse(`
type user
type repo
relations
define allowed: [user] as self
define viewer: [user] as self and allowed
`),
}, nil)
mockDatastore.EXPECT().ReadStartingWithUser(gomock.Any(), store, gomock.Any()).AnyTimes().Return(nil, errors.New("error reading from storage"))
s := MustNewServerWithOpts(
WithDatastore(mockDatastore),
)
t.Run("error_listing_objects_from_storage_in_non-streaming_version", func(t *testing.T) {
res, err := s.ListObjects(ctx, &openfgav1.ListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
})
require.Nil(t, res)
require.ErrorIs(t, err, serverErrors.NewInternalError("", errors.New("error reading from storage")))
})
t.Run("error_listing_objects_from_storage_in_streaming_version", func(t *testing.T) {
err := s.StreamedListObjects(&openfgav1.StreamedListObjectsRequest{
StoreId: store,
AuthorizationModelId: modelID,
Type: "repo",
Relation: "viewer",
User: "user:bob",
}, NewMockStreamServer())
require.ErrorIs(t, err, serverErrors.NewInternalError("", errors.New("error reading from storage")))
})
} | 0 | Go | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
func PostSambaConnectionsCreate(c *gin.Context) {
connection := model.Connections{}
c.ShouldBindJSON(&connection)
if connection.Port == "" {
connection.Port = "445"
}
if connection.Username == "" || connection.Host == "" {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.CHARACTER_LIMIT, Message: common_err.GetMsg(common_err.CHARACTER_LIMIT)})
return
}
if ok, _ := regexp.MatchString(`^[\w@#*.]{4,30}$`, connection.Password); !ok {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.CHARACTER_LIMIT, Message: common_err.GetMsg(common_err.CHARACTER_LIMIT)})
return
} | 0 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
func (s *connectionsStruct) MountSmaba(username, host, directory, port, mountPoint, password string) string {
str := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;MountCIFS " + username + " " + host + " " + directory + " " + port + " " + mountPoint + " " + password)
return str
} | 0 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
Skipper: func(c echo.Context) bool {
return c.RealIP() == "::1" || c.RealIP() == "127.0.0.1"
// return true
},
ParseTokenFunc: func(token string, c echo.Context) (interface{}, error) {
claims, code := jwt.Validate(token) // TODO - needs JWT validation
if code != common_err.SUCCESS {
return nil, echo.ErrUnauthorized
}
c.Request().Header.Set("user_id", strconv.Itoa(claims.ID))
return claims, nil
},
TokenLookupFuncs: []echo_middleware.ValuesExtractor{
func(c echo.Context) ([]string, error) {
return []string{c.Request().Header.Get(echo.HeaderAuthorization)}, nil
},
},
})) | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
func (r *Reader) readBytes(op string) []byte {
size := int(r.ReadLong())
if size < 0 {
r.ReportError("ReadString", "invalid "+op+" length")
return nil
}
if size == 0 {
return []byte{}
}
// The bytes are entirely in the buffer and of a reasonable size.
// Use the byte slab.
if r.head+size <= r.tail && size <= 1024 {
if cap(r.slab) < size {
r.slab = make([]byte, 1024)
}
dst := r.slab[:size]
r.slab = r.slab[size:]
copy(dst, r.buf[r.head:r.head+size])
r.head += size
return dst
}
buf := make([]byte, size)
r.Read(buf)
return buf
} | 0 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
func OperateFirewallPort(oldPorts, newPorts []int) error {
client, err := firewall.NewFirewallClient()
if err != nil {
return err
}
for _, port := range newPorts {
if err := client.Port(fireClient.FireInfo{Port: strconv.Itoa(port), Protocol: "tcp", Strategy: "accept"}, "add"); err != nil {
return err
}
}
for _, port := range oldPorts {
if err := client.Port(fireClient.FireInfo{Port: strconv.Itoa(port), Protocol: "tcp", Strategy: "accept"}, "remove"); err != nil {
return err
}
}
return client.Reload()
} | 0 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
func useAPIAuthentication(next fasthttp.RequestHandler) fasthttp.RequestHandler {
token := auth.GetAPIToken()
if token == "" {
return next
}
log.Info("enabled token authentication on http server")
return func(ctx *fasthttp.RequestCtx) {
v := ctx.Request.Header.Peek(authConsts.APITokenHeader)
if auth.ExcludedRoute(string(ctx.Request.URI().FullURI())) || string(v) == token {
ctx.Request.Header.Del(authConsts.APITokenHeader)
next(ctx)
} else {
ctx.Error("invalid api token", http.StatusUnauthorized)
}
}
} | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
func ExcludedRoute(route string) bool {
for _, r := range excludedRoutes {
if strings.Contains(route, r) {
return true
}
}
return false
} | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
func TestExcludedRoute(t *testing.T) {
t.Run("healthz route is excluded", func(t *testing.T) {
route := "v1.0/healthz"
excluded := ExcludedRoute(route)
assert.True(t, excluded)
})
t.Run("custom route is not excluded", func(t *testing.T) {
route := "v1.0/state"
excluded := ExcludedRoute(route)
assert.False(t, excluded)
})
} | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
func rawFileHandler(w http.ResponseWriter, r *http.Request, file *files.FileInfo) (int, error) {
fd, err := file.Fs.Open(file.Path)
if err != nil {
return http.StatusInternalServerError, err
}
defer fd.Close()
setContentDisposition(w, r, file)
w.Header().Set("Cache-Control", "private")
http.ServeContent(w, r, file.Name, file.ModTime, fd)
return 0, nil
} | 0 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
func (mbp *multipartBodyProcessor) ProcessRequest(reader io.Reader, v plugintypes.TransactionVariables, options plugintypes.BodyProcessorOptions) error {
mimeType := options.Mime
storagePath := options.StoragePath
mediaType, params, err := mime.ParseMediaType(mimeType)
if err != nil {
log.Fatalf("failed to parse media type: %s", err.Error())
}
if !strings.HasPrefix(mediaType, "multipart/") {
return errors.New("not a multipart body")
}
mr := multipart.NewReader(reader, params["boundary"])
totalSize := int64(0)
filesCol := v.Files()
filesTmpNamesCol := v.FilesTmpNames()
fileSizesCol := v.FilesSizes()
postCol := v.ArgsPost()
filesCombinedSizeCol := v.FilesCombinedSize()
filesNamesCol := v.FilesNames()
headersNames := v.MultipartPartHeaders()
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return err
}
partName := p.FormName()
for key, values := range p.Header {
for _, value := range values {
headersNames.Add(partName, fmt.Sprintf("%s: %s", key, value))
}
}
// if is a file
filename := originFileName(p)
if filename != "" {
var size int64
if environment.HasAccessToFS {
// Only copy file to temp when not running in TinyGo
temp, err := os.CreateTemp(storagePath, "crzmp*")
if err != nil {
return err
}
sz, err := io.Copy(temp, p)
if err != nil {
return err
}
size = sz
filesTmpNamesCol.Add("", temp.Name())
} else {
sz, err := io.Copy(io.Discard, p)
if err != nil {
return err
}
size = sz
}
totalSize += size
filesCol.Add("", filename)
fileSizesCol.SetIndex(filename, 0, fmt.Sprintf("%d", size))
filesNamesCol.Add("", p.FormName())
} else {
// if is a field
data, err := io.ReadAll(p)
if err != nil {
return err
}
totalSize += int64(len(data))
postCol.Add(p.FormName(), string(data))
}
filesCombinedSizeCol.(*collections.Single).Set(fmt.Sprintf("%d", totalSize))
}
return nil
} | 0 | Go | NVD-CWE-noinfo | null | null | null | vulnerable |
func getTokenFromStorage(c *fiber.Ctx, token string, cfg Config, sessionManager *sessionManager, storageManager *storageManager) []byte {
if cfg.Session != nil {
return sessionManager.getRaw(c, token, dummyValue)
}
return storageManager.getRaw(token)
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func getTokenFromStorage(c *fiber.Ctx, token string, cfg Config, sessionManager *sessionManager, storageManager *storageManager) []byte {
if cfg.Session != nil {
return sessionManager.getRaw(c, token, dummyValue)
}
return storageManager.getRaw(token)
} | 0 | Go | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
func getTokenFromStorage(c *fiber.Ctx, token string, cfg Config, sessionManager *sessionManager, storageManager *storageManager) []byte {
if cfg.Session != nil {
return sessionManager.getRaw(c, token, dummyValue)
}
return storageManager.getRaw(token)
} | 0 | Go | CWE-565 | Reliance on Cookies without Validation and Integrity Checking | The product relies on the existence or values of cookies when performing security-critical operations, but it does not properly ensure that the setting is valid for the associated user. | https://cwe.mitre.org/data/definitions/565.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.