code
stringlengths
23
2.05k
label_name
stringlengths
6
7
label
int64
0
37
func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) { alreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) if !alreadyAuthd { // First ensure the user has access to list hosts, then check the specific // host once team_id is loaded. if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { return nil, err } } host, err := svc.ds.Host(ctx, id, false) if err != nil { return nil, ctxerr.Wrap(ctx, err, "get host") } if !alreadyAuthd { // Authorize again with team loaded now that we have team_id if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return nil, err } } return svc.getHostDetails(ctx, host) }
CWE-863
11
func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction { algorithm, ok := parameters[Algorithm] if !ok { app.lc.Errorf("Could not find '%s' parameter for Encrypt", Algorithm) return nil } secretPath := parameters[SecretPath] secretName := parameters[SecretName] encryptionKey := parameters[EncryptionKey] // SecretPath & SecretName are optional if EncryptionKey specified // EncryptionKey is optional if SecretPath & SecretName are specified // If EncryptionKey not specified, then SecretPath & SecretName must be specified if len(encryptionKey) == 0 && (len(secretPath) == 0 || len(secretName) == 0) { app.lc.Errorf("Could not find '%s' or '%s' and '%s' in configuration", EncryptionKey, SecretPath, SecretName) return nil } // SecretPath & SecretName both must be specified it one of them is. if (len(secretPath) != 0 && len(secretName) == 0) || (len(secretPath) == 0 && len(secretName) != 0) { app.lc.Errorf("'%s' and '%s' both must be set in configuration", SecretPath, SecretName) return nil } initVector, ok := parameters[InitVector] if !ok { app.lc.Error("Could not find " + InitVector) return nil } transform := transforms.Encryption{ EncryptionKey: encryptionKey, InitializationVector: initVector, SecretPath: secretPath, SecretName: secretName, } switch strings.ToLower(algorithm) { case EncryptAES: return transform.EncryptWithAES default: app.lc.Errorf( "Invalid encryption algorithm '%s'. Must be '%s'", algorithm, EncryptAES) return nil } }
CWE-327
3
func getGateway(ctx *statsContext) error { gatewayID := helpers.GetGatewayID(&ctx.gatewayStats) gw, err := storage.GetAndCacheGateway(ctx.ctx, storage.DB(), gatewayID) if err != nil { return errors.Wrap(err, "get gateway error") } ctx.gateway = gw return nil }
CWE-20
0
func Handler(configFns ...func(*Config)) http.HandlerFunc { var once sync.Once config := &Config{ URL: "doc.json", DeepLinking: true, DocExpansion: "list", DomID: "#swagger-ui", } for _, configFn := range configFns { configFn(config) } // create a template with name t := template.New("swagger_index.html") index, _ := t.Parse(indexTempl) var re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`) return func(w http.ResponseWriter, r *http.Request) { matches := re.FindStringSubmatch(r.RequestURI) path := matches[2] h := swaggerFiles.Handler once.Do(func() { h.Prefix = matches[1] }) switch filepath.Ext(path) { case ".html": w.Header().Set("Content-Type", "text/html; charset=utf-8") case ".css": w.Header().Set("Content-Type", "text/css; charset=utf-8") case ".js": w.Header().Set("Content-Type", "application/javascript") case ".png": w.Header().Set("Content-Type", "image/png") case ".json": w.Header().Set("Content-Type", "application/json; charset=utf-8") } switch path { case "index.html": _ = index.Execute(w, config) case "doc.json": doc, err := swag.ReadDoc() if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } _, _ = w.Write([]byte(doc)) case "": http.Redirect(w, r, h.Prefix+"index.html", 301) default: h.ServeHTTP(w, r) } } }
CWE-755
21
func TestMaxDepthValidation(t *testing.T) { s, err := schema.ParseSchema(interfaceSimple, false) if err != nil { t.Fatal(err) } for _, tc := range []struct { name string query string maxDepth int expected bool }{ { name: "off", query: `query Fine { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 id # depth 3 name # depth 3 } } }`, maxDepth: 0, }, { name: "fields", query: `query Fine { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 id # depth 3 name # depth 3 } } }`, maxDepth: 2, expected: true, }, { name: "fragment", query: `fragment friend on Character { id # depth 6 name friends { name # depth 7 } } query { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 friends { # depth 3 friends { # depth 4 friends { # depth 5 ...friend # depth 6 } } } } } }`, maxDepth: 5, expected: true, }, { name: "inlinefragment", query: `query { # depth 0 characters { # depth 1 ... on Droid { # depth 2 primaryFunction # depth 2 } } }`, maxDepth: 1, expected: true, }, } { t.Run(tc.name, func(t *testing.T) { doc, err := query.Parse(tc.query) if err != nil { t.Fatal(err) } context := newContext(s, doc, tc.maxDepth) op := doc.Operations[0] opc := &opContext{context: context, ops: doc.Operations} actual := validateMaxDepth(opc, op.Selections, 1) if actual != tc.expected { t.Errorf("expected %t, actual %t", tc.expected, actual) } }) } }
CWE-400
2
func (p *GitLabProvider) addProjectsToSession(ctx context.Context, s *sessions.SessionState) { // Iterate over projects, check if oauth2-proxy can get project information on behalf of the user for _, project := range p.Projects { projectInfo, err := p.getProjectInfo(ctx, s, project.Name) if err != nil { logger.Errorf("Warning: project info request failed: %v", err) continue } if !projectInfo.Archived { perms := projectInfo.Permissions.ProjectAccess if perms == nil { // use group project access as fallback perms = projectInfo.Permissions.GroupAccess // group project access is not set for this user then we give up if perms == nil { logger.Errorf("Warning: user %q has no project level access to %s", s.Email, project.Name) continue } } if perms != nil && perms.AccessLevel >= project.AccessLevel { s.Groups = append(s.Groups, fmt.Sprintf("project:%s", project.Name)) } else { logger.Errorf("Warning: user %q does not have the minimum required access level for project %q", s.Email, project.Name) } } else { logger.Errorf("Warning: project %s is archived", project.Name) } } }
CWE-863
11
func (EmptyEvidencePool) AddEvidenceFromConsensus(evidence types.Evidence) error { return nil }
CWE-400
2
func Test_buildControlPlanePathRoute(t *testing.T) { b := &Builder{filemgr: filemgr.NewManager()} route, err := b.buildControlPlanePathRoute("/hello/world", false) require.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "name": "pomerium-path-/hello/world", "match": { "path": "/hello/world" }, "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) }
CWE-200
10
func (svc Service) DeleteTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint) error { if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil { return err } return svc.ds.DeleteScheduledQuery(ctx, scheduledQueryID) }
CWE-863
11
func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) { if !config.Cache.Enabled { return nil, false } item, found := a.tokenCache.Get(token) if !found { return nil, false } i := item.(*AuthenticatorOAuth2IntrospectionResult) expires := time.Unix(i.Expires, 0) if expires.Before(time.Now()) { a.tokenCache.Del(token) return nil, false } return i, true }
CWE-863
11
func Test_bindConfig(t *testing.T) { ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*10) defer clearTimeout() b := New("local-grpc", "local-http", filemgr.NewManager(), nil) t.Run("no bind config", func(t *testing.T) { cluster, err := b.buildPolicyCluster(ctx, &config.Options{}, &config.Policy{ From: "https://from.example.com", To: mustParseWeightedURLs(t, "https://to.example.com"), }) assert.NoError(t, err) assert.Nil(t, cluster.UpstreamBindConfig) }) t.Run("freebind", func(t *testing.T) { cluster, err := b.buildPolicyCluster(ctx, &config.Options{ EnvoyBindConfigFreebind: null.BoolFrom(true), }, &config.Policy{ From: "https://from.example.com", To: mustParseWeightedURLs(t, "https://to.example.com"), }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "freebind": true, "sourceAddress": { "address": "0.0.0.0", "portValue": 0 } } `, cluster.UpstreamBindConfig) }) t.Run("source address", func(t *testing.T) { cluster, err := b.buildPolicyCluster(ctx, &config.Options{ EnvoyBindConfigSourceAddress: "192.168.0.1", }, &config.Policy{ From: "https://from.example.com", To: mustParseWeightedURLs(t, "https://to.example.com"), }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "sourceAddress": { "address": "192.168.0.1", "portValue": 0 } } `, cluster.UpstreamBindConfig) }) }
CWE-200
10
func (evpool *Pool) removePendingEvidence(evidence types.Evidence) { key := keyPending(evidence) if err := evpool.evidenceStore.Delete(key); err != nil { evpool.logger.Error("Unable to delete pending evidence", "err", err) } else { atomic.AddUint32(&evpool.evidenceSize, ^uint32(0)) evpool.logger.Info("Deleted pending evidence", "evidence", evidence) } }
CWE-400
2
func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) { added, err := cs.addVote(vote, peerID) if err != nil { // If the vote height is off, we'll just ignore it, // But if it's a conflicting sig, add it to the cs.evpool. // If it's otherwise invalid, punish peer. // nolint: gocritic if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { if cs.privValidatorPubKey == nil { return false, errPubKeyIsNotSet } if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) { cs.Logger.Error( "Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type) return added, err } var timestamp time.Time if voteErr.VoteA.Height == cs.state.InitialHeight { timestamp = cs.state.LastBlockTime // genesis time } else { timestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators) } // form duplicate vote evidence from the conflicting votes and send it across to the // evidence pool ev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators) evidenceErr := cs.evpool.AddEvidenceFromConsensus(ev) if evidenceErr != nil { cs.Logger.Error("Failed to add evidence to the evidence pool", "err", evidenceErr) } else { cs.Logger.Debug("Added evidence to the evidence pool", "ev", ev) } return added, err } else if err == types.ErrVoteNonDeterministicSignature { cs.Logger.Debug("Vote has non-deterministic signature", "err", err) } else { // Either // 1) bad peer OR // 2) not a bad peer? this can also err sometimes with "Unexpected step" OR // 3) tmkms use with multiple validators connecting to a single tmkms instance // (https://github.com/tendermint/tendermint/issues/3839). cs.Logger.Info("Error attempting to add vote", "err", err) return added, ErrAddingVote } } return added, nil }
CWE-400
2
func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error { var ( dest = m.Destination data = label.FormatMountLabel(m.Data, mountLabel) flags = m.Flags ) if libcontainerUtils.CleanPath(dest) == "/dev" { flags &= ^unix.MS_RDONLY } // Mount it rw to allow chmod operation. A remount will be performed // later to make it ro if set. if m.Device == "tmpfs" { flags &= ^unix.MS_RDONLY } copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP if !(copyUp || strings.HasPrefix(dest, rootfs)) { dest = filepath.Join(rootfs, dest) } if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil { return err } for _, pflag := range m.PropagationFlags { if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil { return err } } return nil }
CWE-362
18
func (cn *clusterNode) resurrect() { gRPCServer, err := comm_utils.NewGRPCServer(cn.bindAddress, cn.serverConfig) if err != nil { panic(fmt.Errorf("failed starting gRPC server: %v", err)) } cn.srv = gRPCServer orderer.RegisterClusterServer(gRPCServer.Server(), cn) go cn.srv.Start() }
CWE-20
0
func (r *schemaResolver) UpdateSavedSearch(ctx context.Context, args *struct { ID graphql.ID Description string Query string NotifyOwner bool NotifySlack bool OrgID *graphql.ID UserID *graphql.ID }) (*savedSearchResolver, error) { var userID, orgID *int32 // 🚨 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org. if args.UserID != nil { u, err := unmarshalSavedSearchID(*args.UserID) if err != nil { return nil, err } userID = &u if err := backend.CheckSiteAdminOrSameUser(ctx, r.db, u); err != nil { return nil, err } } else if args.OrgID != nil { o, err := unmarshalSavedSearchID(*args.OrgID) if err != nil { return nil, err } orgID = &o if err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, o); err != nil { return nil, err } } else { return nil, errors.New("failed to update saved search: no Org ID or User ID associated with saved search") } id, err := unmarshalSavedSearchID(args.ID) if err != nil { return nil, err } if !queryHasPatternType(args.Query) { return nil, errMissingPatternType } ss, err := r.db.SavedSearches().Update(ctx, &types.SavedSearch{ ID: id, Description: args.Description, Query: args.Query, Notify: args.NotifyOwner, NotifySlack: args.NotifySlack, UserID: userID, OrgID: orgID, }) if err != nil { return nil, err } return r.toSavedSearchResolver(*ss), nil }
CWE-863
11
func validateMaxDepth(c *opContext, sels []types.Selection, depth int) bool { // maxDepth checking is turned off when maxDepth is 0 if c.maxDepth == 0 { return false } exceededMaxDepth := false for _, sel := range sels { switch sel := sel.(type) { case *types.Field: if depth > c.maxDepth { exceededMaxDepth = true c.addErr(sel.Alias.Loc, "MaxDepthExceeded", "Field %q has depth %d that exceeds max depth %d", sel.Name.Name, depth, c.maxDepth) continue } exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, sel.SelectionSet, depth+1) case *types.InlineFragment: // Depth is not checked because inline fragments resolve to other fields which are checked. // Depth is not incremented because inline fragments have the same depth as neighboring fields exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, sel.Selections, depth) case *types.FragmentSpread: // Depth is not checked because fragments resolve to other fields which are checked. frag := c.doc.Fragments.Get(sel.Name.Name) if frag == nil { // In case of unknown fragment (invalid request), ignore max depth evaluation c.addErr(sel.Loc, "MaxDepthEvaluationError", "Unknown fragment %q. Unable to evaluate depth.", sel.Name.Name) continue } // Depth is not incremented because fragments have the same depth as surrounding fields exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, frag.Selections, depth) } } return exceededMaxDepth }
CWE-400
2
func (p *GatewayAPIProcessor) validateForwardTo(serviceName *string, port *gatewayapi_v1alpha1.PortNumber, namespace string) (*Service, error) { // Verify the service is valid if serviceName == nil { return nil, fmt.Errorf("Spec.Rules.ForwardTo.ServiceName must be specified") } // TODO: Do not require port to be present (#3352). if port == nil { return nil, fmt.Errorf("Spec.Rules.ForwardTo.ServicePort must be specified") } meta := types.NamespacedName{Name: *serviceName, Namespace: namespace} // TODO: Refactor EnsureService to take an int32 so conversion to intstr is not needed. service, err := p.dag.EnsureService(meta, intstr.FromInt(int(*port)), p.source) if err != nil { return nil, fmt.Errorf("service %q does not exist", meta.Name) } return service, nil }
CWE-610
17
func prepareBindMount(m *configs.Mount, rootfs string) error { stat, err := os.Stat(m.Source) if err != nil { // error out if the source of a bind mount does not exist as we will be // unable to bind anything to it. return err } // ensure that the destination of the bind mount is resolved of symlinks at mount time because // any previous mounts can invalidate the next mount's destination. // this can happen when a user specifies mounts within other mounts to cause breakouts or other // evil stuff to try to escape the container's rootfs. var dest string if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil { return err } if err := checkProcMount(rootfs, dest, m.Source); err != nil { return err } // update the mount with the correct dest after symlinks are resolved. m.Destination = dest if err := createIfNotExists(dest, stat.IsDir()); err != nil { return err } return nil }
CWE-362
18
func TestBuilder_BuildBootstrapStatsConfig(t *testing.T) { b := New("local-grpc", "local-http", filemgr.NewManager(), nil) t.Run("valid", func(t *testing.T) { statsCfg, err := b.BuildBootstrapStatsConfig(&config.Config{ Options: &config.Options{ Services: "all", }, }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "statsTags": [{ "tagName": "service", "fixedValue": "pomerium" }] } `, statsCfg) }) }
CWE-200
10
func (f *Fosite) WriteAuthorizeError(rw http.ResponseWriter, ar AuthorizeRequester, err error) { rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") rfcerr := ErrorToRFC6749Error(err) if !f.SendDebugMessagesToClients { rfcerr = rfcerr.Sanitize() } if !ar.IsRedirectURIValid() { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") js, err := json.Marshal(rfcerr) if err != nil { if f.SendDebugMessagesToClients { errorMessage := EscapeJSONString(err.Error()) http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError) } else { http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError) } return } rw.WriteHeader(rfcerr.Code) rw.Write(js) return } redirectURI := ar.GetRedirectURI() // The endpoint URI MUST NOT include a fragment component. redirectURI.Fragment = "" query := rfcerr.ToValues() query.Add("state", ar.GetState()) var redirectURIString string if !(len(ar.GetResponseTypes()) == 0 || ar.GetResponseTypes().ExactOne("code")) && !errors.Is(err, ErrUnsupportedResponseType) { redirectURIString = redirectURI.String() + "#" + query.Encode() } else { for key, values := range redirectURI.Query() { for _, value := range values { query.Add(key, value) } } redirectURI.RawQuery = query.Encode() redirectURIString = redirectURI.String() } rw.Header().Add("Location", redirectURIString) rw.WriteHeader(http.StatusFound) }
CWE-755
21
func TestListActivities(t *testing.T) { ds := new(mock.Store) svc := newTestService(t, ds, nil, nil) ds.ListActivitiesFunc = func(ctx context.Context, opts fleet.ListOptions) ([]*fleet.Activity, error) { return []*fleet.Activity{ {ID: 1}, {ID: 2}, }, nil } // admin user activities, err := svc.ListActivities(test.UserContext(test.UserAdmin), fleet.ListOptions{}) require.NoError(t, err) require.Len(t, activities, 2) // anyone can read activities activities, err = svc.ListActivities(test.UserContext(test.UserNoRoles), fleet.ListOptions{}) require.NoError(t, err) require.Len(t, activities, 2) // no user in context _, err = svc.ListActivities(context.Background(), fleet.ListOptions{}) require.Error(t, err) require.Contains(t, err.Error(), authz.ForbiddenErrorMessage) }
CWE-863
11
func doesPolicySignatureV4Match(formValues http.Header) APIErrorCode { // Server region. region := globalServerRegion // Parse credential tag. credHeader, s3Err := parseCredentialHeader("Credential="+formValues.Get(xhttp.AmzCredential), region, serviceS3) if s3Err != ErrNone { return s3Err } cred, _, s3Err := checkKeyValid(credHeader.accessKey) if s3Err != ErrNone { return s3Err } // Get signing key. signingKey := getSigningKey(cred.SecretKey, credHeader.scope.date, credHeader.scope.region, serviceS3) // Get signature. newSignature := getSignature(signingKey, formValues.Get("Policy")) // Verify signature. if !compareSignatureV4(newSignature, formValues.Get(xhttp.AmzSignature)) { return ErrSignatureDoesNotMatch } // Success. return ErrNone }
CWE-285
23
func (EmptyEvidencePool) CheckEvidence(evList types.EvidenceList) error { return nil }
CWE-400
2
func (evpool *Pool) AddEvidenceFromConsensus(ev types.Evidence) error { // we already have this evidence, log this but don't return an error. if evpool.isPending(ev) { evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev) return nil } // add evidence to a buffer which will pass the evidence to the pool at the following height. // This avoids the issue of some nodes verifying and proposing evidence at a height where the // block hasn't been committed on cause others to potentially fail. evpool.mtx.Lock() defer evpool.mtx.Unlock() evpool.consensusBuffer = append(evpool.consensusBuffer, ev) evpool.logger.Info("received new evidence of byzantine behavior from consensus", "evidence", ev) return nil }
CWE-400
2
func (svc Service) CountSoftware(ctx context.Context, opt fleet.SoftwareListOptions) (int, error) { if err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil { return 0, err } return svc.ds.CountSoftware(ctx, opt) }
CWE-863
11
func (svc *Service) ListUsers(ctx context.Context, opt fleet.UserListOptions) ([]*fleet.User, error) { if err := svc.authz.Authorize(ctx, &fleet.User{}, fleet.ActionRead); err != nil { return nil, err } return svc.ds.ListUsers(ctx, opt) }
CWE-863
11
func (svc *Service) DeleteGlobalScheduledQueries(ctx context.Context, id uint) error { if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionWrite); err != nil { return err } return svc.DeleteScheduledQuery(ctx, id) }
CWE-863
11
func (p *Profile) write() (pth string, err error) { rootDir, err := utils.GetTempDir() if err != nil { return } pth = filepath.Join(rootDir, p.Id) _ = os.Remove(pth) err = ioutil.WriteFile(pth, []byte(p.Data), os.FileMode(0600)) if err != nil { err = &WriteError{ errors.Wrap(err, "profile: Failed to write profile"), } return } return }
CWE-269
6
func MkdirSecure(pth string) (err error) { err = os.MkdirAll(pth, 0755) if err != nil { err = &errortypes.WriteError{ errors.Wrap(err, "utils: Failed to create directory"), } return } err = acl.Apply( pth, true, false, acl.GrantName(windows.GENERIC_ALL, "CREATOR OWNER"), acl.GrantName(windows.GENERIC_ALL, "SYSTEM"), acl.GrantName(windows.GENERIC_ALL, "Administrators"), ) if err != nil { err = &errortypes.WriteError{ errors.Wrap(err, "utils: Failed to acl directory"), } return } return }
CWE-269
6
func Skip(self Protocol, fieldType Type, maxDepth int) (err error) { if maxDepth <= 0 { return NewProtocolExceptionWithType(DEPTH_LIMIT, errors.New("Depth limit exceeded")) } switch fieldType { case STOP: return case BOOL: _, err = self.ReadBool() return case BYTE: _, err = self.ReadByte() return case I16: _, err = self.ReadI16() return case I32: _, err = self.ReadI32() return case I64: _, err = self.ReadI64() return case DOUBLE: _, err = self.ReadDouble() return case FLOAT: _, err = self.ReadFloat() return case STRING: _, err = self.ReadString() return case STRUCT: if _, err = self.ReadStructBegin(); err != nil { return err } for { _, typeId, _, _ := self.ReadFieldBegin() if typeId == STOP { break } err := Skip(self, typeId, maxDepth-1) if err != nil { return err } self.ReadFieldEnd() } return self.ReadStructEnd() case MAP: keyType, valueType, size, err := self.ReadMapBegin() if err != nil { return err } for i := 0; i < size; i++ { err := Skip(self, keyType, maxDepth-1) if err != nil { return err } self.Skip(valueType) } return self.ReadMapEnd() case SET: elemType, size, err := self.ReadSetBegin() if err != nil { return err } for i := 0; i < size; i++ { err := Skip(self, elemType, maxDepth-1) if err != nil { return err } } return self.ReadSetEnd() case LIST: elemType, size, err := self.ReadListBegin() if err != nil { return err } for i := 0; i < size; i++ { err := Skip(self, elemType, maxDepth-1) if err != nil { return err } } return self.ReadListEnd() } return nil }
CWE-755
21
func (f *Fosite) WriteAccessResponse(rw http.ResponseWriter, requester AccessRequester, responder AccessResponder) { rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") js, err := json.Marshal(responder.ToMap()) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/json;charset=UTF-8") rw.WriteHeader(http.StatusOK) rw.Write(js) }
CWE-755
21
func InstallNps() { path := common.GetInstallPath() if common.FileExists(path) { log.Fatalf("the path %s has exist, does not support install", path) } MkidrDirAll(path, "conf", "web/static", "web/views") //复制文件到对应目录 if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "views"), filepath.Join(path, "web", "views")); err != nil { log.Fatalln(err) } if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "static"), filepath.Join(path, "web", "static")); err != nil { log.Fatalln(err) } if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil { log.Fatalln(err) } if !common.IsWindows() { if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/bin/nps"); err != nil { if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/local/bin/nps"); err != nil { log.Fatalln(err) } else { os.Chmod("/usr/local/bin/nps", 0777) log.Println("Executable files have been copied to", "/usr/local/bin/nps") } } else { os.Chmod("/usr/bin/nps", 0777) log.Println("Executable files have been copied to", "/usr/bin/nps") } } log.Println("install ok!") log.Println("Static files and configuration files in the current directory will be useless") log.Println("The new configuration file is located in", path, "you can edit them") if !common.IsWindows() { log.Println("You can start with nps test|start|stop|restart|status anywhere") } else { log.Println("You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status") } }
CWE-732
13
ctx := log.WithContext(context.TODO(), func(c zerolog.Context) zerolog.Context { return c.Str("config_file_source", configFile) }) options, err := newOptionsFromConfig(configFile) if err != nil { return nil, err } ports, err := netutil.AllocatePorts(3) if err != nil { return nil, err } grpcPort := ports[0] httpPort := ports[1] outboundPort := ports[2] cfg := &Config{ Options: options, EnvoyVersion: envoyVersion, GRPCPort: grpcPort, HTTPPort: httpPort, OutboundPort: outboundPort, } metrics.SetConfigInfo(ctx, cfg.Options.Services, "local", cfg.Checksum(), true) src := &FileOrEnvironmentSource{ configFile: configFile, config: cfg, } options.viper.OnConfigChange(src.onConfigChange(ctx)) go options.viper.WatchConfig() return src, nil }
CWE-200
10
func TestService_ListSoftware(t *testing.T) { ds := new(mock.Store) var calledWithTeamID *uint var calledWithOpt fleet.SoftwareListOptions ds.ListSoftwareFunc = func(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) { calledWithTeamID = opt.TeamID calledWithOpt = opt return []fleet.Software{}, nil } user := &fleet.User{ID: 3, Email: "foo@bar.com", GlobalRole: ptr.String(fleet.RoleObserver)} svc := newTestService(t, ds, nil, nil) ctx := context.Background() ctx = viewer.NewContext(ctx, viewer.Viewer{User: user}) _, err := svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: ptr.Uint(42), ListOptions: fleet.ListOptions{PerPage: 77, Page: 4}}) require.NoError(t, err) assert.True(t, ds.ListSoftwareFuncInvoked) assert.Equal(t, ptr.Uint(42), calledWithTeamID) // sort order defaults to hosts_count descending, automatically, if not explicitly provided assert.Equal(t, fleet.ListOptions{PerPage: 77, Page: 4, OrderKey: "hosts_count", OrderDirection: fleet.OrderDescending}, calledWithOpt.ListOptions) assert.True(t, calledWithOpt.WithHostCounts) // call again, this time with an explicit sort ds.ListSoftwareFuncInvoked = false _, err = svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: nil, ListOptions: fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}}) require.NoError(t, err) assert.True(t, ds.ListSoftwareFuncInvoked) assert.Nil(t, calledWithTeamID) assert.Equal(t, fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}, calledWithOpt.ListOptions) assert.True(t, calledWithOpt.WithHostCounts) }
CWE-863
11
func (set *IdmapSet) doUidshiftIntoContainer(dir string, testmode bool, how string) error { convert := func(path string, fi os.FileInfo, err error) (e error) { uid, gid, err := GetOwner(path) if err != nil { return err } var newuid, newgid int switch how { case "in": newuid, newgid = set.ShiftIntoNs(uid, gid) case "out": newuid, newgid = set.ShiftFromNs(uid, gid) } if testmode { fmt.Printf("I would shift %q to %d %d\n", path, newuid, newgid) } else { err = os.Lchown(path, int(newuid), int(newgid)) if err == nil { m := fi.Mode() if m&os.ModeSymlink == 0 { err = os.Chmod(path, m) if err != nil { fmt.Printf("Error resetting mode on %q, continuing\n", path) } } } } return nil } if !PathExists(dir) { return fmt.Errorf("No such file or directory: %q", dir) } return filepath.Walk(dir, convert) }
CWE-362
18
func TestMsgGrantAuthorization(t *testing.T) { tests := []struct { title string granter, grantee sdk.AccAddress authorization authz.Authorization expiration time.Time expectErr bool expectPass bool }{ {"nil granter address", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil grantee address", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil granter and grantee address", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil authorization", granter, grantee, nil, time.Now(), true, false}, {"valid test case", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true}, {"past time", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false}, } for i, tc := range tests { msg, err := authz.NewMsgGrant( tc.granter, tc.grantee, tc.authorization, tc.expiration, ) if !tc.expectErr { require.NoError(t, err) } else { continue } if tc.expectPass { require.NoError(t, msg.ValidateBasic(), "test: %v", i) } else { require.Error(t, msg.ValidateBasic(), "test: %v", i) } } }
CWE-754
31
func (p *GitLabProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { // Retrieve user info userInfo, err := p.getUserInfo(ctx, s) if err != nil { return fmt.Errorf("failed to retrieve user info: %v", err) } // Check if email is verified if !p.AllowUnverifiedEmail && !userInfo.EmailVerified { return fmt.Errorf("user email is not verified") } s.User = userInfo.Username s.Email = userInfo.Email p.addGroupsToSession(ctx, s) p.addProjectsToSession(ctx, s) return nil }
CWE-863
11
func (mgr *MetricsManager) OnConfigChange(ctx context.Context, cfg *Config) { mgr.mu.Lock() defer mgr.mu.Unlock() mgr.updateInfo(cfg) mgr.updateServer(cfg) }
CWE-200
10
func Test_buildControlPlanePrefixRoute(t *testing.T) { b := &Builder{filemgr: filemgr.NewManager()} route, err := b.buildControlPlanePrefixRoute("/hello/world/", false) require.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "name": "pomerium-prefix-/hello/world/", "match": { "prefix": "/hello/world/" }, "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) }
CWE-200
10
func TestCheckValid(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() objLayer, fsDir, err := prepareFS() if err != nil { t.Fatal(err) } defer os.RemoveAll(fsDir) if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil { t.Fatalf("unable initialize config file, %s", err) } newAllSubsystems() initConfigSubsystem(ctx, objLayer) globalIAMSys.Init(ctx, objLayer, globalEtcdClient, globalNotificationSys, 2*time.Second) req, err := newTestRequest(http.MethodGet, "http://example.com:9000/bucket/object", 0, nil) if err != nil { t.Fatal(err) } if err = signRequestV4(req, globalActiveCred.AccessKey, globalActiveCred.SecretKey); err != nil { t.Fatal(err) } _, owner, s3Err := checkKeyValid(req, globalActiveCred.AccessKey) if s3Err != ErrNone { t.Fatalf("Unexpected failure with %v", errorCodes.ToAPIErr(s3Err)) } if !owner { t.Fatalf("Expected owner to be 'true', found %t", owner) } _, _, s3Err = checkKeyValid(req, "does-not-exist") if s3Err != ErrInvalidAccessKeyID { t.Fatalf("Expected error 'ErrInvalidAccessKeyID', found %v", s3Err) } ucreds, err := auth.CreateCredentials("myuser1", "mypassword1") if err != nil { t.Fatalf("unable create credential, %s", err) } globalIAMSys.CreateUser(ctx, ucreds.AccessKey, madmin.UserInfo{ SecretKey: ucreds.SecretKey, Status: madmin.AccountEnabled, }) _, owner, s3Err = checkKeyValid(req, ucreds.AccessKey) if s3Err != ErrNone { t.Fatalf("Unexpected failure with %v", errorCodes.ToAPIErr(s3Err)) } if owner { t.Fatalf("Expected owner to be 'false', found %t", owner) } }
CWE-863
11
func NewGrant(a Authorization, expiration time.Time) (Grant, error) { g := Grant{ Expiration: expiration, } msg, ok := a.(proto.Message) if !ok { return Grant{}, sdkerrors.Wrapf(sdkerrors.ErrPackAny, "cannot proto marshal %T", a) } any, err := cdctypes.NewAnyWithValue(msg) if err != nil { return Grant{}, err } g.Authorization = any return g, nil }
CWE-754
31
func (sys *IAMSys) CreateUser(ctx context.Context, accessKey string, uinfo madmin.UserInfo) error { if !sys.Initialized() { return errServerNotInitialized } if sys.usersSysType != MinIOUsersSysType { return errIAMActionNotAllowed } if !auth.IsAccessKeyValid(accessKey) { return auth.ErrInvalidAccessKeyLength } if !auth.IsSecretKeyValid(uinfo.SecretKey) { return auth.ErrInvalidSecretKeyLength } err := sys.store.AddUser(ctx, accessKey, uinfo) if err != nil { return err } sys.notifyForUser(ctx, accessKey, false) return nil }
CWE-863
11
func (evpool *Pool) AddEvidence(ev types.Evidence) error { evpool.logger.Debug("Attempting to add evidence", "ev", ev) // We have already verified this piece of evidence - no need to do it again if evpool.isPending(ev) { evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev) return nil } // check that the evidence isn't already committed if evpool.isCommitted(ev) { // this can happen if the peer that sent us the evidence is behind so we shouldn't // punish the peer. evpool.logger.Debug("Evidence was already committed, ignoring this one", "ev", ev) return nil } // 1) Verify against state. err := evpool.verify(ev) if err != nil { return types.NewErrInvalidEvidence(ev, err) } // 2) Save to store. if err := evpool.addPendingEvidence(ev); err != nil { return fmt.Errorf("can't add evidence to pending list: %w", err) } // 3) Add evidence to clist. evpool.evidenceList.PushBack(ev) evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev) return nil }
CWE-400
2
func (f *Fosite) writeJsonError(rw http.ResponseWriter, err error) { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") rfcerr := ErrorToRFC6749Error(err) if !f.SendDebugMessagesToClients { rfcerr = rfcerr.Sanitize() } js, err := json.Marshal(rfcerr) if err != nil { if f.SendDebugMessagesToClients { errorMessage := EscapeJSONString(err.Error()) http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError) } else { http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError) } return } rw.WriteHeader(rfcerr.Code) rw.Write(js) }
CWE-755
21
func (a *AuthenticatorOAuth2Introspection) traceRequest(ctx context.Context, req *http.Request) func() { tracer := opentracing.GlobalTracer() if tracer == nil { return func() {} } parentSpan := opentracing.SpanFromContext(ctx) opts := make([]opentracing.StartSpanOption, 0, 1) if parentSpan != nil { opts = append(opts, opentracing.ChildOf(parentSpan.Context())) } urlStr := req.URL.String() clientSpan := tracer.StartSpan(req.Method+" "+urlStr, opts...) ext.SpanKindRPCClient.Set(clientSpan) ext.HTTPUrl.Set(clientSpan, urlStr) ext.HTTPMethod.Set(clientSpan, req.Method) tracer.Inject(clientSpan.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)) return clientSpan.Finish }
CWE-863
11
func LoadAll(basedir string) ([]*Plugin, error) { plugins := []*Plugin{} // We want basedir/*/plugin.yaml scanpath := filepath.Join(basedir, "*", PluginFileName) matches, err := filepath.Glob(scanpath) if err != nil { return plugins, err } if matches == nil { return plugins, nil } for _, yaml := range matches { dir := filepath.Dir(yaml) p, err := LoadDir(dir) if err != nil { return plugins, err } plugins = append(plugins, p) } return plugins, nil }
CWE-74
1
func (EmptyEvidencePool) AddEvidence(types.Evidence) error { return nil }
CWE-400
2
func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error { // First get a list of a all tmpfs mounts tmpfs := []string{} for _, m := range mounts { switch m.Device { case "tmpfs": tmpfs = append(tmpfs, m.Destination) } } // Now go through all mounts and create the mountpoints // if the mountpoints are not on a tmpfs, as CRIU will // restore the complete tmpfs content from its checkpoint. umounts := []string{} defer func() { for _, u := range umounts { if e := unix.Unmount(u, unix.MNT_DETACH); e != nil { if e != unix.EINVAL { // Ignore EINVAL as it means 'target is not a mount point.' // It probably has already been unmounted. logrus.Warnf("Error during cleanup unmounting of %q (%v)", u, e) } } } }() for _, m := range mounts { if !isPathInPrefixList(m.Destination, tmpfs) { if err := c.makeCriuRestoreMountpoints(m); err != nil { return err } // If the mount point is a bind mount, we need to mount // it now so that runc can create the necessary mount // points for mounts in bind mounts. // This also happens during initial container creation. // Without this CRIU restore will fail // See: https://github.com/opencontainers/runc/issues/2748 // It is also not necessary to order the mount points // because during initial container creation mounts are // set up in the order they are configured. if m.Device == "bind" { if err := unix.Mount(m.Source, m.Destination, "", unix.MS_BIND|unix.MS_REC, ""); err != nil { return errorsf.Wrapf(err, "unable to bind mount %q to %q", m.Source, m.Destination) } umounts = append(umounts, m.Destination) } } } return nil }
CWE-362
18
func (i *IDTokenHandleHelper) GetAccessTokenHash(ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder) string { token := responder.GetAccessToken() buffer := bytes.NewBufferString(token) hash := sha256.New() hash.Write(buffer.Bytes()) hashBuf := bytes.NewBuffer(hash.Sum([]byte{})) len := hashBuf.Len() return base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:len/2]) }
CWE-755
21
func LoadDir(dirname string) (*Plugin, error) { data, err := ioutil.ReadFile(filepath.Join(dirname, PluginFileName)) if err != nil { return nil, err } plug := &Plugin{Dir: dirname} if err := yaml.Unmarshal(data, &plug.Metadata); err != nil { return nil, err } return plug, nil }
CWE-74
1
func Test_buildRouteConfiguration(t *testing.T) { b := New("local-grpc", "local-http", nil, nil) virtualHosts := make([]*envoy_config_route_v3.VirtualHost, 10) routeConfig, err := b.buildRouteConfiguration("test-route-configuration", virtualHosts) require.NoError(t, err) assert.Equal(t, "test-route-configuration", routeConfig.GetName()) assert.Equal(t, virtualHosts, routeConfig.GetVirtualHosts()) assert.False(t, routeConfig.GetValidateClusters().GetValue()) }
CWE-200
10
func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, cond C.scmp_cast_t) error { var length C.uint if cond != nil { length = 1 } else { length = 0 } var retCode C.int if exact { retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond) } else { retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond) } if syscall.Errno(-1*retCode) == syscall.EFAULT { return fmt.Errorf("unrecognized syscall") } else if syscall.Errno(-1*retCode) == syscall.EPERM { return fmt.Errorf("requested action matches default action of filter") } else if retCode != 0 { return syscall.Errno(-1 * retCode) } return nil }
CWE-20
0
func mountCgroupV2(m *configs.Mount, c *mountConfig) error { dest, err := securejoin.SecureJoin(c.root, m.Destination) if err != nil { return err } if err := os.MkdirAll(dest, 0755); err != nil { return err } if err := unix.Mount(m.Source, dest, "cgroup2", uintptr(m.Flags), m.Data); err != nil { // when we are in UserNS but CgroupNS is not unshared, we cannot mount cgroup2 (#2158) if err == unix.EPERM || err == unix.EBUSY { src := fs2.UnifiedMountpoint if c.cgroupns && c.cgroup2Path != "" { // Emulate cgroupns by bind-mounting // the container cgroup path rather than // the whole /sys/fs/cgroup. src = c.cgroup2Path } err = unix.Mount(src, dest, "", uintptr(m.Flags)|unix.MS_BIND, "") if err == unix.ENOENT && c.rootlessCgroups { err = nil } return err } return err } return nil }
CWE-362
18
func TestAddDebug(t *testing.T) { err := ErrRevocationClientMismatch.WithDebug("debug") assert.NotEqual(t, err, ErrRevocationClientMismatch) assert.Empty(t, ErrRevocationClientMismatch.Debug) assert.NotEmpty(t, err.Debug) }
CWE-755
21
func (f *Fosite) WriteRevocationResponse(rw http.ResponseWriter, err error) { rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") if err == nil { rw.WriteHeader(http.StatusOK) return } if errors.Is(err, ErrInvalidRequest) { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") js, err := json.Marshal(ErrInvalidRequest) if err != nil { http.Error(rw, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError) return } rw.WriteHeader(ErrInvalidRequest.Code) rw.Write(js) } else if errors.Is(err, ErrInvalidClient) { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") js, err := json.Marshal(ErrInvalidClient) if err != nil { http.Error(rw, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError) return } rw.WriteHeader(ErrInvalidClient.Code) rw.Write(js) } else { // 200 OK rw.WriteHeader(http.StatusOK) } }
CWE-755
21
func doesPolicySignatureMatch(formValues http.Header) APIErrorCode { // For SignV2 - Signature field will be valid if _, ok := formValues["Signature"]; ok { return doesPolicySignatureV2Match(formValues) } return doesPolicySignatureV4Match(formValues) }
CWE-285
23
func (svc *Service) ListHostDeviceMapping(ctx context.Context, id uint) ([]*fleet.HostDeviceMapping, error) { if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) { if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { return nil, err } host, err := svc.ds.HostLite(ctx, id) if err != nil { return nil, ctxerr.Wrap(ctx, err, "get host") } // Authorize again with team loaded now that we have team_id if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return nil, err } } return svc.ds.ListHostDeviceMapping(ctx, id) }
CWE-863
11
func isAdminOfTheModifiedTeams(currentUser *fleet.User, originalUserTeams, newUserTeams []fleet.UserTeam) bool { // If the user is of the right global role, then they can modify the teams if currentUser.GlobalRole != nil && (*currentUser.GlobalRole == fleet.RoleAdmin || *currentUser.GlobalRole == fleet.RoleMaintainer) { return true } // otherwise, gather the resulting teams resultingTeams := make(map[uint]string) for _, team := range newUserTeams { resultingTeams[team.ID] = team.Role } // and see which ones were removed or changed from the original teamsAffected := make(map[uint]struct{}) for _, team := range originalUserTeams { if resultingTeams[team.ID] != team.Role { teamsAffected[team.ID] = struct{}{} } } // then gather the teams the current user is admin for currentUserTeamAdmin := make(map[uint]struct{}) for _, team := range currentUser.Teams { if team.Role == fleet.RoleAdmin { currentUserTeamAdmin[team.ID] = struct{}{} } } // and let's check that the teams that were either removed or changed are also teams this user is an admin of for teamID := range teamsAffected { if _, ok := currentUserTeamAdmin[teamID]; !ok { return false } } return true }
CWE-863
11
func Test_requireProxyProtocol(t *testing.T) { b := New("local-grpc", "local-http", nil, nil) t.Run("required", func(t *testing.T) { li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{ UseProxyProtocol: true, InsecureServer: true, }}) require.NoError(t, err) testutil.AssertProtoJSONEqual(t, `[ { "name": "envoy.filters.listener.proxy_protocol", "typedConfig": { "@type": "type.googleapis.com/envoy.extensions.filters.listener.proxy_protocol.v3.ProxyProtocol" } } ]`, li.GetListenerFilters()) }) t.Run("not required", func(t *testing.T) { li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{ UseProxyProtocol: false, InsecureServer: true, }}) require.NoError(t, err) assert.Len(t, li.GetListenerFilters(), 0) }) }
CWE-200
10
func createDeviceNode(rootfs string, node *devices.Device, bind bool) error { if node.Path == "" { // The node only exists for cgroup reasons, ignore it here. return nil } dest := filepath.Join(rootfs, node.Path) if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { return err } if bind { return bindMountDeviceNode(dest, node) } if err := mknodDevice(dest, node); err != nil { if os.IsExist(err) { return nil } else if os.IsPermission(err) { return bindMountDeviceNode(dest, node) } return err } return nil }
CWE-362
18
func (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string) { if !config.Cache.Enabled { return } if a.cacheTTL != nil { a.tokenCache.SetWithTTL(token, i, 1, *a.cacheTTL) } else { a.tokenCache.Set(token, i, 1) } }
CWE-863
11
func (svc *Service) OSVersions(ctx context.Context, teamID *uint, platform *string) (*fleet.OSVersions, error) { if err := svc.authz.Authorize(ctx, &fleet.Host{TeamID: teamID}, fleet.ActionList); err != nil { return nil, err } osVersions, err := svc.ds.OSVersions(ctx, teamID, platform) if err != nil { return nil, err } return osVersions, nil }
CWE-863
11
func logNamespaceDiagnostics(spec *specs.Spec) { sawMountNS := false sawUserNS := false sawUTSNS := false for _, ns := range spec.Linux.Namespaces { switch ns.Type { case specs.CgroupNamespace: if ns.Path != "" { logrus.Debugf("unable to join cgroup namespace, sorry about that") } else { logrus.Debugf("unable to create cgroup namespace, sorry about that") } case specs.IPCNamespace: if ns.Path != "" { logrus.Debugf("unable to join IPC namespace, sorry about that") } else { logrus.Debugf("unable to create IPC namespace, sorry about that") } case specs.MountNamespace: if ns.Path != "" { logrus.Debugf("unable to join mount namespace %q, creating a new one", ns.Path) } sawMountNS = true case specs.NetworkNamespace: if ns.Path != "" { logrus.Debugf("unable to join network namespace, sorry about that") } else { logrus.Debugf("unable to create network namespace, sorry about that") } case specs.PIDNamespace: if ns.Path != "" { logrus.Debugf("unable to join PID namespace, sorry about that") } else { logrus.Debugf("unable to create PID namespace, sorry about that") } case specs.UserNamespace: if ns.Path != "" { logrus.Debugf("unable to join user namespace %q, creating a new one", ns.Path) } sawUserNS = true case specs.UTSNamespace: if ns.Path != "" { logrus.Debugf("unable to join UTS namespace %q, creating a new one", ns.Path) } sawUTSNS = true } } if !sawMountNS { logrus.Debugf("mount namespace not requested, but creating a new one anyway") } if !sawUserNS { logrus.Debugf("user namespace not requested, but creating a new one anyway") } if !sawUTSNS { logrus.Debugf("UTS namespace not requested, but creating a new one anyway") } }
CWE-200
10
func (svc *Service) User(ctx context.Context, id uint) (*fleet.User, error) { if err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionRead); err != nil { return nil, err } return svc.ds.UserByID(ctx, id) }
CWE-863
11
signBufferFunc: (chunk: Buffer) => makeMessageChunkSignatureWithDerivedKeys(chunk, derivedKeys), signatureLength: derivedKeys.signatureLength, sequenceHeaderSize: 0, }; const securityHeader = new SymmetricAlgorithmSecurityHeader({ tokenId: 10 }); const msgChunkManager = new SecureMessageChunkManager("MSG", options, securityHeader, sequenceNumberGenerator); msgChunkManager.on("chunk", (chunk, final) => callback(null, chunk)); msgChunkManager.write(buffer, buffer.length); msgChunkManager.end(); }
CWE-400
2
async function installMonitoredItem(subscription, nodeId) { debugLog("installMonitoredItem", nodeId.toString()); const monitoredItem = await subscription.monitor( { nodeId, attributeId: AttributeIds.Value }, { samplingInterval: 0, // reports immediately discardOldest: true, queueSize: 10 }, TimestampsToReturn.Both, MonitoringMode.Reporting ); const recordedValue = []; monitoredItem.on("changed", function (dataValue) { recordedValue.push(dataValue.value.value); debugLog("change =", recordedValue); }); return await new Promise((resolve, reject) => { const timer = setTimeout(() => { reject(new Error("Never received changedx for id" + nodeId.toString())); }, 5000); monitoredItem.once("changed", function (dataValue) { clearTimeout(timer); resolve([recordedValue, monitoredItem]); }); }); }
CWE-400
2
static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) { // # Parse data as unsigned-big-endian encoded integer. // # For empty data different possibilities may occur: // # minByteLen <= 0 : return 0 // # raise_on_Null == False and minByteLen > 0: return None // # raise_on_Null == True and minByteLen > 0: raise SlpInvalidOutputMessage if(intBytes.length >= minByteLen && intBytes.length <= maxByteLen) return intBytes.readUIntBE(0, intBytes.length) if(intBytes.length === 0 && !raise_on_Null) return null; throw Error('Field has wrong length'); }
CWE-20
0
response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing); } await send_registered_server_request(discoveryServerEndpointUrl, request, check_response); });
CWE-400
2
export function getExtensionPath(): string { return extensionPath; }
CWE-863
11
html: html({ url, host, theme }), }) const failed = result.rejected.concat(result.pending).filter(Boolean) if (failed.length) { throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`) } }, options, } }
CWE-863
11
calculateMintCost(mintOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) { return this.calculateMintOrGenesisCost(mintOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate); }
CWE-20
0
function sendResponse(response1: Response) { try { assert(response1 instanceof ResponseClass); if (message.session) { const counterName = ResponseClass.name.replace("Response", ""); message.session.incrementRequestTotalCounter(counterName); } return channel.send_response("MSG", response1, message); } catch (err) { warningLog(err); // istanbul ignore next if (err instanceof Error) { // istanbul ignore next errorLog( "Internal error in issuing response\nplease contact support@sterfive.com", message.request.toString(), "\n", response1.toString() ); } // istanbul ignore next throw err; } }
CWE-400
2
}validateOrReject(Object.assign(new Validators.${checker.typeToString(v.type)}(), req.${ v.name }), validatorOptions)${v.hasQuestion ? ' : null' : ''}` : '' ) .join(',\n')}\n ])`
CWE-20
0
async signup(params: any) { // Check if the installation allows user signups if (process.env.DISABLE_SIGNUPS === 'true') { return {}; } const { email } = params; const existingUser = await this.usersService.findByEmail(email); if (existingUser) { throw new NotAcceptableException('Email already exists'); } const organization = await this.organizationsService.create('Untitled organization'); const user = await this.usersService.create({ email }, organization, ['all_users', 'admin']); // eslint-disable-next-line @typescript-eslint/no-unused-vars const organizationUser = await this.organizationUsersService.create(user, organization); await this.emailService.sendWelcomeEmail(user.email, user.firstName, user.invitationToken); return {}; }
CWE-74
1
} actionItems() { let composing = new PrivateComposing(this.user); const items = new ItemList(); if (app.session.user && app.forum.attribute('canStartPrivateDiscussion')) { items.add('start_private', composing.component()); }
CWE-269
6
.catch(error => { // There was an error with the session token const result = {}; if (error && error.code === Parse.Error.INVALID_SESSION_TOKEN) { // Store a resolved promise with the error for 10 minutes result.error = error; this.authCache.set( sessionToken, Promise.resolve(result), 60 * 10 * 1000 ); } else {
CWE-672
37
Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null ])
CWE-20
0
use: (path) => { useCount++; expect(path).toEqual('somepath'); },
CWE-863
11
static buildMintOpReturn(config: configBuildMintOpReturn, type = 0x01) { return SlpTokenType1.buildMintOpReturn( config.tokenIdHex, config.batonVout, config.mintQuantity, type ) }
CWE-20
0
type: new GraphQLNonNull(parseGraphQLSchema.viewerType), async resolve(_source, _args, context, queryInfo) { try { const { config, info } = context; return await getUserFromSessionToken( config, info, queryInfo, 'user.', false ); } catch (e) { parseGraphQLSchema.handleError(e); } }, }, true, true ); };
CWE-863
11
module.exports = (env) => { const toReplace = Object.keys(env).filter((envVar) => { // https://github.com/semantic-release/semantic-release/issues/1558 if (envVar === 'GOPRIVATE') { return false; } return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE; }); const regexp = new RegExp(toReplace.map((envVar) => escapeRegExp(env[envVar])).join('|'), 'g'); return (output) => output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output; };
CWE-116
15
export async function getApi(constructor = Gists) { const token = await getToken(); const apiurl = config.get("apiUrl"); if (!apiurl) { const message = "No API URL is set."; throw new Error(message); } return new constructor({ apiurl, token }); }
CWE-863
11
get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } }) }))
CWE-20
0
callParserIfExistsQuery(parseNumberTypeQueryParams([['requiredNum', false, false], ['optionalNum', true, false], ['optionalNumArr', true, true], ['emptyNum', true, false], ['requiredNumArr', false, true]])), callParserIfExistsQuery(parseBooleanTypeQueryParams([['bool', false, false], ['optionalBool', true, false], ['boolArray', false, true], ['optionalBoolArray', true, true]])), normalizeQuery, createValidateHandler(req => [ Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null ]) ] }, asyncMethodToHandler(controller0.get) )
CWE-20
0
const addReplyToEvent = (event: any) => { event.reply = (...args: any[]) => { event.sender.sendToFrame(event.frameId, ...args); }; };
CWE-668
7
async function validateSystemTransfer( message: Message, meta: ConfirmedTransactionMeta, recipient: Recipient ): Promise<[BigNumber, BigNumber]> { const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipient)); if (accountIndex === -1) throw new ValidateTransferError('recipient not found'); return [ new BigNumber(meta.preBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL), new BigNumber(meta.postBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL), ]; }
CWE-670
36
on(eventName: "message", eventHandler: (message: Buffer) => void): this;
CWE-400
2
export function cloneMirrorTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): StringTask<string> { append(customArgs,'--mirror'); return cloneTask(repo, directory, customArgs); }
CWE-77
14
link: new ApolloLink((operation, forward) => { return forward(operation).map((response) => { const context = operation.getContext(); const { response: { headers }, } = context; expect(headers.get('access-control-allow-origin')).toEqual('*'); checked = true; return response; }); }).concat( createHttpLink({ uri: 'http://localhost:13377/graphql', fetch, headers: { ...headers, Origin: 'http://someorigin.com', }, }) ), cache: new InMemoryCache(), });
CWE-863
11
await getManager().transaction(async (manager) => { const organizationUser = await manager.findOne(OrganizationUser, { where: { id } }); const user = await manager.findOne(User, { where: { id: organizationUser.userId } }); await this.usersService.throwErrorIfRemovingLastActiveAdmin(user); await manager.update(User, user.id, { invitationToken: null }); await manager.update(OrganizationUser, id, { status: 'archived' }); });
CWE-74
1
const errorHandler = (err: Error) => { this._cancel_wait_for_open_secure_channel_request_timeout(); this.messageBuilder.removeListener("message", messageHandler); this.close(() => { callback(new Error("/Expecting OpenSecureChannelRequest to be valid " + err.message)); }); };
CWE-400
2
function simulateTransation(request: FindServersRequest, response: FindServersResponse, callback: SimpleCallback) { serverSChannel.once("message", (message: Message) => { doDebug && console.log("server receiving message =", response.responseHeader.requestHandle); response.responseHeader.requestHandle = message.request.requestHeader.requestHandle; serverSChannel.send_response("MSG", response, message, () => { /** */ doDebug && console.log("server message sent ", response.responseHeader.requestHandle); }); }); doDebug && console.log(" now sending a request " + request.constructor.name); clientChannel.performMessageTransaction(request, (err, response) => { doDebug && console.log("client received a response ", response?.constructor.name); doDebug && console.log(response?.toString()); callback(err || undefined); }); }
CWE-400
2
parseGraphQLServer._getGraphQLOptions = async (req) => { expect(req.info).toBeDefined(); expect(req.config).toBeDefined(); expect(req.auth).toBeDefined(); checked = true; return await originalGetGraphQLOptions.bind(parseGraphQLServer)(req); };
CWE-863
11
export function fetchRemoteBranch(remote: string, remoteBranch: string, cwd: string) { const results = git(["fetch", remote, remoteBranch], { cwd }); if (!results.success) { throw gitError(`Cannot fetch remote: ${remote} ${remoteBranch}`); } }
CWE-77
14
stitchSchemas({ subschemas: [autoSchema] }), }); parseGraphQLServer.applyGraphQL(expressApp); await new Promise((resolve) => httpServer.listen({ port: 13377 }, resolve) ); const httpLink = createUploadLink({ uri: 'http://localhost:13377/graphql', fetch, headers, }); apolloClient = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), defaultOptions: { query: { fetchPolicy: 'no-cache', }, }, }); }); afterAll(async () => { await httpServer.close(); }); it('can resolve a query', async () => { const result = await apolloClient.query({ query: gql` query Health { health } `, }); expect(result.data.health).toEqual(true); }); });
CWE-863
11
async function validateSPLTokenTransfer( message: Message, meta: ConfirmedTransactionMeta, recipient: Recipient, splToken: SPLToken ): Promise<[BigNumber, BigNumber]> { const recipientATA = await getAssociatedTokenAddress(splToken, recipient); const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipientATA)); if (accountIndex === -1) throw new ValidateTransferError('recipient not found'); const preBalance = meta.preTokenBalances?.find((x) => x.accountIndex === accountIndex); const postBalance = meta.postTokenBalances?.find((x) => x.accountIndex === accountIndex); return [ new BigNumber(preBalance?.uiTokenAmount.uiAmountString || 0), new BigNumber(postBalance?.uiTokenAmount.uiAmountString || 0), ]; }
CWE-670
36
.on("message", (request, msgType, requestId, channelId) => { this._on_common_message(request, msgType, requestId, channelId); })
CWE-400
2
@action gotoUrl = (_url) => { transaction(() => { let url = (_url || this.nextUrl).trim().replace(/\/+$/, ''); if (!hasProtocol.test(url)) { url = `https://${url}`; } this.setNextUrl(url); this.setCurrentUrl(this.nextUrl); }); }
CWE-346
16
async function decodeMessage(buffer: Buffer): Promise<any> { /* const offset = 16 * 3 + 6; buffer = buffer.slice(offset); */ const messageBuilder = new MessageBuilder({}); messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None); let objMessage: any = null; messageBuilder.once("full_message_body", (fullMessageBody: Buffer) => { const stream = new BinaryStream(fullMessageBody); const id = decodeExpandedNodeId(stream); objMessage = constructObject(id); objMessage.decode(stream); }); messageBuilder.feed(buffer); return objMessage; }
CWE-400
2