// InspectMachineToken decodes a machine token and verifies it is valid.
548144
func (r *InspectMachineTokenRPC) InspectMachineToken(c context.Context, req *admin.InspectMachineTokenRequest) (*admin.InspectMachineTokenResponse, error) {
	// Defaults.
	if req.TokenType == 0 {
		req.TokenType = tokenserver.MachineTokenType_LUCI_MACHINE_TOKEN
	}

	// Only LUCI_MACHINE_TOKEN is supported currently.
	switch req.TokenType {
	case tokenserver.MachineTokenType_LUCI_MACHINE_TOKEN:
		// supported
	default:
		return nil, status.Errorf(codes.InvalidArgument, "unsupported token type %s", req.TokenType)
	}

	// Deserialize the token, check its signature.
	inspection, err := InspectToken(c, r.Signer, req.Token)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}
	resp := &admin.InspectMachineTokenResponse{
		Signed:           inspection.Signed,
		NonExpired:       inspection.NonExpired,
		InvalidityReason: inspection.InvalidityReason,
	}

	// Grab the signing key from the envelope, if managed to deserialize it.
	if env, _ := inspection.Envelope.(*tokenserver.MachineTokenEnvelope); env != nil {
		resp.SigningKeyId = env.KeyId
	}

	// If we could not deserialize the body, that's all checks we could do.
	body, _ := inspection.Body.(*tokenserver.MachineTokenBody)
	if body == nil {
		return resp, nil
	}
	resp.TokenType = &admin.InspectMachineTokenResponse_LuciMachineToken{
		LuciMachineToken: body,
	}

	addReason := func(r string) {
		if resp.InvalidityReason == "" {
			resp.InvalidityReason = r
		} else {
			resp.InvalidityReason += "; " + r
		}
	}

	// Check revocation status. Find CA name that signed the certificate used when
	// minting the token.
	caName, err := certconfig.GetCAByUniqueID(c, body.CaId)
	switch {
	case err != nil:
		return nil, status.Errorf(codes.Internal, "can't resolve ca_id to CA name - %s", err)
	case caName == "":
		addReason("no CA with given ID")
		return resp, nil
	}
	resp.CertCaName = caName

	// Grab CertChecker for this CA. It has CRL cached.
	certChecker, err := certchecker.GetCertChecker(c, caName)
	switch {
	case transient.Tag.In(err):
		return nil, status.Errorf(codes.Internal, "can't fetch CRL - %s", err)
	case err != nil:
		addReason(fmt.Sprintf("can't fetch CRL - %s", err))
		return resp, nil
	}

	// Check that certificate SN is not in the revocation list.
	sn := big.NewInt(0).SetUint64(body.CertSn)
	revoked, err := certChecker.CRL.IsRevokedSN(c, sn)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "can't check CRL - %s", err)
	}
	resp.NonRevoked = !revoked

	// Note: if Signed or NonExpired is false, InvalidityReason is already set.
	if resp.Signed && resp.NonExpired {
		if resp.NonRevoked {
			resp.Valid = true
		} else {
			addReason("corresponding cert was revoked")
		}
	}

	return resp, nil
}
1370752
func (task *provisionerTask) markMachineFailedInAZ(machine apiprovisioner.MachineProvisioner, zone string) (bool, error) {
	if zone == "" {
		return false, errors.New("no zone provided")
	}
	task.machinesMutex.Lock()
	defer task.machinesMutex.Unlock()
	azRemaining := false
	for _, zoneMachines := range task.availabilityZoneMachines {
		if zone == zoneMachines.ZoneName {
			zoneMachines.MachineIds.Remove(machine.Id())
			zoneMachines.FailedMachineIds.Add(machine.Id())
			if azRemaining {
				break
			}
		}
		if !zoneMachines.FailedMachineIds.Contains(machine.Id()) &&
			!zoneMachines.ExcludedMachineIds.Contains(machine.Id()) {
			azRemaining = true
		}
	}
	return azRemaining, nil
}
412270
func decodeToken(encoded string) *oauth2.Token {
	t := new(oauth2.Token)
	f := strings.Fields(encoded)
	if len(f) > 0 {
		t.AccessToken = f[0]
	}
	if len(f) > 1 {
		t.RefreshToken = f[1]
	}
	if len(f) > 2 && f[2] != "0" {
		sec, err := strconv.ParseInt(f[2], 10, 64)
		if err == nil {
			t.Expiry = time.Unix(sec, 0)
		}
	}
	return t
}
91767
func (m *API) WatchMachineRemovals(models params.Entities) params.NotifyWatchResults {
	results := make([]params.NotifyWatchResult, len(models.Entities))
	for i, entity := range models.Entities {
		id, err := m.watchRemovalsForTag(entity.Tag)
		results[i].NotifyWatcherId = id
		results[i].Error = common.ServerError(err)
	}
	return params.NotifyWatchResults{Results: results}
}
187429
func (m *MockModelCache) WatchMachines() (cache.StringsWatcher, error) {
	ret := m.ctrl.Call(m, "WatchMachines")
	ret0, _ := ret[0].(cache.StringsWatcher)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
158646
func (g *globTokeniser) PeekToken() (token string, tokenType tc) {
	return g.peekToken, g.peekTokenType
}
95277
func VerifyToken(realToken, sentToken string) bool {
	r := b64decode(realToken)
	if len(r) == 2*tokenLength {
		r = unmaskToken(r)
	}
	s := b64decode(sentToken)
	if len(s) == 2*tokenLength {
		s = unmaskToken(s)
	}
	return subtle.ConstantTimeCompare(r, s) == 1
}
368643
func (c *ServiceWorker) InspectWorker(versionId string) (*gcdmessage.ChromeResponse, error) {
	var v ServiceWorkerInspectWorkerParams
	v.VersionId = versionId
	return c.InspectWorkerWithParams(&v)
}
969417
func (c *Client) GetMachine(machineID string) (*Machine, error) {
	var resp Machine
	req := request{
		method: client.GET,
		url:    makeURL(apiMachines, machineID),
		resp:   &resp,
	}
	if _, err := c.sendRequest(req); err != nil {
		return nil, errors.Newf(err, "failed to get machine with id: %s", machineID)
	}
	return &resp, nil
}
811351
func (r *renderer) visitToken(t markdown.Token) string {
	switch t.(type) {
	case *markdown.ParagraphOpen:
		r.inParagraph = true
		return ""
	case *markdown.ParagraphClose:
		r.inParagraph = false
		return "\n"
	case *markdown.CodeBlock:
		return fmt.Sprintf("\n%s\n", indent(t.(*markdown.CodeBlock).Content, 2))
	case *markdown.Fence:
		return fmt.Sprintf("\n%s\n", indent(t.(*markdown.Fence).Content, 2))
	case *markdown.HeadingOpen:
		n := t.(*markdown.HeadingOpen).HLevel
		return fmt.Sprintf("\n  %s \033[%dm", strings.Repeat("#", n), colors.Blue)
	case *markdown.HeadingClose:
		return "\n\033[0m\n"
	case *markdown.StrongOpen:
		return "\033[1m"
	case *markdown.StrongClose:
		return "\033[0m"
	case *markdown.BulletListOpen:
		r.inList = true
		return "\n"
	case *markdown.BulletListClose:
		r.inList = false
		return "\n"
	case *markdown.ListItemOpen:
		return "  - "
	case *markdown.LinkOpen:
		r.inLink = t.(*markdown.LinkOpen).Href
		return ""
	case *markdown.CodeInline:
		s := t.(*markdown.CodeInline).Content
		return fmt.Sprintf("\033[%dm%s\033[0m", colors.Gray, s)
	case *markdown.Text:
		s := t.(*markdown.Text).Content

		if r.inLink != "" {
			s = fmt.Sprintf("%s (%s)", s, r.inLink)
			r.inLink = ""
		}

		return s
	case *markdown.Inline:
		s := r.visit(t.(*markdown.Inline).Children)

		if r.inParagraph && !r.inList {
			s = indent(wordwrap.WrapString(s, 75), 1)
		}

		return s
	default:
		return ""
	}
}
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
}
1088517
func (e *ModelMachinesWatcher) WatchModelMachines() (params.StringsWatchResult, error) {
	result := params.StringsWatchResult{}
	if !e.authorizer.AuthController() {
		return result, ErrPerm
	}
	watch := e.st.WatchModelMachines()
	// Consume the initial event and forward it to the result.
	if changes, ok := <-watch.Changes(); ok {
		result.StringsWatcherId = e.resources.Register(watch)
		result.Changes = changes
	} else {
		err := watcher.EnsureErr(watch)
		return result, fmt.Errorf("cannot obtain initial model machines: %v", err)
	}
	return result, nil
}
1059376
func CheckToken(c context.Context, params CheckTokenParams) (identity.Identity, error) {
	// base64-encoded token -> DelegationToken proto (with signed serialized
	// subtoken).
	tok, err := deserializeToken(params.Token)
	if err != nil {
		logging.Warningf(c, "auth: Failed to deserialize delegation token - %s", err)
		return "", ErrMalformedDelegationToken
	}

	// Signed serialized subtoken -> Subtoken proto.
	subtoken, err := unsealToken(c, tok, params.CertificatesProvider)
	if err != nil {
		if transient.Tag.In(err) {
			logging.Warningf(c, "auth: Transient error when checking delegation token signature - %s", err)
			return "", err
		}
		logging.Warningf(c, "auth: Failed to check delegation token signature - %s", err)
		return "", ErrUnsignedDelegationToken
	}

	// Validate all constrains encoded in the token and derive the delegated
	// identity.
	return checkSubtoken(c, subtoken, &params)
}
1284834
func InspectImage(ctx context.Context, client client.ImageAPIClient, image string) (types.ImageInspect, error) {
	imageInspect, _, err := client.ImageInspectWithRaw(ctx, image)
	return imageInspect, err
}
1338396
func (api *InstanceMutaterAPI) WatchMachines() (params.StringsWatchResult, error) {
	result := params.StringsWatchResult{}
	if !api.authorizer.AuthController() {
		return result, common.ErrPerm
	}

	watch, err := api.model.WatchMachines()
	if err != nil {
		return result, err
	}
	if changes, ok := <-watch.Changes(); ok {
		result.StringsWatcherId = api.resources.Register(watch)
		result.Changes = changes
	} else {
		return result, errors.Errorf("cannot obtain initial model machines")
	}
	return result, nil
}
255353
func InspectToken(c context.Context, certs tokensigning.CertificatesSupplier, tok string) (*tokensigning.Inspection, error) {
	i := tokensigning.Inspector{
		Certificates:   certs,
		SigningContext: tokenSigningContext,
		Envelope:       func() proto.Message { return &messages.DelegationToken{} },
		Body:           func() proto.Message { return &messages.Subtoken{} },
		Unwrap: func(e proto.Message) tokensigning.Unwrapped {
			env := e.(*messages.DelegationToken)
			return tokensigning.Unwrapped{
				Body:         env.SerializedSubtoken,
				RsaSHA256Sig: env.Pkcs1Sha256Sig,
				KeyID:        env.SigningKeyId,
			}
		},
		Lifespan: func(b proto.Message) tokensigning.Lifespan {
			body := b.(*messages.Subtoken)
			return tokensigning.Lifespan{
				NotBefore: time.Unix(body.CreationTime, 0),
				NotAfter:  time.Unix(body.CreationTime+int64(body.ValidityDuration), 0),
			}
		},
	}
	return i.InspectToken(c, tok)
}
1131900
func (session *Session) Inspect() (result Result, err error) {
	if session.accessToken == "" && session.HttpClient == nil {
		err = fmt.Errorf("access token is not set")
		return
	}

	if session.app == nil {
		err = fmt.Errorf("cannot inspect access token without binding an app")
		return
	}

	appAccessToken := session.app.AppAccessToken()

	if appAccessToken == "" {
		err = fmt.Errorf("app access token is not set")
		return
	}

	result, err = session.Api("/debug_token", GET, Params{
		"input_token":  session.accessToken,
		"access_token": appAccessToken,
	})

	if err != nil {
		return
	}

	// facebook stores everything, including error, inside result["data"].
	// make sure that result["data"] exists and doesn't contain error.
	if _, ok := result["data"]; !ok {
		err = fmt.Errorf("facebook inspect api returns unexpected result")
		return
	}

	var data Result
	result.DecodeField("data", &data)
	result = data
	err = result.Err()
	return
}