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....
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 :=...
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...
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 { ...
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 { logge...
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" }, ...
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.(*A...
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{}, &confi...
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 ...
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...
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 wi...
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...
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 { exceededM...
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...
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...
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...
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() { ...
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.ListActi...
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 :...
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 evide...
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 wri...
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.GE...
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 c...
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.StatusInternalServerE...
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",...
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 := port...
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 []flee...
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(...
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{Spe...
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.EmailVeri...
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/worl...
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 ...
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{}, ...
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.ErrInvalidAccessKeyLengt...
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 } ...
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...
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 = ap...
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 ma...
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 // i...
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{}...
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",...
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, con...
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 ...
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;ch...
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(c...
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...
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) t...
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 b...
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(toke...
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 n...
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.De...
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...
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: tru...
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 == Fal...
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(c...
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('...
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( s...
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.', ...
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()) >= SE...
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', tr...
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('recip...
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')...
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); ...
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.m...
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); resp...
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', ...
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((...
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; messageBuilde...
CWE-400
2