333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
 
const debug = require('debug')('ali-oss:sts');
const crypto = require('crypto');
const querystring = require('querystring');
const copy = require('copy-to');
const AgentKeepalive = require('agentkeepalive');
const is = require('is-type-of');
const ms = require('humanize-ms');
const urllib = require('urllib');
 
const globalHttpAgent = new AgentKeepalive();
 
 
function STS(options) {
  if (!(this instanceof STS)) {
    return new STS(options);
  }
 
  if (!options
    || !options.accessKeyId
    || !options.accessKeySecret) {
    throw new Error('require accessKeyId, accessKeySecret');
  }
 
  this.options = {
    endpoint: options.endpoint || 'https://sts.aliyuncs.com',
    format: 'JSON',
    apiVersion: '2015-04-01',
    sigMethod: 'HMAC-SHA1',
    sigVersion: '1.0',
    timeout: '60s'
  };
  copy(options).to(this.options);
 
  // support custom agent and urllib client
  if (this.options.urllib) {
    this.urllib = this.options.urllib;
  } else {
    this.urllib = urllib;
    this.agent = this.options.agent || globalHttpAgent;
  }
}
 
module.exports = STS;
 
const proto = STS.prototype;
 
/**
 * STS opertaions
 */
 
proto.assumeRole = async function assumeRole(role, policy, expiration, session, options) {
  const opts = this.options;
  const params = {
    Action: 'AssumeRole',
    RoleArn: role,
    RoleSessionName: session || 'app',
    DurationSeconds: expiration || 3600,
 
    Format: opts.format,
    Version: opts.apiVersion,
    AccessKeyId: opts.accessKeyId,
    SignatureMethod: opts.sigMethod,
    SignatureVersion: opts.sigVersion,
    SignatureNonce: Math.random(),
    Timestamp: new Date().toISOString()
  };
 
  if (policy) {
    let policyStr;
    if (is.string(policy)) {
      try {
        policyStr = JSON.stringify(JSON.parse(policy));
      } catch (err) {
        throw new Error(`Policy string is not a valid JSON: ${err.message}`);
      }
    } else {
      policyStr = JSON.stringify(policy);
    }
    params.Policy = policyStr;
  }
 
  const signature = this._getSignature('POST', params, opts.accessKeySecret);
  params.Signature = signature;
 
  const reqUrl = opts.endpoint;
  const reqParams = {
    agent: this.agent,
    timeout: ms((options && options.timeout) || opts.timeout),
    method: 'POST',
    content: querystring.stringify(params),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    ctx: options && options.ctx
  };
 
  const result = await this.urllib.request(reqUrl, reqParams);
  debug(
    'response %s %s, got %s, headers: %j',
    reqParams.method, reqUrl, result.status, result.headers,
  );
 
  if (Math.floor(result.status / 100) !== 2) {
    const err = await this._requestError(result);
    err.params = reqParams;
    throw err;
  }
  result.data = JSON.parse(result.data);
 
  return {
    res: result.res,
    credentials: result.data.Credentials
  };
};
 
proto._requestError = async function _requestError(result) {
  const err = new Error();
  err.status = result.status;
 
  try {
    const resp = await JSON.parse(result.data) || {};
    err.code = resp.Code;
    err.message = `${resp.Code}: ${resp.Message}`;
    err.requestId = resp.RequestId;
  } catch (e) {
    err.message = `UnknownError: ${String(result.data)}`;
  }
 
  return err;
};
 
proto._getSignature = function _getSignature(method, params, key) {
  const that = this;
  const canoQuery = Object.keys(params).sort().map(k => `${that._escape(k)}=${that._escape(params[k])}`).join('&');
 
  const stringToSign =
      `${method.toUpperCase()
      }&${this._escape('/')
      }&${this._escape(canoQuery)}`;
 
  debug('string to sign: %s', stringToSign);
 
  let signature = crypto.createHmac('sha1', `${key}&`);
  signature = signature.update(stringToSign).digest('base64');
 
  debug('signature: %s', signature);
 
  return signature;
};
 
/**
 * Since `encodeURIComponent` doesn't encode '*', which causes
 * 'SignatureDoesNotMatch'. We need do it ourselves.
 */
proto._escape = function _escape(str) {
  return encodeURIComponent(str).replace(/\*/g, '%2A');
};