// InspectToken returns information about the machine token.
//
// Inspection.Envelope is either nil or *tokenserver.MachineTokenEnvelope.
// Inspection.Body is either nil or *tokenserver.MachineTokenBody.
973892
func InspectToken(c context.Context, certs tokensigning.CertificatesSupplier, tok string) (*tokensigning.Inspection, error) {
	i := tokensigning.Inspector{
		Encoding:       base64.RawStdEncoding,
		Certificates:   certs,
		SigningContext: tokenSigningContext,
		Envelope:       func() proto.Message { return &tokenserver.MachineTokenEnvelope{} },
		Body:           func() proto.Message { return &tokenserver.MachineTokenBody{} },
		Unwrap: func(e proto.Message) tokensigning.Unwrapped {
			env := e.(*tokenserver.MachineTokenEnvelope)
			return tokensigning.Unwrapped{
				Body:         env.TokenBody,
				RsaSHA256Sig: env.RsaSha256,
				KeyID:        env.KeyId,
			}
		},
		Lifespan: func(b proto.Message) tokensigning.Lifespan {
			body := b.(*tokenserver.MachineTokenBody)
			return tokensigning.Lifespan{
				NotBefore: time.Unix(int64(body.IssuedAt), 0),
				NotAfter:  time.Unix(int64(body.IssuedAt)+int64(body.Lifetime), 0),
			}
		},
	}
	return i.InspectToken(c, tok)
}
799654
func (m *Middleware) VerifyToken(token string, v VerifyClaimsFunc, r *http.Request) (int, string, error) {
	tokenParts := strings.Split(token, ".")
	if len(tokenParts) != 3 {
		return http.StatusUnauthorized, "", ErrMalformedToken
	}

	// First, verify JOSE header
	header, err := decode(tokenParts[0])
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("decoding header (%v)", tokenParts[0]), err
	}
	var t struct {
		Typ string
		Alg string
	}
	err = json.Unmarshal(header, &t)
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("unmarshalling header (%s)", header), ErrMalformedToken
	}

	// Then, verify signature
	mac := hmac.New(sha256.New, []byte(m.secret))
	message := []byte(strings.Join([]string{tokenParts[0], tokenParts[1]}, "."))
	mac.Write(message)
	expectedMac, err := encode(mac.Sum(nil))
	if err != nil {
		return http.StatusInternalServerError, "", err
	}
	if !hmac.Equal([]byte(tokenParts[2]), []byte(expectedMac)) {
		return http.StatusUnauthorized, fmt.Sprintf("checking signature (%v)", tokenParts[2]), ErrInvalidSignature
	}

	// Finally, check claims
	claimSet, err := decode(tokenParts[1])
	if err != nil {
		return http.StatusInternalServerError, "decoding claims", ErrDecoding
	}
	err = v(claimSet, r)
	if err != nil {
		return http.StatusUnauthorized, "handling claims callback", err
	}

	return 200, "", nil
}
1357849
func (c *Container) Inspect(ctx context.Context) (*enginetypes.VirtualizationInfo, error) {
	if c.Engine == nil {
		return nil, ErrNilEngine
	}
	inspectCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	return c.Engine.VirtualizationInspect(inspectCtx, c.ID)
}
169221
func (p *Parser) PeekN(shift int, typ TokenType, val string) *Token {
	t := p.Get(p.idx + shift)
	if t != nil {
		if t.Typ == typ && t.Val == val {
			return t
		}
	}
	return nil
}
155689
func VerifyToken(c *messagebird.Client, id, token string) (*Verify, error) {
	params := &url.Values{}
	params.Set("token", token)

	pathWithParams := path + "/" + id + "?" + params.Encode()

	verify := &Verify{}
	if err := c.Request(verify, http.MethodGet, pathWithParams, nil); err != nil {
		return nil, err
	}

	return verify, nil
}
121809
func (m *LexTokenPager) Peek() lex.Token {
	if len(m.tokens) <= m.cursor+1 && !m.done {
		m.lexNext()
	}
	if len(m.tokens) < 2 {
		m.lexNext()
	}
	if len(m.tokens) == m.cursor+1 {
		return m.tokens[m.cursor]
	}
	if m.cursor == -1 {
		return m.tokens[1]
	}
	return m.tokens[m.cursor+1]
}
1928
func (l *Lexer) PeekNextTokenType() token.Type {
	if len(l.input)-1 > l.pos {
		ch := l.input[l.pos]
		return resolveTokenType(ch)
	}
	return resolveTokenType(0) // EOF
}
373003
func (r *Lexer) scanToken() {
	if r.token.kind != tokenUndef || r.fatalError != nil {
		return
	}

	r.FetchToken()
}
372785
func (*AMQPConnector) InspectQueue(channel *amqp.Channel, queueName string) (*amqp.Queue, error) {
	queueState, err := channel.QueueInspect(queueName)
	if err != nil {
		return nil, fmt.Errorf("Queue inspect error: %s", err)
	}

	return &queueState, nil
}
448371
func (s *ClusterPairServer) Inspect(
	ctx context.Context,
	req *api.SdkClusterPairInspectRequest,
) (*api.SdkClusterPairInspectResponse, error) {
	if s.cluster() == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if len(req.GetId()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply cluster ID")
	}
	resp, err := s.cluster().GetPair(req.GetId())
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Cannot Get cluster information for %s : %v", req.GetId(), err)
	}
	return &api.SdkClusterPairInspectResponse{
		Result: resp,
	}, nil
}
236345
func (ens *NetpluginNameServer) InspectState() (interface{}, error) {

	s := struct {
		SvcChan int                                       `json:"serviceQueue"`
		EpChan  int                                       `json:"endpointQueue"`
		Dtbl    map[string]map[string]map[string][]string `json:"dnsRecords"`
		Stats   map[string]map[string]uint64              `json:"stats"`
	}{SvcChan: len(ens.svcChan), EpChan: len(ens.epChan),
		Dtbl: ens.inspectNameRecord(), Stats: ens.inspectStats()}
	return &s, nil
}
1208727
func (r *InspectOAuthTokenGrantRPC) InspectOAuthTokenGrant(c context.Context, req *admin.InspectOAuthTokenGrantRequest) (*admin.InspectOAuthTokenGrantResponse, error) {
	inspection, err := InspectGrant(c, r.Signer, req.Token)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	resp := &admin.InspectOAuthTokenGrantResponse{
		Valid:            inspection.Signed && inspection.NonExpired,
		Signed:           inspection.Signed,
		NonExpired:       inspection.NonExpired,
		InvalidityReason: inspection.InvalidityReason,
	}

	addInvalidityReason := func(msg string, args ...interface{}) {
		reason := fmt.Sprintf(msg, args...)
		resp.Valid = false
		if resp.InvalidityReason == "" {
			resp.InvalidityReason = reason
		} else {
			resp.InvalidityReason += "; " + reason
		}
	}

	if env, _ := inspection.Envelope.(*tokenserver.OAuthTokenGrantEnvelope); env != nil {
		resp.SigningKeyId = env.KeyId
	}

	// Examine the body, even if the token is expired or unsigned. This helps to
	// debug expired or unsigned tokens...
	resp.TokenBody, _ = inspection.Body.(*tokenserver.OAuthTokenGrantBody)
	if resp.TokenBody != nil {
		rules, err := r.Rules(c)
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to load service accounts rules")
		}

		// Always return the rule that matches the service account, even if the
		// token itself is not allowed by it (we check it separately below).
		rule, err := rules.Rule(c, resp.TokenBody.ServiceAccount, "")
		switch {
		case status.Code(err) == codes.PermissionDenied:
			s, _ := status.FromError(err)
			addInvalidityReason("%s", s.Message())
			return resp, nil
		case err != nil: // usually codes.Internal
			return nil, err
		default:
			resp.MatchingRule = rule.Rule
		}

		q := &RulesQuery{
			ServiceAccount: resp.TokenBody.ServiceAccount,
			Rule:           rule,
			Proxy:          identity.Identity(resp.TokenBody.Proxy),
			EndUser:        identity.Identity(resp.TokenBody.EndUser),
		}
		switch _, err = rules.Check(c, q); {
		case err == nil:
			resp.AllowedByRules = true
		case status.Code(err) == codes.Internal:
			return nil, err // a transient error when checking rules
		default: // fatal gRPC error => the rules forbid the token
			addInvalidityReason("not allowed by the rules (rev %s)", rules.ConfigRevision())
		}
	}

	return resp, nil
}
898411
func (c *container) inspect(vm *VirtualMachine) error {
	if c.id == "" {
		return nil
	}

	var objects []struct {
		NetworkSettings struct {
			Gateway     string
			IPAddress   string
			IPPrefixLen int
			MacAddress  string
		}
	}

	cmd := exec.Command("docker", "inspect", c.id)
	out, err := cmd.Output()
	if err != nil {
		return err
	}
	if err = json.NewDecoder(bytes.NewReader(out)).Decode(&objects); err != nil {
		return err
	}

	vm.Config.Annotation = strings.Join(cmd.Args, " ")
	vm.logPrintf("%s: %s", vm.Config.Annotation, string(out))

	for _, o := range objects {
		s := o.NetworkSettings
		if s.IPAddress == "" {
			continue
		}

		vm.Guest.IpAddress = s.IPAddress
		vm.Summary.Guest.IpAddress = s.IPAddress

		if len(vm.Guest.Net) != 0 {
			net := &vm.Guest.Net[0]
			net.IpAddress = []string{s.IPAddress}
			net.MacAddress = s.MacAddress
		}
	}

	return nil
}
622361
func (inspector InspectorFunc) Inspect(ctx context.Context, p proto.Message) error {
	return inspector(ctx, p)
}
142330
func VerifyToken(token string, r *http.Request) error {
	realToken, err := ExtractTokenFromCookie(r)
	if err != nil {
		return trace.Wrap(err, "unable to extract CSRF token from cookie")
	}

	decodedTokenA, err := decode(token)
	if err != nil {
		return trace.Wrap(err, "unable to decode CSRF token")
	}

	decodedTokenB, err := decode(realToken)
	if err != nil {
		return trace.Wrap(err, "unable to decode cookie CSRF token")
	}

	if !compareTokens(decodedTokenA, decodedTokenB) {
		return trace.BadParameter("CSRF tokens do not match")
	}

	return nil
}
32496
func (m *Machine) EncodeToken(ctx context.Context, notifier *observer.Notifier,
	token *envelope.MachineToken) error {

	n := notifier.Notifier(2)

	n.Notify(observer.Progress, "Creating keyring memberships for token", true)

	v1members, v2members, err := createKeyringMemberships(ctx, m.engine.crypto,
		m.engine.client, m.engine.session, token.Body.OrgID, token.ID)
	if err != nil {
		return err
	}

	n.Notify(observer.Progress, "Uploading keyring memberships", true)

	if len(v1members) != 0 {
		_, err = m.engine.client.KeyringMember.Post(ctx, v1members)
		if err != nil {
			log.Printf("error uploading memberships: %s", err)
			return err
		}
	}

	for _, member := range v2members {
		err = m.engine.client.Keyring.Members.Post(ctx, member)
		if err != nil {
			log.Printf("error uploading memberships: %s", err)
			return err
		}
	}

	return nil
}
261848
func ProbeAuthScheme(r *http.Request) (string, error) {
	_, tokenErr := GetToken(r)
	_, sessErr := decodeCookieSession(r.Context(), r)

	if tokenErr != nil && sessErr != nil {
		return "", fmt.Errorf("token required")
	}

	if tokenErr == nil {
		return tokenAuthScheme, nil
	}

	return sessionAuthScheme, nil
}