1// +build !go1.13
2
3// Copyright 2017 Microsoft Corporation
4//
5//  Licensed under the Apache License, Version 2.0 (the "License");
6//  you may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at
8//
9//      http://www.apache.org/licenses/LICENSE-2.0
10//
11//  Unless required by applicable law or agreed to in writing, software
12//  distributed under the License is distributed on an "AS IS" BASIS,
13//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14//  See the License for the specific language governing permissions and
15//  limitations under the License.
16
17package adal
18
19import (
20	"context"
21	"net/http"
22	"time"
23)
24
25func getMSIEndpoint(ctx context.Context, sender Sender) (*http.Response, error) {
26	tempCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
27	defer cancel()
28	req, _ := http.NewRequest(http.MethodGet, msiEndpoint, nil)
29	req = req.WithContext(tempCtx)
30	q := req.URL.Query()
31	q.Add("api-version", msiAPIVersion)
32	req.URL.RawQuery = q.Encode()
33	return sender.Do(req)
34}
35
36// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by
37// RefreshWithin) and autoRefresh flag is on.  This method is safe for concurrent use.
38func (mt *MultiTenantServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error {
39	if err := mt.PrimaryToken.EnsureFreshWithContext(ctx); err != nil {
40		return err
41	}
42	for _, aux := range mt.AuxiliaryTokens {
43		if err := aux.EnsureFreshWithContext(ctx); err != nil {
44			return err
45		}
46	}
47	return nil
48}
49
50// RefreshWithContext obtains a fresh token for the Service Principal.
51func (mt *MultiTenantServicePrincipalToken) RefreshWithContext(ctx context.Context) error {
52	if err := mt.PrimaryToken.RefreshWithContext(ctx); err != nil {
53		return err
54	}
55	for _, aux := range mt.AuxiliaryTokens {
56		if err := aux.RefreshWithContext(ctx); err != nil {
57			return err
58		}
59	}
60	return nil
61}
62
63// RefreshExchangeWithContext refreshes the token, but for a different resource.
64func (mt *MultiTenantServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error {
65	if err := mt.PrimaryToken.RefreshExchangeWithContext(ctx, resource); err != nil {
66		return err
67	}
68	for _, aux := range mt.AuxiliaryTokens {
69		if err := aux.RefreshExchangeWithContext(ctx, resource); err != nil {
70			return err
71		}
72	}
73	return nil
74}
75